Restore damage calc for some paladin seal after client switch
[getmangos.git] / src / game / Unit.cpp
blobe4b8a9729d0bd1f58ecd13a7ad8433787e8497e4
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"
47 #include <math.h>
49 float baseMoveSpeed[MAX_MOVE_TYPE] =
51 2.5f, // MOVE_WALK
52 7.0f, // MOVE_RUN
53 1.25f, // MOVE_RUN_BACK
54 4.722222f, // MOVE_SWIM
55 4.5f, // MOVE_SWIM_BACK
56 3.141594f, // MOVE_TURN_RATE
57 7.0f, // MOVE_FLIGHT
58 4.5f, // MOVE_FLIGHT_BACK
59 3.14f // MOVE_PITCH_RATE
62 // Used for prepare can/can`t triggr aura
63 static bool InitTriggerAuraData();
64 // Define can trigger auras
65 static bool isTriggerAura[TOTAL_AURAS];
66 // Define can`t trigger auras (need for disable second trigger)
67 static bool isNonTriggerAura[TOTAL_AURAS];
68 // Prepare lists
69 static bool procPrepared = InitTriggerAuraData();
71 Unit::Unit()
72 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
74 m_objectType |= TYPEMASK_UNIT;
75 m_objectTypeId = TYPEID_UNIT;
76 // 2.3.2 - 0x70
77 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
79 m_attackTimer[BASE_ATTACK] = 0;
80 m_attackTimer[OFF_ATTACK] = 0;
81 m_attackTimer[RANGED_ATTACK] = 0;
82 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
83 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
84 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
86 m_extraAttacks = 0;
88 m_state = 0;
89 m_form = FORM_NONE;
90 m_deathState = ALIVE;
92 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
93 m_currentSpells[i] = NULL;
95 m_addDmgOnce = 0;
97 for(int i = 0; i < MAX_TOTEM; ++i)
98 m_TotemSlot[i] = 0;
100 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
101 //m_Aura = NULL;
102 //m_AurasCheck = 2000;
103 //m_removeAuraTimer = 4;
104 //tmpAura = NULL;
105 waterbreath = false;
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 < 3; 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, GetUnitMovementFlags(), 0, player);
239 void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 MovementFlags, uint32 transitTime, Player* player)
241 if (!transitTime)
243 float dx = x - GetPositionX();
244 float dy = y - GetPositionY();
245 float dz = z - GetPositionZ();
247 float dist = ((dx*dx) + (dy*dy) + (dz*dz));
248 if(dist<0)
249 dist = 0;
250 else
251 dist = sqrt(dist);
253 double speed = GetSpeed((MovementFlags & MOVEMENTFLAG_WALK_MODE) ? MOVE_WALK : MOVE_RUN);
254 if(speed<=0)
255 speed = 2.5f;
256 speed *= 0.001f;
257 transitTime = static_cast<uint32>(dist / speed + 0.5);
259 //float orientation = (float)atan2((double)dy, (double)dx);
260 SendMonsterMove(x, y, z, 0, MovementFlags, transitTime, player);
263 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player)
265 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
266 data.append(GetPackGUID());
268 // Point A, starting location
269 data << GetPositionX() << GetPositionY() << GetPositionZ();
270 // unknown field - unrelated to orientation
271 // seems to increment about 1000 for every 1.7 seconds
272 // for now, we'll just use mstime
273 data << getMSTime();
275 data << uint8(type); // unknown
276 switch(type)
278 case 0: // normal packet
279 break;
280 case 1: // stop packet
281 SendMessageToSet( &data, true );
282 return;
283 case 2: // not used currently
284 data << float(0);
285 data << float(0);
286 data << float(0);
287 break;
288 case 3: // not used currently
289 data << uint64(0); // probably target guid
290 break;
291 case 4: // not used currently
292 data << float(0); // probably orientation
293 break;
296 //Movement Flags (0x0 = walk, 0x100 = run, 0x200 = fly/swim)
297 data << uint32(MovementFlags);
299 data << Time; // Time in between points
300 data << uint32(1); // 1 single waypoint
301 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
303 if(player)
304 player->GetSession()->SendPacket(&data);
305 else
306 SendMessageToSet( &data, true );
309 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, uint32 MovementFlags)
311 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
313 uint32 pathSize = end-start;
315 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+4+4+4+4+1+4+4+4+pathSize*4*3) );
316 data.append(GetPackGUID());
317 data << GetPositionX();
318 data << GetPositionY();
319 data << GetPositionZ();
321 // unknown field - unrelated to orientation
322 // seems to increment about 1000 for every 1.7 seconds
323 // for now, we'll just use mstime
324 data << getMSTime();
326 data << uint8( 0 );
327 data << uint32( MovementFlags );
328 data << uint32( traveltime );
329 data << uint32( pathSize );
330 data.append( (char*)path.GetNodes(start), pathSize * 4 * 3 );
332 //WPAssert( data.size() == 37 + pathnodes.Size( ) * 4 * 3 );
333 SendMessageToSet(&data, true);
336 void Unit::resetAttackTimer(WeaponAttackType type)
338 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
341 bool Unit::canReachWithAttack(Unit *pVictim) const
343 assert(pVictim);
344 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
345 if( reach <= 0.0f )
346 reach = 1.0f;
347 return IsWithinDistInMap(pVictim, reach);
350 void Unit::RemoveSpellsCausingAura(AuraType auraType)
352 if (auraType >= TOTAL_AURAS) return;
353 AuraList::iterator iter, next;
354 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
356 next = iter;
357 ++next;
359 if (*iter)
361 RemoveAurasDueToSpell((*iter)->GetId());
362 if (!m_modAuras[auraType].empty())
363 next = m_modAuras[auraType].begin();
364 else
365 return;
370 bool Unit::HasAuraType(AuraType auraType) const
372 return (!m_modAuras[auraType].empty());
375 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
376 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
378 if(!HasAuraType(auraType))
379 return;
381 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
382 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
383 float chance = float(damage) / max_dmg * 100.0f;
384 if (roll_chance_f(chance))
385 RemoveSpellsCausingAura(auraType);
388 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
390 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
391 return 0;
393 //You don't lose health from damage taken from another player while in a sanctuary
394 //You still see it in the combat log though
395 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
397 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
398 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
399 return 0;
402 // remove affects from victim (including from 0 damage and DoTs)
403 if(pVictim != this)
404 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
406 // remove affects from attacker at any non-DoT damage (including 0 damage)
407 if( damagetype != DOT)
409 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
410 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
412 if(pVictim != this)
413 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
415 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
416 pVictim->SetStandState(PLAYER_STATE_NONE);
419 //Script Event damage Deal
420 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
421 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
422 //Script Event damage taken
423 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
424 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
426 if(!damage)
428 // Rage from physical damage received .
429 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
430 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
432 return 0;
434 if (!spellProto || !IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR, spellProto->Id))
435 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
436 // root type spells do not dispel the root effect
437 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT, spellProto->Id)))
438 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
440 if(pVictim->GetTypeId() != TYPEID_PLAYER)
442 // no xp,health if type 8 /critters/
443 if ( pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
445 pVictim->setDeathState(JUST_DIED);
446 pVictim->SetHealth(0);
448 // allow loot only if has loot_id in creature_template
449 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
450 if(cInfo && cInfo->lootid)
451 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
453 // some critters required for quests
454 if(GetTypeId() == TYPEID_PLAYER)
455 ((Player*)this)->KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
457 return damage;
460 if(!pVictim->isInCombat() && ((Creature*)pVictim)->AI())
461 ((Creature*)pVictim)->AI()->AttackStart(this);
464 DEBUG_LOG("DealDamageStart");
466 uint32 health = pVictim->GetHealth();
467 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
469 // duel ends when player has 1 or less hp
470 bool duel_hasEnded = false;
471 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
473 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
474 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
475 damage = health-1;
477 duel_hasEnded = true;
479 //Get in CombatState
480 if(pVictim != this && damagetype != DOT)
482 SetInCombatWith(pVictim);
483 pVictim->SetInCombatWith(this);
485 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
486 SetContestedPvP(attackedPlayer);
489 // Rage from Damage made (only from direct weapon damage)
490 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
492 uint32 weaponSpeedHitFactor;
494 switch(cleanDamage->attackType)
496 case BASE_ATTACK:
498 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
499 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
500 else
501 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
503 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
505 break;
507 case OFF_ATTACK:
509 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
510 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
511 else
512 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
514 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
516 break;
518 case RANGED_ATTACK:
519 break;
523 if(pVictim->GetTypeId() == TYPEID_PLAYER && GetTypeId() == TYPEID_PLAYER)
525 if(((Player*)pVictim)->InBattleGround())
527 Player *killer = ((Player*)this);
528 if(killer != ((Player*)pVictim))
529 if(BattleGround *bg = killer->GetBattleGround())
530 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
534 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
535 ((Creature*)pVictim)->SetLootRecipient(this);
536 if (health <= damage)
538 DEBUG_LOG("DealDamage: victim just died");
540 // find player: owner of controlled `this` or `this` itself maybe
541 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
543 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
544 player = ((Creature*)pVictim)->GetLootRecipient();
545 // Reward player, his pets, and group/raid members
546 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
547 if(player && player!=pVictim)
549 player->RewardPlayerAndGroupAtKill(pVictim);
550 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
553 DEBUG_LOG("DealDamageAttackStop");
555 // stop combat
556 pVictim->CombatStop();
557 pVictim->getHostilRefManager().deleteReferences();
559 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
561 // if talent known but not triggered (check priest class for speedup check)
562 Aura* spiritOfRedemtionTalentReady = NULL;
563 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
564 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
566 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
567 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
569 if((*itr)->GetSpellProto()->SpellIconID==1654)
571 spiritOfRedemtionTalentReady = *itr;
572 break;
577 DEBUG_LOG("SET JUST_DIED");
578 if(!spiritOfRedemtionTalentReady)
579 pVictim->setDeathState(JUST_DIED);
581 DEBUG_LOG("DealDamageHealth1");
583 if(spiritOfRedemtionTalentReady)
585 // save value before aura remove
586 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
587 if(!ressSpellId)
588 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
590 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
591 pVictim->RemoveAllAurasOnDeath();
593 // restore for use at real death
594 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
596 // FORM_SPIRITOFREDEMPTION and related auras
597 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
599 else
600 pVictim->SetHealth(0);
602 // remember victim PvP death for corpse type and corpse reclaim delay
603 // at original death (not at SpiritOfRedemtionTalent timeout)
604 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
605 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
607 // Call KilledUnit for creatures
608 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
609 ((Creature*)this)->AI()->KilledUnit(pVictim);
611 // achievement stuff
612 if ( pVictim->GetTypeId() == TYPEID_PLAYER)
614 if(GetTypeId() == TYPEID_UNIT)
615 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
616 else if(GetTypeId() == TYPEID_PLAYER)
617 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1);
620 // 10% durability loss on death
621 // clean InHateListOf
622 if (pVictim->GetTypeId() == TYPEID_PLAYER)
624 // only if not player and not controlled by player pet. And not at BG
625 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
627 DEBUG_LOG("We are dead, loosing 10 percents durability");
628 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
629 // durability lost message
630 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
631 ((Player*)pVictim)->GetSession()->SendPacket(&data);
634 else // creature died
636 DEBUG_LOG("DealDamageNotPlayer");
637 Creature *cVictim = (Creature*)pVictim;
639 if(!cVictim->isPet())
641 cVictim->DeleteThreatList();
642 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
644 // Call creature just died function
645 if (cVictim->AI())
646 cVictim->AI()->JustDied(this);
648 // Dungeon specific stuff, only applies to players killing creatures
649 if(cVictim->GetInstanceId())
651 Map *m = cVictim->GetMap();
652 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
653 // TODO: do instance binding anyway if the charmer/owner is offline
655 if(m->IsDungeon() && creditedPlayer)
657 if(m->IsRaid() || m->IsHeroic())
659 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
660 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
662 else
664 // the reset time is set but not added to the scheduler
665 // until the players leave the instance
666 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
667 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
668 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
674 // last damage from non duel opponent or opponent controlled creature
675 if(duel_hasEnded)
677 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
678 Player *he = (Player*)pVictim;
680 assert(he->duel);
682 he->duel->opponent->CombatStopWithPets(true);
683 he->CombatStopWithPets(true);
685 he->DuelComplete(DUEL_INTERUPTED);
688 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
689 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
691 Player *killed = ((Player*)pVictim);
692 if(BattleGround *bg = killed->GetBattleGround())
693 if(player)
694 bg->HandleKillPlayer(killed, player);
695 //later we can add support for creature->player kills here i'm
696 //not sure, but i guess those kills also get counted in av
697 //else if(GetTypeId() == TYPEID_UNIT)
698 // bg->HandleKillPlayer(killed,(Creature*)this);
701 else // if (health <= damage)
703 DEBUG_LOG("DealDamageAlive");
705 pVictim->ModifyHealth(- (int32)damage);
707 if(damagetype != DOT)
709 if(getVictim())
711 // if have target and damage pVictim just call AI reaction
712 if(pVictim != getVictim() && pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
713 ((Creature*)pVictim)->AI()->AttackedBy(this);
715 else
717 // if not have main target then attack state with target (including AI call)
718 //start melee attacks only after melee hit
719 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
723 // polymorphed and other negative transformed cases
724 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
725 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
727 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
729 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
730 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
732 if (pVictim->GetTypeId() != TYPEID_PLAYER)
734 if(spellProto && IsDamageToThreatSpell(spellProto))
735 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
736 else
737 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
739 else // victim is a player
741 // Rage from damage received
742 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
744 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
745 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
748 // random durability for items (HIT TAKEN)
749 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
751 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
752 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
756 if(GetTypeId()==TYPEID_PLAYER)
758 // random durability for items (HIT DONE)
759 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
761 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
762 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
766 // TODO: Store auras by interrupt flag to speed this up.
767 AuraMap& vAuras = pVictim->GetAuras();
768 for (AuraMap::iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
770 const SpellEntry *se = i->second->GetSpellProto();
771 next = i; ++next;
772 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
773 continue;
774 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
776 bool remove = true;
777 if (se->procFlags & (1<<3))
779 if (!roll_chance_i(se->procChance))
780 remove = false;
782 if (remove)
784 pVictim->RemoveAurasDueToSpell(i->second->GetId());
785 // FIXME: this may cause the auras with proc chance to be rerolled several times
786 next = vAuras.begin();
791 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
793 if( damagetype != DOT )
795 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
797 // skip channeled spell (processed differently below)
798 if (i == CURRENT_CHANNELED_SPELL)
799 continue;
801 if(Spell* spell = pVictim->m_currentSpells[i])
802 if(spell->getState() == SPELL_STATE_PREPARING)
803 spell->Delayed();
807 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
809 if (spell->getState() == SPELL_STATE_CASTING)
811 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
812 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
814 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
815 spell->DelayedChannel();
817 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
819 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
820 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
823 else if (spell->getState() == SPELL_STATE_DELAYED)
824 // break channeled spell in delayed state on damage
826 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
827 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
832 // last damage from duel opponent
833 if(duel_hasEnded)
835 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
836 Player *he = (Player*)pVictim;
838 assert(he->duel);
840 he->SetHealth(1);
842 he->duel->opponent->CombatStopWithPets(true);
843 he->CombatStopWithPets(true);
845 he->CastSpell(he, 7267, true); // beg
846 he->DuelComplete(DUEL_WON);
850 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
852 return damage;
855 void Unit::CastStop(uint32 except_spellid)
857 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
858 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
859 InterruptSpell(i,false);
862 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
864 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
866 if(!spellInfo)
868 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
869 return;
872 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
875 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
877 if(!spellInfo)
879 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
880 return;
883 if (castItem)
884 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
886 if(!originalCaster && triggeredByAura)
887 originalCaster = triggeredByAura->GetCasterGUID();
889 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
891 SpellCastTargets targets;
892 targets.setUnitTarget( Victim );
893 spell->m_CastItem = castItem;
894 spell->prepare(&targets, triggeredByAura);
897 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
899 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
901 if(!spellInfo)
903 sLog.outError("CastCustomSpell: unknown spell id %i\n", spellId);
904 return;
907 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
910 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)
912 if(!spellInfo)
914 sLog.outError("CastCustomSpell: unknown spell");
915 return;
918 if (castItem)
919 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
921 if(!originalCaster && triggeredByAura)
922 originalCaster = triggeredByAura->GetCasterGUID();
924 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
926 if(bp0)
927 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
929 if(bp1)
930 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
932 if(bp2)
933 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
935 SpellCastTargets targets;
936 targets.setUnitTarget( Victim );
937 spell->m_CastItem = castItem;
938 spell->prepare(&targets, triggeredByAura);
941 // used for scripting
942 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
944 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
946 if(!spellInfo)
948 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()));
949 return;
952 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
955 // used for scripting
956 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
958 if(!spellInfo)
960 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
961 return;
964 if (castItem)
965 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
967 if(!originalCaster && triggeredByAura)
968 originalCaster = triggeredByAura->GetCasterGUID();
970 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
972 SpellCastTargets targets;
973 targets.setDestination(x, y, z);
974 spell->m_CastItem = castItem;
975 spell->prepare(&targets, triggeredByAura);
978 // Obsolete func need remove, here only for comotability vs another patches
979 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
981 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
982 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
983 CalculateSpellDamage(&damageInfo, damage, spellInfo);
984 SendSpellNonMeleeDamageLog(&damageInfo);
985 DealSpellDamage(&damageInfo, true);
986 return damageInfo.damage;
989 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
991 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
992 Unit *pVictim = damageInfo->target;
994 if (damage < 0)
995 return;
997 if(!this || !pVictim)
998 return;
999 if(!this->isAlive() || !pVictim->isAlive())
1000 return;
1002 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1003 // Check spell crit chance
1004 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1005 bool blocked = false;
1006 // Per-school calc
1007 switch (spellInfo->DmgClass)
1009 // Melee and Ranged Spells
1010 case SPELL_DAMAGE_CLASS_RANGED:
1011 case SPELL_DAMAGE_CLASS_MELEE:
1013 // Physical Damage
1014 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1016 //Calculate armor mitigation
1017 damage = CalcArmorReducedDamage(pVictim, damage);
1018 // Get blocked status
1019 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1021 // Magical Damage
1022 else
1024 // Calculate damage bonus
1025 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1027 if (crit)
1029 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1031 // Calculate crit bonus
1032 uint32 crit_bonus = damage;
1033 // Apply crit_damage bonus for melee spells
1034 if(Player* modOwner = GetSpellModOwner())
1035 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1036 damage += crit_bonus;
1038 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1039 int32 critPctDamageMod=0;
1040 if(attackType == RANGED_ATTACK)
1041 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1042 else
1044 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1045 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1047 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1048 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1050 if (critPctDamageMod!=0)
1051 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1053 // Resilience - reduce crit damage
1054 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1055 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1057 // Spell weapon based damage CAN BE crit & blocked at same time
1058 if (blocked)
1060 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1061 if (damage < damageInfo->blocked)
1062 damageInfo->blocked = damage;
1063 damage-=damageInfo->blocked;
1066 break;
1067 // Magical Attacks
1068 case SPELL_DAMAGE_CLASS_NONE:
1069 case SPELL_DAMAGE_CLASS_MAGIC:
1071 // Calculate damage bonus
1072 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1073 // If crit add critical bonus
1074 if (crit)
1076 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1077 damage = SpellCriticalBonus(spellInfo, damage, pVictim);
1078 // Resilience - reduce crit damage
1079 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1080 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1083 break;
1086 // Calculate absorb resist
1087 if(damage > 0)
1089 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1090 damage-= damageInfo->absorb + damageInfo->resist;
1092 else
1093 damage = 0;
1094 damageInfo->damage = damage;
1097 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1099 if (damageInfo==0)
1100 return;
1102 Unit *pVictim = damageInfo->target;
1104 if(!this || !pVictim)
1105 return;
1107 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1108 return;
1110 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1111 if (spellProto == NULL)
1113 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1114 return;
1117 //You don't lose health from damage taken from another player while in a sanctuary
1118 //You still see it in the combat log though
1119 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1121 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1122 if(area && area->flags & 0x800) //sanctuary
1123 return;
1126 // update at damage Judgement aura duration that applied by attacker at victim
1127 if(damageInfo->damage && spellProto->Id == 35395)
1129 AuraMap& vAuras = pVictim->GetAuras();
1130 for(AuraMap::iterator itr = vAuras.begin(); itr != vAuras.end(); ++itr)
1132 SpellEntry const *spellInfo = (*itr).second->GetSpellProto();
1133 if( spellInfo->AttributesEx3 & 0x40000 && spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && ((*itr).second->GetCasterGUID() == GetGUID()))
1135 (*itr).second->SetAuraDuration((*itr).second->GetAuraMaxDuration());
1136 (*itr).second->SendAuraUpdate(false);
1140 // Call default DealDamage
1141 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1142 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1145 //TODO for melee need create structure as in
1146 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1148 damageInfo->attacker = this;
1149 damageInfo->target = pVictim;
1150 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1151 damageInfo->attackType = attackType;
1152 damageInfo->damage = 0;
1153 damageInfo->cleanDamage = 0;
1154 damageInfo->absorb = 0;
1155 damageInfo->resist = 0;
1156 damageInfo->blocked_amount = 0;
1158 damageInfo->TargetState = 0;
1159 damageInfo->HitInfo = 0;
1160 damageInfo->procAttacker = PROC_FLAG_NONE;
1161 damageInfo->procVictim = PROC_FLAG_NONE;
1162 damageInfo->procEx = PROC_EX_NONE;
1163 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1165 if(!this || !pVictim)
1166 return;
1167 if(!this->isAlive() || !pVictim->isAlive())
1168 return;
1170 // Select HitInfo/procAttacker/procVictim flag based on attack type
1171 switch (attackType)
1173 case BASE_ATTACK:
1174 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1175 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1176 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1177 break;
1178 case OFF_ATTACK:
1179 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1180 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1181 damageInfo->HitInfo = HITINFO_LEFTSWING;
1182 break;
1183 case RANGED_ATTACK:
1184 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1185 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1186 damageInfo->HitInfo = 0x08;// test
1187 break;
1188 default:
1189 break;
1192 // Physical Immune check
1193 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1195 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1196 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1198 damageInfo->procEx |=PROC_EX_IMMUNE;
1199 damageInfo->damage = 0;
1200 damageInfo->cleanDamage = 0;
1201 return;
1203 damage += CalculateDamage (damageInfo->attackType, false);
1204 // Add melee damage bonus
1205 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1206 // Calculate armor reduction
1207 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1208 damageInfo->cleanDamage += damage - damageInfo->damage;
1210 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1212 // Disable parry or dodge for ranged attack
1213 if(damageInfo->attackType == RANGED_ATTACK)
1215 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1216 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1219 switch(damageInfo->hitOutCome)
1221 case MELEE_HIT_EVADE:
1223 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1224 damageInfo->TargetState = VICTIMSTATE_EVADES;
1226 damageInfo->procEx|=PROC_EX_EVADE;
1227 damageInfo->damage = 0;
1228 damageInfo->cleanDamage = 0;
1229 return;
1231 case MELEE_HIT_MISS:
1233 damageInfo->HitInfo |= HITINFO_MISS;
1234 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1236 damageInfo->procEx|=PROC_EX_MISS;
1237 damageInfo->damage = 0;
1238 damageInfo->cleanDamage = 0;
1239 break;
1241 case MELEE_HIT_NORMAL:
1242 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1243 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1244 break;
1245 case MELEE_HIT_CRIT:
1247 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1248 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1250 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1251 // Crit bonus calc
1252 damageInfo->damage += damageInfo->damage;
1253 int32 mod=0;
1254 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1255 if(damageInfo->attackType == RANGED_ATTACK)
1256 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1257 else
1259 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1260 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1263 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1265 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1266 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1267 if (mod!=0)
1268 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1270 // Resilience - reduce crit damage
1271 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1273 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1274 damageInfo->damage -= resilienceReduction;
1275 damageInfo->cleanDamage += resilienceReduction;
1277 break;
1279 case MELEE_HIT_PARRY:
1280 damageInfo->TargetState = VICTIMSTATE_PARRY;
1281 damageInfo->procEx|=PROC_EX_PARRY;
1282 damageInfo->cleanDamage += damageInfo->damage;
1283 damageInfo->damage = 0;
1284 break;
1286 case MELEE_HIT_DODGE:
1287 damageInfo->TargetState = VICTIMSTATE_DODGE;
1288 damageInfo->procEx|=PROC_EX_DODGE;
1289 damageInfo->cleanDamage += damageInfo->damage;
1290 damageInfo->damage = 0;
1291 break;
1292 case MELEE_HIT_BLOCK:
1294 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1295 damageInfo->HitInfo |= HITINFO_BLOCK;
1296 damageInfo->procEx|=PROC_EX_BLOCK;
1297 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1298 if (damageInfo->blocked_amount >= damageInfo->damage)
1300 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1301 damageInfo->blocked_amount = damageInfo->damage;
1303 damageInfo->damage -= damageInfo->blocked_amount;
1304 damageInfo->cleanDamage += damageInfo->blocked_amount;
1305 break;
1307 case MELEE_HIT_GLANCING:
1309 damageInfo->HitInfo |= HITINFO_GLANCING;
1310 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1311 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1312 float reducePercent = 1.0f; //damage factor
1313 // calculate base values and mods
1314 float baseLowEnd = 1.3;
1315 float baseHighEnd = 1.2;
1316 switch(getClass()) // lowering base values for casters
1318 case CLASS_SHAMAN:
1319 case CLASS_PRIEST:
1320 case CLASS_MAGE:
1321 case CLASS_WARLOCK:
1322 case CLASS_DRUID:
1323 baseLowEnd -= 0.7;
1324 baseHighEnd -= 0.3;
1325 break;
1328 float maxLowEnd = 0.6;
1329 switch(getClass()) // upper for melee classes
1331 case CLASS_WARRIOR:
1332 case CLASS_ROGUE:
1333 maxLowEnd = 0.91; //If the attacker is a melee class then instead the lower value of 0.91
1336 // calculate values
1337 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1338 float lowEnd = baseLowEnd - ( 0.05f * diff );
1339 float highEnd = baseHighEnd - ( 0.03f * diff );
1341 // apply max/min bounds
1342 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1343 lowEnd = 0.01f;
1344 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1345 lowEnd = maxLowEnd;
1347 if ( highEnd < 0.2f ) //high end limits
1348 highEnd = 0.2f;
1349 if ( highEnd > 0.99f )
1350 highEnd = 0.99f;
1352 if(lowEnd > highEnd) // prevent negative range size
1353 lowEnd = highEnd;
1355 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1357 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1358 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1359 break;
1361 case MELEE_HIT_CRUSHING:
1363 damageInfo->HitInfo |= HITINFO_CRUSHING;
1364 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1365 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1366 // 150% normal damage
1367 damageInfo->damage += (damageInfo->damage / 2);
1368 break;
1370 default:
1372 break;
1375 // Calculate absorb resist
1376 if(int32(damageInfo->damage) > 0)
1378 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1379 // Calculate absorb & resists
1380 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1381 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1382 if (damageInfo->absorb)
1384 damageInfo->HitInfo|=HITINFO_ABSORB;
1385 damageInfo->procEx|=PROC_EX_ABSORB;
1387 if (damageInfo->resist)
1388 damageInfo->HitInfo|=HITINFO_RESIST;
1391 else // Umpossible get negative result but....
1392 damageInfo->damage = 0;
1395 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1397 if (damageInfo==0) return;
1398 Unit *pVictim = damageInfo->target;
1400 if(!this || !pVictim)
1401 return;
1403 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1404 return;
1406 //You don't lose health from damage taken from another player while in a sanctuary
1407 //You still see it in the combat log though
1408 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1410 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1411 if(area && area->flags & 0x800) //sanctuary
1412 return;
1415 // Hmmmm dont like this emotes cloent must by self do all animations
1416 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1417 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1418 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1419 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1421 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1423 // Get attack timers
1424 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1425 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1426 // Reduce attack time
1427 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1429 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20;
1430 float percent60 = 3 * percent20;
1431 if(offtime > percent20 && offtime <= percent60)
1433 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1435 else if(offtime > percent60)
1437 offtime -= 2 * percent20;
1438 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1441 else
1443 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1444 float percent60 = 3 * percent20;
1445 if(basetime > percent20 && basetime <= percent60)
1447 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1449 else if(basetime > percent60)
1451 basetime -= 2 * percent20;
1452 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1457 // Call default DealDamage
1458 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1459 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1461 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1462 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1463 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1465 // -probability is between 0% and 40%
1466 // 20% base chance
1467 float Probability = 20;
1469 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1470 if( pVictim->getLevel() < 30 )
1471 Probability = 0.65f*pVictim->getLevel()+0.5;
1473 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1474 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1476 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1478 if(Probability > 40)
1479 Probability = 40;
1481 if(roll_chance_f(Probability))
1482 CastSpell(pVictim, 1604, true);
1485 // update at damage Judgement aura duration that applied by attacker at victim
1486 if(damageInfo->damage)
1488 AuraMap& vAuras = pVictim->GetAuras();
1489 for(AuraMap::iterator itr = vAuras.begin(); itr != vAuras.end(); ++itr)
1491 SpellEntry const *spellInfo = (*itr).second->GetSpellProto();
1492 if( spellInfo->AttributesEx3 & 0x40000 && spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && ((*itr).second->GetCasterGUID() == GetGUID()))
1494 (*itr).second->SetAuraDuration((*itr).second->GetAuraMaxDuration());
1495 (*itr).second->SendAuraUpdate(false);
1500 // If not miss
1501 if (!(damageInfo->HitInfo & HITINFO_MISS))
1503 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1505 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1506 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1509 // victim's damage shield
1510 std::set<Aura*> alreadyDone;
1511 uint32 removedAuras = pVictim->m_removedAuras;
1512 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1513 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1515 next++;
1516 if (alreadyDone.find(*i) == alreadyDone.end())
1518 alreadyDone.insert(*i);
1519 uint32 damage=(*i)->GetModifier()->m_amount;
1520 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1521 if(!spellProto)
1522 continue;
1523 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1524 //uint32 absorb;
1525 //uint32 resist;
1526 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1527 //damage-=absorb + resist;
1529 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1530 data << uint64(pVictim->GetGUID());
1531 data << uint64(GetGUID());
1532 data << uint32(spellProto->Id);
1533 data << uint32(damage); // Damage
1534 data << uint32(0); // Overkill
1535 data << uint32(spellProto->SchoolMask);
1536 pVictim->SendMessageToSet(&data, true );
1538 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1540 if (pVictim->m_removedAuras > removedAuras)
1542 removedAuras = pVictim->m_removedAuras;
1543 next = vDamageShields.begin();
1551 void Unit::HandleEmoteCommand(uint32 anim_id)
1553 WorldPacket data( SMSG_EMOTE, 12 );
1554 data << uint32(anim_id);
1555 data << uint64(GetGUID());
1556 SendMessageToSet(&data, true);
1559 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1561 uint32 newdamage = 0;
1562 float armor = pVictim->GetArmor();
1563 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1564 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1566 // Apply Player CR_ARMOR_PENETRATION rating
1567 if (GetTypeId()==TYPEID_PLAYER)
1568 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1570 if (armor < 0.0f) armor=0.0f;
1572 float levelModifier = getLevel();
1573 if ( levelModifier > 59 )
1574 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1576 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1577 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1579 if(tmpvalue < 0.0f)
1580 tmpvalue = 0.0f;
1581 if(tmpvalue > 0.75f)
1582 tmpvalue = 0.75f;
1583 newdamage = uint32(damage - (damage * tmpvalue));
1585 return (newdamage > 1) ? newdamage : 1;
1588 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1590 if(!pVictim || !pVictim->isAlive() || !damage)
1591 return;
1593 // Magic damage, check for resists
1594 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1596 // Get base victim resistance for school
1597 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1598 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1599 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1601 tmpvalue2 *= (float)(0.15f / getLevel());
1602 if (tmpvalue2 < 0.0f)
1603 tmpvalue2 = 0.0f;
1604 if (tmpvalue2 > 0.75f)
1605 tmpvalue2 = 0.75f;
1606 uint32 ran = urand(0, 100);
1607 uint32 faq[4] = {24,6,4,6};
1608 uint8 m = 0;
1609 float Binom = 0.0f;
1610 for (uint8 i = 0; i < 4; i++)
1612 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1613 if (ran > Binom )
1614 ++m;
1615 else
1616 break;
1618 if (damagetype == DOT && m == 4)
1619 *resist += uint32(damage - 1);
1620 else
1621 *resist += uint32(damage * m / 4);
1622 if(*resist > damage)
1623 *resist = damage;
1625 else
1626 *resist = 0;
1628 int32 RemainingDamage = damage - *resist;
1630 // absorb without mana cost
1631 int32 reflectDamage = 0;
1632 Aura* reflectAura = NULL;
1633 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1634 for(AuraList::const_iterator i = vSchoolAbsorb.begin(), next; i != vSchoolAbsorb.end() && RemainingDamage > 0; i = next)
1636 next = i; ++next;
1638 if (((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1639 continue;
1641 // Cheat Death
1642 if((*i)->GetSpellProto()->SpellFamilyName==SPELLFAMILY_ROGUE && (*i)->GetSpellProto()->SpellIconID == 2109)
1644 if (((Player*)pVictim)->HasSpellCooldown(31231))
1645 continue;
1646 if (pVictim->GetHealth() <= RemainingDamage)
1648 int32 chance = (*i)->GetModifier()->m_amount;
1649 if (roll_chance_i(chance))
1651 pVictim->CastSpell(pVictim,31231,true);
1652 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1654 // with health > 10% lost health until health==10%, in other case no losses
1655 uint32 health10 = pVictim->GetMaxHealth()/10;
1656 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1659 continue;
1662 int32 currentAbsorb;
1664 // Reflective Shield
1665 if ((pVictim != this) && (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_PRIEST && (*i)->GetSpellProto()->SpellFamilyFlags == 0x1)
1667 if(Unit* caster = (*i)->GetCaster())
1669 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1670 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1672 switch((*k)->GetModifier()->m_miscvalue)
1674 case 5065: // Rank 1
1675 case 5064: // Rank 2
1676 case 5063: // Rank 3
1678 if(RemainingDamage >= (*i)->GetModifier()->m_amount)
1679 reflectDamage = (*i)->GetModifier()->m_amount * (*k)->GetModifier()->m_amount/100;
1680 else
1681 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1682 reflectAura = *i;
1684 } break;
1685 default: break;
1688 if(reflectDamage)
1689 break;
1694 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1696 currentAbsorb = (*i)->GetModifier()->m_amount;
1697 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1698 next = vSchoolAbsorb.begin();
1700 else
1702 currentAbsorb = RemainingDamage;
1703 (*i)->GetModifier()->m_amount -= RemainingDamage;
1706 RemainingDamage -= currentAbsorb;
1708 // do not cast spells while looping auras; auras can get invalid otherwise
1709 if (reflectDamage)
1710 pVictim->CastCustomSpell(this, 33619, &reflectDamage, NULL, NULL, true, NULL, reflectAura);
1712 // absorb by mana cost
1713 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1714 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1716 next = i; ++next;
1718 // check damage school mask
1719 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1720 continue;
1722 int32 currentAbsorb;
1723 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1724 currentAbsorb = (*i)->GetModifier()->m_amount;
1725 else
1726 currentAbsorb = RemainingDamage;
1728 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1729 if(Player *modOwner = GetSpellModOwner())
1730 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1732 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1733 if (currentAbsorb > maxAbsorb)
1734 currentAbsorb = maxAbsorb;
1736 (*i)->GetModifier()->m_amount -= currentAbsorb;
1737 if((*i)->GetModifier()->m_amount <= 0)
1739 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1740 next = vManaShield.begin();
1743 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1744 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1746 RemainingDamage -= currentAbsorb;
1749 // only split damage if not damaging yourself
1750 if(pVictim != this)
1752 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1753 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1755 next = i; ++next;
1757 // check damage school mask
1758 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1759 continue;
1761 // Damage can be splitted only if aura has an alive caster
1762 Unit *caster = (*i)->GetCaster();
1763 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1764 continue;
1766 int32 currentAbsorb;
1767 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1768 currentAbsorb = (*i)->GetModifier()->m_amount;
1769 else
1770 currentAbsorb = RemainingDamage;
1772 RemainingDamage -= currentAbsorb;
1774 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1776 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1777 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1780 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1781 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1783 next = i; ++next;
1785 // check damage school mask
1786 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1787 continue;
1789 // Damage can be splitted only if aura has an alive caster
1790 Unit *caster = (*i)->GetCaster();
1791 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1792 continue;
1794 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1796 RemainingDamage -= splitted;
1798 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1800 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1801 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1805 *absorb = damage - RemainingDamage - *resist;
1808 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1810 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1811 return;
1813 if (!pVictim->isAlive())
1814 return;
1816 if(IsNonMeleeSpellCasted(false))
1817 return;
1819 uint32 hitInfo;
1820 if (attType == BASE_ATTACK)
1821 hitInfo = HITINFO_NORMALSWING2;
1822 else if (attType == OFF_ATTACK)
1823 hitInfo = HITINFO_LEFTSWING;
1824 else
1825 return; // ignore ranged case
1827 uint32 extraAttacks = m_extraAttacks;
1829 // melee attack spell casted at main hand attack only
1830 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1832 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1834 // not recent extra attack only at any non extra attack (melee spell case)
1835 if(!extra && extraAttacks)
1837 while(m_extraAttacks)
1839 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1840 if(m_extraAttacks > 0)
1841 --m_extraAttacks;
1845 return;
1848 CalcDamageInfo damageInfo;
1849 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1850 // Send log damage message to client
1851 SendAttackStateUpdate(&damageInfo);
1852 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1853 DealMeleeDamage(&damageInfo,true);
1855 if (GetTypeId() == TYPEID_PLAYER)
1856 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1857 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1858 else
1859 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1860 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1862 // extra attack only at any non extra attack (normal case)
1863 if(!extra && extraAttacks)
1865 while(m_extraAttacks)
1867 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1868 if(m_extraAttacks > 0)
1869 --m_extraAttacks;
1874 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
1876 // This is only wrapper
1878 // Miss chance based on melee
1879 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
1881 // Critical hit chance
1882 float crit_chance = GetUnitCriticalChance(attType, pVictim);
1884 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
1885 float dodge_chance = pVictim->GetUnitDodgeChance();
1886 float block_chance = pVictim->GetUnitBlockChance();
1887 float parry_chance = pVictim->GetUnitParryChance();
1889 // Useful if want to specify crit & miss chances for melee, else it could be removed
1890 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
1892 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
1895 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
1897 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1898 return MELEE_HIT_EVADE;
1900 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
1901 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
1903 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
1904 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
1906 // bonus from skills is 0.04%
1907 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
1908 int32 sum = 0, tmp = 0;
1909 int32 roll = urand (0, 10000);
1911 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
1912 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
1913 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
1915 tmp = miss_chance;
1917 if (tmp > 0 && roll < (sum += tmp ))
1919 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
1920 return MELEE_HIT_MISS;
1923 // always crit against a sitting target (except 0 crit chance)
1924 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
1926 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
1927 return MELEE_HIT_CRIT;
1930 // Dodge chance
1932 // only players can't dodge if attacker is behind
1933 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
1935 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
1937 else
1939 // Reduce dodge chance by attacker expertise rating
1940 if (GetTypeId() == TYPEID_PLAYER)
1941 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
1943 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
1944 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
1946 tmp = dodge_chance;
1947 if ( (tmp > 0) // check if unit _can_ dodge
1948 && ((tmp -= skillBonus) > 0)
1949 && roll < (sum += tmp))
1951 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
1952 return MELEE_HIT_DODGE;
1956 // parry & block chances
1958 // check if attack comes from behind, nobody can parry or block if attacker is behind
1959 if (!pVictim->HasInArc(M_PI,this))
1961 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
1963 else
1965 // Reduce parry chance by attacker expertise rating
1966 if (GetTypeId() == TYPEID_PLAYER)
1967 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
1969 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
1971 int32 tmp = int32(parry_chance);
1972 if ( (tmp > 0) // check if unit _can_ parry
1973 && ((tmp -= skillBonus) > 0)
1974 && (roll < (sum += tmp)))
1976 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
1977 return MELEE_HIT_PARRY;
1981 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
1983 tmp = block_chance;
1984 if ( (tmp > 0) // check if unit _can_ block
1985 && ((tmp -= skillBonus) > 0)
1986 && (roll < (sum += tmp)))
1988 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
1989 return MELEE_HIT_BLOCK;
1994 // Critical chance
1995 tmp = crit_chance;
1997 if (tmp > 0 && roll < (sum += tmp))
1999 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2000 return MELEE_HIT_CRIT;
2003 // 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)
2004 if( attType != RANGED_ATTACK &&
2005 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2006 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2007 getLevel() < pVictim->getLevelForTarget(this) )
2009 // cap possible value (with bonuses > max skill)
2010 int32 skill = attackerWeaponSkill;
2011 int32 maxskill = attackerMaxSkillValueForLevel;
2012 skill = (skill > maxskill) ? maxskill : skill;
2014 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2015 tmp = tmp > 4000 ? 4000 : tmp;
2016 if (roll < (sum += tmp))
2018 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2019 return MELEE_HIT_GLANCING;
2023 // mobs can score crushing blows if they're 4 or more levels above victim
2024 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2025 // can be from by creature (if can) or from controlled player that considered as creature
2026 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2027 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2028 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2030 // when their weapon skill is 15 or more above victim's defense skill
2031 tmp = victimDefenseSkill;
2032 int32 tmpmax = victimMaxSkillValueForLevel;
2033 // having defense above your maximum (from items, talents etc.) has no effect
2034 tmp = tmp > tmpmax ? tmpmax : tmp;
2035 // tmp = mob's level * 5 - player's current defense skill
2036 tmp = attackerMaxSkillValueForLevel - tmp;
2037 if(tmp >= 15)
2039 // add 2% chance per lacking skill point, min. is 15%
2040 tmp = tmp * 200 - 1500;
2041 if (roll < (sum += tmp))
2043 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2044 return MELEE_HIT_CRUSHING;
2049 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2050 return MELEE_HIT_NORMAL;
2053 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2055 float min_damage, max_damage;
2057 if (normalized && GetTypeId()==TYPEID_PLAYER)
2058 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2059 else
2061 switch (attType)
2063 case RANGED_ATTACK:
2064 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2065 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2066 break;
2067 case BASE_ATTACK:
2068 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2069 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2070 break;
2071 case OFF_ATTACK:
2072 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2073 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2074 break;
2075 // Just for good manner
2076 default:
2077 min_damage = 0.0f;
2078 max_damage = 0.0f;
2079 break;
2083 if (min_damage > max_damage)
2085 std::swap(min_damage,max_damage);
2088 if(max_damage == 0.0f)
2089 max_damage = 5.0f;
2091 return urand((uint32)min_damage, (uint32)max_damage);
2094 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2096 if(spellProto->spellLevel <= 0)
2097 return 1.0f;
2099 float LvlPenalty = 0.0f;
2101 if(spellProto->spellLevel < 20)
2102 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2103 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2104 if(LvlFactor > 1.0f)
2105 LvlFactor = 1.0f;
2107 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2110 void Unit::SendAttackStart(Unit* pVictim)
2112 WorldPacket data( SMSG_ATTACKSTART, 16 );
2113 data << uint64(GetGUID());
2114 data << uint64(pVictim->GetGUID());
2116 SendMessageToSet(&data, true);
2117 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2120 void Unit::SendAttackStop(Unit* victim)
2122 if(!victim)
2123 return;
2125 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2126 data.append(GetPackGUID());
2127 data.append(victim->GetPackGUID()); // can be 0x00...
2128 data << uint32(0); // can be 0x1
2129 SendMessageToSet(&data, true);
2130 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2132 /*if(victim->GetTypeId() == TYPEID_UNIT)
2133 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2136 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2138 if (pVictim->HasInArc(M_PI,this))
2140 /* Currently not exist spells with ignore block
2141 // Ignore combat result aura (parry/dodge check on prepare)
2142 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2143 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2145 if (!(*i)->isAffectedOnSpell(spellProto))
2146 continue;
2147 if ((*i)->GetModifier()->m_miscvalue == )
2148 return false;
2152 // Check creatures flags_extra for disable block
2153 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2154 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2155 return false;
2157 float blockChance = GetUnitBlockChance();
2158 blockChance += (GetWeaponSkillValue(attackType) - pVictim->GetMaxSkillValueForLevel() )*0.04;
2159 if (roll_chance_f(blockChance))
2160 return true;
2162 return false;
2165 // Melee based spells can be miss, parry or dodge on this step
2166 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2167 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2169 // Calculate hit chance (more correct for chance mod)
2170 int32 HitChance;
2172 // PvP - PvE melee chances
2173 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2174 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2175 if(leveldif < 3)
2176 HitChance = 95 - leveldif;
2177 else
2178 HitChance = 93 - (leveldif - 2) * lchance;
2180 // Hit chance depends from victim auras
2181 if(attType == RANGED_ATTACK)
2182 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2183 else
2184 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2186 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2187 if(Player *modOwner = GetSpellModOwner())
2188 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2190 // Miss = 100 - hit
2191 float miss_chance= 100.0f - HitChance;
2193 // Bonuses from attacker aura and ratings
2194 if (attType == RANGED_ATTACK)
2195 miss_chance -= m_modRangedHitChance;
2196 else
2197 miss_chance -= m_modMeleeHitChance;
2199 // bonus from skills is 0.04%
2200 miss_chance -= skillDiff * 0.04f;
2202 // Limit miss chance from 0 to 60%
2203 if (miss_chance < 0.0f)
2204 return 0.0f;
2205 if (miss_chance > 60.0f)
2206 return 60.0f;
2207 return miss_chance;
2210 // Melee based spells hit result calculations
2211 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2213 WeaponAttackType attType = BASE_ATTACK;
2215 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2216 attType = RANGED_ATTACK;
2218 // bonus from skills is 0.04% per skill Diff
2219 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2220 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2221 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2223 uint32 roll = urand (0, 10000);
2225 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2226 // Roll miss
2227 uint32 tmp = missChance;
2228 if (roll < tmp)
2229 return SPELL_MISS_MISS;
2231 bool canDodge = true;
2232 bool canParry = true;
2234 // Same spells cannot be parry/dodge
2235 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2236 return SPELL_MISS_NONE;
2238 // Ranged attack cannot be parry/dodge
2239 if (attType == RANGED_ATTACK)
2240 return SPELL_MISS_NONE;
2242 // Check for attack from behind
2243 if (!pVictim->HasInArc(M_PI,this))
2245 // Can`t dodge from behind in PvP (but its possible in PvE)
2246 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2247 canDodge = false;
2248 // Can`t parry
2249 canParry = false;
2251 // Check creatures flags_extra for disable parry
2252 if(pVictim->GetTypeId()==TYPEID_UNIT)
2254 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2255 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2256 canParry = false;
2258 // Ignore combat result aura
2259 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2260 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2262 if (!(*i)->isAffectedOnSpell(spell))
2263 continue;
2264 switch((*i)->GetModifier()->m_miscvalue)
2266 case MELEE_HIT_DODGE: canDodge = false; break;
2267 case MELEE_HIT_BLOCK: break; // Block check in hit step
2268 case MELEE_HIT_PARRY: canParry = false; break;
2269 default:
2270 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2271 break;
2275 if (canDodge)
2277 // Roll dodge
2278 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2279 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2280 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2281 // Reduce dodge chance by attacker expertise rating
2282 if (GetTypeId() == TYPEID_PLAYER)
2283 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2284 if (dodgeChance < 0)
2285 dodgeChance = 0;
2287 tmp += dodgeChance;
2288 if (roll < tmp)
2289 return SPELL_MISS_DODGE;
2292 if (canParry)
2294 // Roll parry
2295 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2296 // Reduce parry chance by attacker expertise rating
2297 if (GetTypeId() == TYPEID_PLAYER)
2298 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2299 if (parryChance < 0)
2300 parryChance = 0;
2302 tmp += parryChance;
2303 if (roll < tmp)
2304 return SPELL_MISS_PARRY;
2307 return SPELL_MISS_NONE;
2310 // TODO need use unit spell resistances in calculations
2311 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2313 // Can`t miss on dead target (on skinning for example)
2314 if (!pVictim->isAlive())
2315 return SPELL_MISS_NONE;
2317 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2318 // PvP - PvE spell misschances per leveldif > 2
2319 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2320 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2322 // Base hit chance from attacker and victim levels
2323 int32 modHitChance;
2324 if(leveldif < 3)
2325 modHitChance = 96 - leveldif;
2326 else
2327 modHitChance = 94 - (leveldif - 2) * lchance;
2329 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2330 if(Player *modOwner = GetSpellModOwner())
2331 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2332 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2333 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2334 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2335 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2336 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2337 if (IsAreaOfEffectSpell(spell))
2338 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2339 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2340 if (IsDispelSpell(spell))
2341 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2342 // Chance resist mechanic (select max value from every mechanic spell effect)
2343 int32 resist_mech = 0;
2344 // Get effects mechanic and chance
2345 for(int eff = 0; eff < 3; ++eff)
2347 int32 effect_mech = GetEffectMechanic(spell, eff);
2348 if (effect_mech)
2350 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2351 if (resist_mech < temp)
2352 resist_mech = temp;
2355 // Apply mod
2356 modHitChance-=resist_mech;
2358 // Chance resist debuff
2359 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2361 int32 HitChance = modHitChance * 100;
2362 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2363 HitChance += int32(m_modSpellHitChance*100.0f);
2365 // Decrease hit chance from victim rating bonus
2366 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2367 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2369 if (HitChance < 100) HitChance = 100;
2370 if (HitChance > 9900) HitChance = 9900;
2372 uint32 rand = urand(0,10000);
2373 if (rand > HitChance)
2374 return SPELL_MISS_RESIST;
2375 return SPELL_MISS_NONE;
2378 // Calculate spell hit result can be:
2379 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2380 // For melee based spells:
2381 // Miss
2382 // Dodge
2383 // Parry
2384 // For spells
2385 // Resist
2386 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2388 // Return evade for units in evade mode
2389 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2390 return SPELL_MISS_EVADE;
2392 // Check for immune
2393 if (pVictim->IsImmunedToSpell(spell))
2394 return SPELL_MISS_IMMUNE;
2396 // All positive spells can`t miss
2397 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2398 if (IsPositiveSpell(spell->Id))
2399 return SPELL_MISS_NONE;
2401 // Check for immune
2402 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2403 return SPELL_MISS_IMMUNE;
2405 // Try victim reflect spell
2406 if (CanReflect)
2408 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2409 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2410 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2411 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2412 reflectchance += (*i)->GetModifier()->m_amount;
2413 if (reflectchance > 0 && roll_chance_i(reflectchance))
2415 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2416 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2417 return SPELL_MISS_REFLECT;
2421 switch (spell->DmgClass)
2423 case SPELL_DAMAGE_CLASS_RANGED:
2424 case SPELL_DAMAGE_CLASS_MELEE:
2425 return MeleeSpellHitResult(pVictim, spell);
2426 case SPELL_DAMAGE_CLASS_NONE:
2427 case SPELL_DAMAGE_CLASS_MAGIC:
2428 return MagicSpellHitResult(pVictim, spell);
2430 return SPELL_MISS_NONE;
2433 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2435 if(!pVictim)
2436 return 0.0f;
2438 // Base misschance 5%
2439 float misschance = 5.0f;
2441 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2442 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2444 bool isNormal = false;
2445 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2447 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2449 isNormal = true;
2450 break;
2453 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2455 misschance = 5.0f;
2457 else
2459 misschance = 24.0f;
2463 // PvP : PvE melee misschances per leveldif > 2
2464 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2466 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2467 if(leveldif < 0)
2468 leveldif = 0;
2470 // Hit chance from attacker based on ratings and auras
2471 float m_modHitChance;
2472 if (attType == RANGED_ATTACK)
2473 m_modHitChance = m_modRangedHitChance;
2474 else
2475 m_modHitChance = m_modMeleeHitChance;
2477 if(leveldif < 3)
2478 misschance += (leveldif - m_modHitChance);
2479 else
2480 misschance += ((leveldif - 2) * chance - m_modHitChance);
2482 // Hit chance for victim based on ratings
2483 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2485 if (attType == RANGED_ATTACK)
2486 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2487 else
2488 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2491 // Modify miss chance by victim auras
2492 if(attType == RANGED_ATTACK)
2493 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2494 else
2495 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2497 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2498 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2499 misschance -= skillBonus * 0.04f;
2501 // Limit miss chance from 0 to 60%
2502 if ( misschance < 0.0f)
2503 return 0.0f;
2504 if ( misschance > 60.0f)
2505 return 60.0f;
2507 return misschance;
2510 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2512 if(GetTypeId() == TYPEID_PLAYER)
2514 // in PvP use full skill instead current skill value
2515 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2516 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2517 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2518 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2519 return value;
2521 else
2522 return GetUnitMeleeSkill(target);
2525 float Unit::GetUnitDodgeChance() const
2527 if(hasUnitState(UNIT_STAT_STUNNED))
2528 return 0.0f;
2529 if( GetTypeId() == TYPEID_PLAYER )
2530 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2531 else
2533 if(((Creature const*)this)->isTotem())
2534 return 0.0f;
2535 else
2537 float dodge = 5.0f;
2538 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2539 return dodge > 0.0f ? dodge : 0.0f;
2544 float Unit::GetUnitParryChance() const
2546 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2547 return 0.0f;
2549 float chance = 0.0f;
2551 if(GetTypeId() == TYPEID_PLAYER)
2553 Player const* player = (Player const*)this;
2554 if(player->CanParry() )
2556 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2557 if(!tmpitem)
2558 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2560 if(tmpitem)
2561 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2564 else if(GetTypeId() == TYPEID_UNIT)
2566 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2568 chance = 5.0f;
2569 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2573 return chance > 0.0f ? chance : 0.0f;
2576 float Unit::GetUnitBlockChance() const
2578 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2579 return 0.0f;
2581 if(GetTypeId() == TYPEID_PLAYER)
2583 Player const* player = (Player const*)this;
2584 if(player->CanBlock() )
2586 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2587 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2588 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2590 // is player but has no block ability or no not broken shield equipped
2591 return 0.0f;
2593 else
2595 if(((Creature const*)this)->isTotem())
2596 return 0.0f;
2597 else
2599 float block = 5.0f;
2600 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2601 return block > 0.0f ? block : 0.0f;
2606 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2608 float crit;
2610 if(GetTypeId() == TYPEID_PLAYER)
2612 switch(attackType)
2614 case BASE_ATTACK:
2615 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2616 break;
2617 case OFF_ATTACK:
2618 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2619 break;
2620 case RANGED_ATTACK:
2621 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2622 break;
2623 // Just for good manner
2624 default:
2625 crit = 0.0f;
2626 break;
2629 else
2631 crit = 5.0f;
2632 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2635 // flat aura mods
2636 if(attackType == RANGED_ATTACK)
2637 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2638 else
2639 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2641 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2643 // reduce crit chance from Rating for players
2644 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2646 if (attackType==RANGED_ATTACK)
2647 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2648 else
2649 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2652 // Apply crit chance from defence skill
2653 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2655 if (crit < 0.0f)
2656 crit = 0.0f;
2657 return crit;
2660 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2662 uint32 value = 0;
2663 if(GetTypeId() == TYPEID_PLAYER)
2665 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2667 // feral or unarmed skill only for base attack
2668 if(attType != BASE_ATTACK && !item )
2669 return 0;
2671 if(((Player*)this)->IsInFeralForm())
2672 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2674 // weapon skill or (unarmed for base attack)
2675 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2677 // in PvP use full skill instead current skill value
2678 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2679 ? ((Player*)this)->GetMaxSkillValue(skill)
2680 : ((Player*)this)->GetSkillValue(skill);
2681 // Modify value from ratings
2682 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2683 switch (attType)
2685 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2686 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2687 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2690 else
2691 value = GetUnitMeleeSkill(target);
2692 return value;
2695 void Unit::_UpdateSpells( uint32 time )
2697 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2698 _UpdateAutoRepeatSpell();
2700 // remove finished spells from current pointers
2701 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2703 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2705 m_currentSpells[i]->SetReferencedFromCurrent(false);
2706 m_currentSpells[i] = NULL; // remove pointer
2710 // TODO: Find a better way to prevent crash when multiple auras are removed.
2711 m_removedAuras = 0;
2712 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2713 if ((*i).second)
2714 (*i).second->SetUpdated(false);
2716 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2718 next = i;
2719 ++next;
2720 if ((*i).second)
2722 // prevent double update
2723 if ((*i).second->IsUpdated())
2724 continue;
2725 (*i).second->SetUpdated(true);
2726 (*i).second->Update( time );
2727 // several auras can be deleted due to update
2728 if (m_removedAuras)
2730 if (m_Auras.empty()) break;
2731 next = m_Auras.begin();
2732 m_removedAuras = 0;
2737 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2739 if ((*i).second)
2741 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2743 RemoveAura(i);
2745 else
2747 ++i;
2750 else
2752 ++i;
2756 if(!m_gameObj.empty())
2758 std::list<GameObject*>::iterator ite1, dnext1;
2759 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2761 dnext1 = ite1;
2762 //(*i)->Update( difftime );
2763 if( !(*ite1)->isSpawned() )
2765 (*ite1)->SetOwnerGUID(0);
2766 (*ite1)->SetRespawnTime(0);
2767 (*ite1)->Delete();
2768 dnext1 = m_gameObj.erase(ite1);
2770 else
2771 ++dnext1;
2776 void Unit::_UpdateAutoRepeatSpell()
2778 //check "realtime" interrupts
2779 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2781 // cancel wand shoot
2782 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2783 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2784 m_AutoRepeatFirstCast = true;
2785 return;
2788 //apply delay
2789 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2790 setAttackTimer(RANGED_ATTACK,500);
2791 m_AutoRepeatFirstCast = false;
2793 //castroutine
2794 if (isAttackReady(RANGED_ATTACK))
2796 // Check if able to cast
2797 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CanCast(true))
2799 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2800 return;
2803 // we want to shoot
2804 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2805 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2807 // all went good, reset attack
2808 resetAttackTimer(RANGED_ATTACK);
2812 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2814 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2816 uint32 CSpellType = pSpell->GetCurrentContainer();
2818 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
2820 // break same type spell if it is not delayed
2821 InterruptSpell(CSpellType,false);
2823 // special breakage effects:
2824 switch (CSpellType)
2826 case CURRENT_GENERIC_SPELL:
2828 // generic spells always break channeled not delayed spells
2829 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
2831 // autorepeat breaking
2832 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
2834 // break autorepeat if not Auto Shot
2835 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2836 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2837 m_AutoRepeatFirstCast = true;
2839 } break;
2841 case CURRENT_CHANNELED_SPELL:
2843 // channel spells always break generic non-delayed and any channeled spells
2844 InterruptSpell(CURRENT_GENERIC_SPELL,false);
2845 InterruptSpell(CURRENT_CHANNELED_SPELL);
2847 // it also does break autorepeat if not Auto Shot
2848 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
2849 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
2850 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2851 } break;
2853 case CURRENT_AUTOREPEAT_SPELL:
2855 // only Auto Shoot does not break anything
2856 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2858 // generic autorepeats break generic non-delayed and channeled non-delayed spells
2859 InterruptSpell(CURRENT_GENERIC_SPELL,false);
2860 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
2862 // special action: set first cast flag
2863 m_AutoRepeatFirstCast = true;
2864 } break;
2866 default:
2868 // other spell types don't break anything now
2869 } break;
2872 // current spell (if it is still here) may be safely deleted now
2873 if (m_currentSpells[CSpellType])
2874 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
2876 // set new current spell
2877 m_currentSpells[CSpellType] = pSpell;
2878 pSpell->SetReferencedFromCurrent(true);
2881 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
2883 assert(spellType < CURRENT_MAX_SPELL);
2885 if(m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
2887 // send autorepeat cancel message for autorepeat spells
2888 if (spellType == CURRENT_AUTOREPEAT_SPELL)
2890 if(GetTypeId()==TYPEID_PLAYER)
2891 ((Player*)this)->SendAutoRepeatCancel();
2894 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
2895 m_currentSpells[spellType]->cancel();
2896 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
2897 m_currentSpells[spellType] = NULL;
2901 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
2903 // We don't do loop here to explicitly show that melee spell is excluded.
2904 // Maybe later some special spells will be excluded too.
2906 // generic spells are casted when they are not finished and not delayed
2907 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
2908 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
2909 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
2910 return(true);
2912 // channeled spells may be delayed, but they are still considered casted
2913 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
2914 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
2915 return(true);
2917 // autorepeat spells may be finished or delayed, but they are still considered casted
2918 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
2919 return(true);
2921 return(false);
2924 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
2926 // generic spells are interrupted if they are not finished or delayed
2927 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
2929 if ( (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
2930 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
2931 m_currentSpells[CURRENT_GENERIC_SPELL]->cancel();
2932 m_currentSpells[CURRENT_GENERIC_SPELL]->SetReferencedFromCurrent(false);
2933 m_currentSpells[CURRENT_GENERIC_SPELL] = NULL;
2936 // autorepeat spells are interrupted if they are not finished or delayed
2937 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
2939 // send disable autorepeat packet in any case
2940 if(GetTypeId()==TYPEID_PLAYER)
2941 ((Player*)this)->SendAutoRepeatCancel();
2943 if ( (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_FINISHED) &&
2944 (withDelayed || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_DELAYED) )
2945 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->cancel();
2946 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->SetReferencedFromCurrent(false);
2947 m_currentSpells[CURRENT_AUTOREPEAT_SPELL] = NULL;
2950 // channeled spells are interrupted if they are not finished, even if they are delayed
2951 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
2953 if (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)
2954 m_currentSpells[CURRENT_CHANNELED_SPELL]->cancel();
2955 m_currentSpells[CURRENT_CHANNELED_SPELL]->SetReferencedFromCurrent(false);
2956 m_currentSpells[CURRENT_CHANNELED_SPELL] = NULL;
2960 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
2962 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2963 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
2964 return m_currentSpells[i];
2965 return NULL;
2968 bool Unit::isInFront(Unit const* target, float distance, float arc) const
2970 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
2973 void Unit::SetInFront(Unit const* target)
2975 SetOrientation(GetAngle(target));
2978 bool Unit::isInBack(Unit const* target, float distance, float arc) const
2980 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
2983 bool Unit::isInAccessablePlaceFor(Creature const* c) const
2985 if(IsInWater())
2986 return c->canSwim();
2987 else
2988 return c->canWalk() || c->canFly();
2991 bool Unit::IsInWater() const
2993 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
2996 bool Unit::IsUnderWater() const
2998 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3001 void Unit::DeMorph()
3003 SetDisplayId(GetNativeDisplayId());
3006 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3008 int32 modifier = 0;
3010 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3011 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3012 modifier += (*i)->GetModifier()->m_amount;
3014 return modifier;
3017 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3019 float multiplier = 1.0f;
3021 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3022 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3023 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3025 return multiplier;
3028 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3030 int32 modifier = 0;
3032 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3033 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3034 if ((*i)->GetModifier()->m_amount > modifier)
3035 modifier = (*i)->GetModifier()->m_amount;
3037 return modifier;
3040 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3042 int32 modifier = 0;
3044 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3045 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3046 if ((*i)->GetModifier()->m_amount < modifier)
3047 modifier = (*i)->GetModifier()->m_amount;
3049 return modifier;
3052 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3054 int32 modifier = 0;
3056 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3057 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3059 Modifier* mod = (*i)->GetModifier();
3060 if (mod->m_miscvalue & misc_mask)
3061 modifier += mod->m_amount;
3063 return modifier;
3066 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3068 float multiplier = 1.0f;
3070 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3071 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3073 Modifier* mod = (*i)->GetModifier();
3074 if (mod->m_miscvalue & misc_mask)
3075 multiplier *= (100.0f + mod->m_amount)/100.0f;
3077 return multiplier;
3080 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3082 int32 modifier = 0;
3084 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3085 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3087 Modifier* mod = (*i)->GetModifier();
3088 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3089 modifier = mod->m_amount;
3092 return modifier;
3095 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3097 int32 modifier = 0;
3099 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3100 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3102 Modifier* mod = (*i)->GetModifier();
3103 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3104 modifier = mod->m_amount;
3107 return modifier;
3110 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3112 int32 modifier = 0;
3114 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3115 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3117 Modifier* mod = (*i)->GetModifier();
3118 if (mod->m_miscvalue == misc_value)
3119 modifier += mod->m_amount;
3121 return modifier;
3124 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3126 float multiplier = 1.0f;
3128 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3129 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3131 Modifier* mod = (*i)->GetModifier();
3132 if (mod->m_miscvalue == misc_value)
3133 multiplier *= (100.0f + mod->m_amount)/100.0f;
3135 return multiplier;
3138 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3140 int32 modifier = 0;
3142 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3143 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3145 Modifier* mod = (*i)->GetModifier();
3146 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3147 modifier = mod->m_amount;
3150 return modifier;
3153 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3155 int32 modifier = 0;
3157 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3158 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3160 Modifier* mod = (*i)->GetModifier();
3161 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3162 modifier = mod->m_amount;
3165 return modifier;
3168 bool Unit::AddAura(Aura *Aur)
3170 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3171 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3172 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3174 delete Aur;
3175 return false;
3178 if(Aur->GetTarget() != this)
3180 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3181 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3182 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3183 delete Aur;
3184 return false;
3187 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3189 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3190 AuraMap::iterator i = m_Auras.find( spair );
3192 // take out same spell
3193 if (i != m_Auras.end())
3195 // passive and persistent auras can stack with themselves any number of times
3196 if (!Aur->IsPassive() && !Aur->IsPersistent())
3198 // replace aura if next will > spell StackAmount
3199 if(aurSpellInfo->StackAmount)
3201 if(m_Auras.count(spair) >= aurSpellInfo->StackAmount)
3202 RemoveAura(i,AURA_REMOVE_BY_STACK);
3204 // if StackAmount==0 not allow auras from same caster
3205 else
3207 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3209 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3211 // can be only single (this check done at _each_ aura add
3212 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3213 break;
3216 bool stop = false;
3217 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3219 // DoT/HoT/etc
3220 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3221 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3222 case SPELL_AURA_PERIODIC_LEECH:
3223 case SPELL_AURA_PERIODIC_HEAL:
3224 case SPELL_AURA_OBS_MOD_HEALTH:
3225 case SPELL_AURA_PERIODIC_MANA_LEECH:
3226 case SPELL_AURA_PERIODIC_ENERGIZE:
3227 case SPELL_AURA_OBS_MOD_MANA:
3228 case SPELL_AURA_POWER_BURN_MANA:
3229 break;
3230 default: // not allow
3231 // can be only single (this check done at _each_ aura add
3232 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3233 stop = true;
3234 break;
3237 if(stop)
3238 break;
3244 // passive auras not stacable with other ranks
3245 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3247 if (!RemoveNoStackAurasDueToAura(Aur))
3249 delete Aur;
3250 return false; // couldn't remove conflicting aura with higher rank
3254 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3255 if (IsSingleTargetSpell(aurSpellInfo) && Aur->GetTarget())
3257 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3258 for(;;)
3260 Unit* caster = Aur->GetCaster();
3261 if(!caster) // caster deleted and not required adding scAura
3262 break;
3264 bool restart = false;
3265 AuraList& scAuras = caster->GetSingleCastAuras();
3266 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3268 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3269 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3271 if ((*itr)->IsInUse())
3273 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());
3274 continue;
3276 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3277 restart = true;
3278 break;
3282 if(!restart)
3284 // done
3285 scAuras.push_back(Aur);
3286 break;
3291 // add aura, register in lists and arrays
3292 Aur->_AddAura();
3293 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3294 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3296 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3299 Aur->ApplyModifier(true,true);
3300 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3301 return true;
3304 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3306 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3307 if(!spellInfo)
3308 return;
3309 AuraMap::iterator i,next;
3310 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3312 next = i;
3313 ++next;
3314 uint32 i_spellId = (*i).second->GetId();
3315 if((*i).second && i_spellId && i_spellId != spellId)
3317 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3319 RemoveAurasDueToSpell(i_spellId);
3321 if( m_Auras.empty() )
3322 break;
3323 else
3324 next = m_Auras.begin();
3330 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3332 if (!Aur)
3333 return false;
3335 SpellEntry const* spellProto = Aur->GetSpellProto();
3336 if (!spellProto)
3337 return false;
3339 uint32 spellId = Aur->GetId();
3341 // passive spell special case (only non stackable with ranks)
3342 if(IsPassiveSpell(spellId))
3344 if(IsPassiveSpellStackableWithRanks(spellProto))
3345 return true;
3348 uint32 effIndex = Aur->GetEffIndex();
3350 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3352 AuraMap::iterator i,next;
3353 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3355 next = i;
3356 ++next;
3357 if (!(*i).second) continue;
3359 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3361 if (!i_spellProto)
3362 continue;
3364 uint32 i_spellId = i_spellProto->Id;
3366 // early checks that spellId is passive non stackable spell
3367 if(IsPassiveSpell(i_spellId))
3369 // passive non-stackable spells not stackable only for same caster
3370 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3371 continue;
3373 // passive non-stackable spells not stackable only with another rank of same spell
3374 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3375 continue;
3378 uint32 i_effIndex = (*i).second->GetEffIndex();
3380 if(i_spellId == spellId) continue;
3382 bool is_triggered_by_spell = false;
3383 // prevent triggered aura of removing aura that triggered it
3384 for(int j = 0; j < 3; ++j)
3385 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3386 is_triggered_by_spell = true;
3387 if (is_triggered_by_spell) continue;
3389 for(int j = 0; j < 3; ++j)
3391 // prevent remove dummy triggered spells at next effect aura add
3392 switch(spellProto->Effect[j]) // main spell auras added added after triggered spell
3394 case SPELL_EFFECT_DUMMY:
3395 switch(spellId)
3397 case 5420: if(i_spellId==34123) is_triggered_by_spell = true; break;
3399 break;
3402 if(is_triggered_by_spell)
3403 break;
3405 // prevent remove form main spell by triggered passive spells
3406 switch(i_spellProto->EffectApplyAuraName[j]) // main aura added before triggered spell
3408 case SPELL_AURA_MOD_SHAPESHIFT:
3409 switch(i_spellId)
3411 case 24858: if(spellId==24905) is_triggered_by_spell = true; break;
3412 case 33891: if(spellId==5420 || spellId==34123) is_triggered_by_spell = true; break;
3413 case 34551: if(spellId==22688) is_triggered_by_spell = true; break;
3415 break;
3419 if(!is_triggered_by_spell)
3421 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3423 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3425 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3427 // cannot remove higher rank
3428 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3429 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3430 return false;
3432 // Its a parent aura (create this aura in ApplyModifier)
3433 if ((*i).second->IsInUse())
3435 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());
3436 continue;
3438 RemoveAurasDueToSpell(i_spellId);
3440 if( m_Auras.empty() )
3441 break;
3442 else
3443 next = m_Auras.begin();
3445 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3447 // Its a parent aura (create this aura in ApplyModifier)
3448 if ((*i).second->IsInUse())
3450 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());
3451 continue;
3453 RemoveAurasDueToSpell(i_spellId);
3455 if( m_Auras.empty() )
3456 break;
3457 else
3458 next = m_Auras.begin();
3460 // Potions stack aura by aura (elixirs/flask already checked)
3461 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3463 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3465 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3466 return false; // cannot remove higher rank
3468 // Its a parent aura (create this aura in ApplyModifier)
3469 if ((*i).second->IsInUse())
3471 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());
3472 continue;
3474 RemoveAura(i);
3475 next = i;
3480 return true;
3483 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3485 spellEffectPair spair = spellEffectPair(spellId, effindex);
3486 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3488 if(iter->second!=except)
3490 RemoveAura(iter);
3491 iter = m_Auras.lower_bound(spair);
3493 else
3494 ++iter;
3498 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3500 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3502 Aura *aur = iter->second;
3503 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3505 // Custom dispel case
3506 // Unstable Affliction
3507 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3509 int32 damage = aur->GetModifier()->m_amount*9;
3510 uint64 caster_guid = aur->GetCasterGUID();
3512 // Remove aura
3513 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3515 // backfire damage and silence
3516 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3518 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3520 else
3521 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3523 else
3524 ++iter;
3528 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3530 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3532 Aura *aur = iter->second;
3533 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3535 int32 basePoints = aur->GetBasePoints();
3536 // construct the new aura for the attacker
3537 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer);
3538 if(!new_aur)
3539 continue;
3541 // set its duration and maximum duration
3542 // max duration 2 minutes (in msecs)
3543 int32 dur = aur->GetAuraDuration();
3544 const int32 max_dur = 2*MINUTE*1000;
3545 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3546 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3548 // add the new aura to stealer
3549 stealer->AddAura(new_aur);
3551 // Remove aura as dispel
3552 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3554 else
3555 ++iter;
3559 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3561 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3563 if (iter->second->GetId() == spellId)
3564 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3565 else
3566 ++iter;
3570 void Unit::RemoveAurasWithDispelType( DispelType type )
3572 // Create dispel mask by dispel type
3573 uint32 dispelMask = GetDispellMask(type);
3574 // Dispel all existing auras vs current dispel type
3575 AuraMap& auras = GetAuras();
3576 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3578 SpellEntry const* spell = itr->second->GetSpellProto();
3579 if( (1<<spell->Dispel) & dispelMask )
3581 // Dispel aura
3582 RemoveAurasDueToSpell(spell->Id);
3583 itr = auras.begin();
3585 else
3586 ++itr;
3590 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3592 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3593 if(iter != m_Auras.end())
3594 RemoveAura(iter);
3597 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3599 for (int i = 0; i < 3; ++i)
3600 RemoveAura(spellId,i,except);
3603 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3605 for (int k=0; k < 3; ++k)
3607 spellEffectPair spair = spellEffectPair(spellId, k);
3608 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3610 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3612 RemoveAura(iter);
3613 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3615 else
3616 ++iter;
3621 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3623 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3625 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3626 RemoveAura(iter);
3627 else
3628 ++iter;
3632 void Unit::RemoveNotOwnSingleTargetAuras()
3634 // single target auras from other casters
3635 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3637 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3638 RemoveAura(iter);
3639 else
3640 ++iter;
3643 // single target auras at other targets
3644 AuraList& scAuras = GetSingleCastAuras();
3645 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3647 Aura* aura = *iter;
3648 if (aura->GetTarget()!=this)
3650 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3651 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3652 iter = scAuras.begin();
3654 else
3655 ++iter;
3660 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3662 Aura* Aur = i->second;
3663 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3665 Unit* caster = NULL;
3666 if (IsSingleTargetSpell(AurSpellInfo))
3668 caster = Aur->GetCaster();
3669 if(caster)
3671 AuraList& scAuras = caster->GetSingleCastAuras();
3672 scAuras.remove(Aur);
3674 else
3676 sLog.outError("Couldn't find the caster of the single target aura, may crash later!");
3677 assert(false);
3681 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3682 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3684 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3687 // Set remove mode
3688 Aur->SetRemoveMode(mode);
3689 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3690 // remove aura from list before to prevent deleting it before
3691 m_Auras.erase(i);
3692 ++m_removedAuras; // internal count used by unit update
3694 // Statue unsummoned at aura remove
3695 Totem* statue = NULL;
3696 bool caster_channeled = false;
3697 if(IsChanneledSpell(AurSpellInfo))
3699 if(!caster) // can be already located for IsSingleTargetSpell case
3700 caster = Aur->GetCaster();
3702 if(caster)
3704 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3705 statue = ((Totem*)caster);
3706 else
3707 caster_channeled = caster==this;
3711 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3712 Aur->ApplyModifier(false,true);
3713 Aur->_RemoveAura();
3714 delete Aur;
3716 if(caster_channeled)
3717 RemoveAurasAtChanneledTarget (AurSpellInfo);
3719 if(statue)
3720 statue->UnSummon();
3722 // only way correctly remove all auras from list
3723 if( m_Auras.empty() )
3724 i = m_Auras.end();
3725 else
3726 i = m_Auras.begin();
3729 void Unit::RemoveAllAuras()
3731 while (!m_Auras.empty())
3733 AuraMap::iterator iter = m_Auras.begin();
3734 RemoveAura(iter);
3738 void Unit::RemoveArenaAuras(bool onleave)
3740 // in join, remove positive buffs, on end, remove negative
3741 // used to remove positive visible auras in arenas
3742 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3744 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3745 && !iter->second->IsPassive() // don't remove passive auras
3746 && (!(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)
3747 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3748 RemoveAura(iter);
3749 else
3750 ++iter;
3754 void Unit::RemoveAllAurasOnDeath()
3756 // used just after dieing to remove all visible auras
3757 // and disable the mods for the passive ones
3758 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3760 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3761 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3762 else
3763 ++iter;
3767 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3769 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3770 if (iter != m_Auras.end())
3772 if (iter->second->GetAuraDuration() < delaytime)
3773 iter->second->SetAuraDuration(0);
3774 else
3775 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3776 iter->second->SendAuraUpdate(false);
3777 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3781 void Unit::_RemoveAllAuraMods()
3783 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3785 (*i).second->ApplyModifier(false);
3789 void Unit::_ApplyAllAuraMods()
3791 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3793 (*i).second->ApplyModifier(true);
3797 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3799 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3800 if (iter != m_Auras.end())
3801 return iter->second;
3802 return NULL;
3805 bool Unit::HasAura(uint32 spellId) const
3807 for (int i = 0; i < 3 ; ++i)
3809 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3810 if (iter != m_Auras.end())
3811 return true;
3813 return false;
3816 void Unit::AddDynObject(DynamicObject* dynObj)
3818 m_dynObjGUIDs.push_back(dynObj->GetGUID());
3821 void Unit::RemoveDynObject(uint32 spellid)
3823 if(m_dynObjGUIDs.empty())
3824 return;
3825 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3827 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3828 if(!dynObj)
3830 i = m_dynObjGUIDs.erase(i);
3832 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
3834 dynObj->Delete();
3835 i = m_dynObjGUIDs.erase(i);
3837 else
3838 ++i;
3842 void Unit::RemoveAllDynObjects()
3844 while(!m_dynObjGUIDs.empty())
3846 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3847 if(dynObj)
3848 dynObj->Delete();
3849 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
3853 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
3855 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3857 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3858 if(!dynObj)
3860 i = m_dynObjGUIDs.erase(i);
3861 continue;
3864 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
3865 return dynObj;
3866 ++i;
3868 return NULL;
3871 DynamicObject * Unit::GetDynObject(uint32 spellId)
3873 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3875 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3876 if(!dynObj)
3878 i = m_dynObjGUIDs.erase(i);
3879 continue;
3882 if (dynObj->GetSpellId() == spellId)
3883 return dynObj;
3884 ++i;
3886 return NULL;
3889 void Unit::AddGameObject(GameObject* gameObj)
3891 assert(gameObj && gameObj->GetOwnerGUID()==0);
3892 m_gameObj.push_back(gameObj);
3893 gameObj->SetOwnerGUID(GetGUID());
3896 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
3898 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
3900 // GO created by some spell
3901 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
3903 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
3904 // Need activate spell use for owner
3905 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
3906 ((Player*)this)->SendCooldownEvent(createBySpell);
3908 gameObj->SetOwnerGUID(0);
3909 m_gameObj.remove(gameObj);
3910 if(del)
3912 gameObj->SetRespawnTime(0);
3913 gameObj->Delete();
3917 void Unit::RemoveGameObject(uint32 spellid, bool del)
3919 if(m_gameObj.empty())
3920 return;
3921 std::list<GameObject*>::iterator i, next;
3922 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
3924 next = i;
3925 if(spellid == 0 || (*i)->GetSpellId() == spellid)
3927 (*i)->SetOwnerGUID(0);
3928 if(del)
3930 (*i)->SetRespawnTime(0);
3931 (*i)->Delete();
3934 next = m_gameObj.erase(i);
3936 else
3937 ++next;
3941 void Unit::RemoveAllGameObjects()
3943 // remove references to unit
3944 for(std::list<GameObject*>::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
3946 (*i)->SetOwnerGUID(0);
3947 (*i)->SetRespawnTime(0);
3948 (*i)->Delete();
3949 i = m_gameObj.erase(i);
3953 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
3955 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
3956 data.append(log->target->GetPackGUID());
3957 data.append(log->attacker->GetPackGUID());
3958 data << uint32(log->SpellID);
3959 data << uint32(log->damage); //damage amount
3960 data << uint32(0);
3961 data << uint8 (log->schoolMask); //damage school
3962 data << uint32(log->absorb); //AbsorbedDamage
3963 data << uint32(log->resist); //resist
3964 data << uint8 (log->phusicalLog); // damsge type? flag
3965 data << uint8 (log->unused); //unused
3966 data << uint32(log->blocked); //blocked
3967 data << uint32(log->HitInfo);
3968 data << uint8 (0); // flag to use extend data
3969 SendMessageToSet( &data, true );
3972 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
3974 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
3975 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
3976 data.append(target->GetPackGUID());
3977 data.append(GetPackGUID());
3978 data << uint32(SpellID);
3979 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
3980 data << uint32(0); // wotlk
3981 data << uint8(damageSchoolMask); // spell school
3982 data << uint32(AbsorbedDamage); // AbsorbedDamage
3983 data << uint32(Resist); // resist
3984 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
3985 data << uint8(0); // unk isFromAura
3986 data << uint32(Blocked); // blocked
3987 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
3988 data << uint8(0); // isDebug?
3989 SendMessageToSet( &data, true );
3992 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
3994 // Not much to do if no flags are set.
3995 if (procAttacker)
3996 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
3997 // Now go on with a victim's events'n'auras
3998 // Not much to do if no flags are set or there is no victim
3999 if(pVictim && pVictim->isAlive() && procVictim)
4000 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4003 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4005 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4006 data << uint32(spellID);
4007 data << uint64(GetGUID());
4008 data << uint8(0); // can be 0 or 1
4009 data << uint32(1); // target count
4010 // for(i = 0; i < target count; ++i)
4011 data << uint64(target->GetGUID()); // target GUID
4012 data << uint8(missInfo);
4013 // end loop
4014 SendMessageToSet(&data, true);
4017 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4019 uint32 count = 1;
4020 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4021 data << (uint32)damageInfo->HitInfo;
4022 data.append(GetPackGUID());
4023 data.append(damageInfo->target->GetPackGUID());
4024 data << (uint32)(damageInfo->damage); // Full damage
4025 data << uint32(0); // overkill value
4027 data << (uint8)count; // Sub damage count
4029 for(int i = 0; i < count; ++i)
4031 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4032 data << (float)damageInfo->damage; // sub damage
4033 data << (uint32)damageInfo->damage; // Sub Damage
4036 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4038 for(int i = 0; i < count; ++i)
4039 data << (uint32)damageInfo->absorb; // Absorb
4042 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4044 for(int i = 0; i < count; ++i)
4045 data << (uint32)damageInfo->resist; // Resist
4048 data << (uint8)damageInfo->TargetState;
4049 data << (uint32)0;
4050 data << (uint32)0;
4052 if(damageInfo->HitInfo & HITINFO_BLOCK)
4053 data << (uint32)damageInfo->blocked_amount;
4055 if(damageInfo->HitInfo & HITINFO_UNK3)
4056 data << uint32(0);
4058 if(damageInfo->HitInfo & HITINFO_UNK1)
4060 data << uint32(0);
4061 data << float(0);
4062 data << float(0);
4063 data << float(0);
4064 data << float(0);
4065 data << float(0);
4066 data << float(0);
4067 data << float(0);
4068 data << float(0);
4069 for(uint8 i = 0; i < 5; ++i)
4071 data << float(0);
4072 data << float(0);
4074 data << uint32(0);
4077 SendMessageToSet( &data, true );
4080 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4082 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4084 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4085 data << uint32(HitInfo); // flags
4086 data.append(GetPackGUID());
4087 data.append(target->GetPackGUID());
4088 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4089 data << uint32(0); // overkill value
4091 data << (uint8)SwingType; // count?
4093 // for(i = 0; i < SwingType; ++i)
4094 data << (uint32)damageSchoolMask;
4095 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4096 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4097 // end loop
4099 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4101 // for(i = 0; i < SwingType; ++i)
4102 data << uint32(AbsorbDamage);
4103 // end loop
4106 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4108 // for(i = 0; i < SwingType; ++i)
4109 data << uint32(Resist);
4110 // end loop
4113 data << (uint8)TargetState;
4114 data << (uint32)0;
4115 data << (uint32)0;
4117 if(HitInfo & HITINFO_BLOCK)
4119 data << uint32(BlockedAmount);
4122 if(HitInfo & HITINFO_UNK3)
4124 data << uint32(0);
4127 if(HitInfo & HITINFO_UNK1)
4129 data << uint32(0);
4130 data << float(0);
4131 data << float(0);
4132 data << float(0);
4133 data << float(0);
4134 data << float(0);
4135 data << float(0);
4136 data << float(0);
4137 data << float(0);
4138 for(uint8 i = 0; i < 5; ++i)
4140 data << float(0);
4141 data << float(0);
4143 data << uint32(0);
4146 SendMessageToSet( &data, true );
4149 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4151 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4153 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4154 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4156 uint32 triggered_spell_id = 0;
4157 Unit* target = pVictim;
4158 int32 basepoints0 = 0;
4160 switch(hasteSpell->SpellFamilyName)
4162 case SPELLFAMILY_ROGUE:
4164 switch(hasteSpell->Id)
4166 // Blade Flurry
4167 case 13877:
4168 case 33735:
4170 target = SelectNearbyTarget();
4171 if(!target)
4172 return false;
4173 basepoints0 = damage;
4174 triggered_spell_id = 22482;
4175 break;
4178 break;
4182 // processed charge only counting case
4183 if(!triggered_spell_id)
4184 return true;
4186 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4188 if(!triggerEntry)
4190 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4191 return false;
4194 // default case
4195 if(!target || target!=this && !target->isAlive())
4196 return false;
4198 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4199 return false;
4201 if(basepoints0)
4202 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4203 else
4204 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4206 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4207 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4209 return true;
4212 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4214 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4215 uint32 effIndex = triggeredByAura->GetEffIndex ();
4217 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4218 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4220 uint32 triggered_spell_id = 0;
4221 Unit* target = pVictim;
4222 int32 basepoints0 = 0;
4224 switch(dummySpell->SpellFamilyName)
4226 case SPELLFAMILY_GENERIC:
4228 switch (dummySpell->Id)
4230 // Eye for an Eye
4231 case 9799:
4232 case 25988:
4234 // prevent damage back from weapon special attacks
4235 if (!procSpell || procSpell->DmgClass != SPELL_DAMAGE_CLASS_MAGIC )
4236 return false;
4238 // return damage % to attacker but < 50% own total health
4239 basepoints0 = triggeredByAura->GetModifier()->m_amount*int32(damage)/100;
4240 if(basepoints0 > GetMaxHealth()/2)
4241 basepoints0 = GetMaxHealth()/2;
4243 triggered_spell_id = 25997;
4244 break;
4246 // Sweeping Strikes
4247 case 12328:
4248 case 18765:
4249 case 35429:
4251 // prevent chain of triggered spell from same triggered spell
4252 if(procSpell && procSpell->Id==26654)
4253 return false;
4255 target = SelectNearbyTarget();
4256 if(!target)
4257 return false;
4259 triggered_spell_id = 26654;
4260 break;
4262 // Unstable Power
4263 case 24658:
4265 if (!procSpell || procSpell->Id == 24659)
4266 return false;
4267 // Need remove one 24659 aura
4268 RemoveSingleAuraFromStack(24659, 0);
4269 RemoveSingleAuraFromStack(24659, 1);
4270 return true;
4272 // Restless Strength
4273 case 24661:
4275 // Need remove one 24662 aura
4276 RemoveSingleAuraFromStack(24662, 0);
4277 return true;
4279 // Adaptive Warding (Frostfire Regalia set)
4280 case 28764:
4282 if(!procSpell)
4283 return false;
4285 // find Mage Armor
4286 bool found = false;
4287 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4288 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4290 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4292 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4294 found=true;
4295 break;
4299 if(!found)
4300 return false;
4302 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4304 case SPELL_SCHOOL_NORMAL:
4305 case SPELL_SCHOOL_HOLY:
4306 return false; // ignored
4307 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4308 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4309 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4310 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4311 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4312 default:
4313 return false;
4316 target = this;
4317 break;
4319 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4320 case 27539:
4322 if(!procSpell)
4323 return false;
4325 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4327 case SPELL_SCHOOL_NORMAL:
4328 return false; // ignore
4329 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4330 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4331 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4332 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4333 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4334 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4335 default:
4336 return false;
4339 target = this;
4340 break;
4342 // Mana Leech (Passive) (Priest Pet Aura)
4343 case 28305:
4345 // Cast on owner
4346 target = GetOwner();
4347 if(!target)
4348 return false;
4350 basepoints0 = int32(damage * 2.5f); // manaregen
4351 triggered_spell_id = 34650;
4352 break;
4354 // Mark of Malice
4355 case 33493:
4357 // Cast finish spell at last charge
4358 if (triggeredByAura->GetAuraCharges() > 1)
4359 return false;
4361 target = this;
4362 triggered_spell_id = 33494;
4363 break;
4365 // Twisted Reflection (boss spell)
4366 case 21063:
4367 triggered_spell_id = 21064;
4368 break;
4369 // Vampiric Aura (boss spell)
4370 case 38196:
4372 basepoints0 = 3 * damage; // 300%
4373 if (basepoints0 < 0)
4374 return false;
4376 triggered_spell_id = 31285;
4377 target = this;
4378 break;
4380 // Aura of Madness (Darkmoon Card: Madness trinket)
4381 //=====================================================
4382 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4383 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4384 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4385 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4386 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4387 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4388 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4389 // 41011 Martyr Complex: +35 stamina (All classes)
4390 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4391 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4392 case 39446:
4394 if(GetTypeId() != TYPEID_PLAYER)
4395 return false;
4397 // Select class defined buff
4398 switch (getClass())
4400 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4401 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4403 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4404 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4405 break;
4407 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4408 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4410 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4411 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4412 break;
4414 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4415 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4416 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4417 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4419 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4420 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4421 break;
4423 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4425 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4426 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4427 break;
4429 default:
4430 return false;
4433 target = this;
4434 if (roll_chance_i(10))
4435 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4436 break;
4439 // TODO: need find item for aura and triggered spells
4440 // Sunwell Exalted Caster Neck (??? neck)
4441 // cast ??? Light's Wrath if Exalted by Aldor
4442 // cast ??? Arcane Bolt if Exalted by Scryers*/
4443 case 46569:
4444 return false; // disable for while
4447 if(GetTypeId() != TYPEID_PLAYER)
4448 return false;
4450 // Get Aldor reputation rank
4451 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4453 target = this;
4454 triggered_spell_id = ???
4455 break;
4457 // Get Scryers reputation rank
4458 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4460 triggered_spell_id = ???
4461 break;
4463 return false;
4464 }/**/
4465 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4466 // cast 45479 Light's Wrath if Exalted by Aldor
4467 // cast 45429 Arcane Bolt if Exalted by Scryers
4468 case 45481:
4470 if(GetTypeId() != TYPEID_PLAYER)
4471 return false;
4473 // Get Aldor reputation rank
4474 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4476 target = this;
4477 triggered_spell_id = 45479;
4478 break;
4480 // Get Scryers reputation rank
4481 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4483 triggered_spell_id = 45429;
4484 break;
4486 return false;
4488 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4489 // cast 45480 Light's Strength if Exalted by Aldor
4490 // cast 45428 Arcane Strike if Exalted by Scryers
4491 case 45482:
4493 if(GetTypeId() != TYPEID_PLAYER)
4494 return false;
4496 // Get Aldor reputation rank
4497 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4499 target = this;
4500 triggered_spell_id = 45480;
4501 break;
4503 // Get Scryers reputation rank
4504 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4506 triggered_spell_id = 45428;
4507 break;
4509 return false;
4511 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4512 // cast 45431 Arcane Insight if Exalted by Aldor
4513 // cast 45432 Light's Ward if Exalted by Scryers
4514 case 45483:
4516 if(GetTypeId() != TYPEID_PLAYER)
4517 return false;
4519 // Get Aldor reputation rank
4520 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4522 target = this;
4523 triggered_spell_id = 45432;
4524 break;
4526 // Get Scryers reputation rank
4527 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4529 target = this;
4530 triggered_spell_id = 45431;
4531 break;
4533 return false;
4535 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4536 // cast 45478 Light's Salvation if Exalted by Aldor
4537 // cast 45430 Arcane Surge if Exalted by Scryers
4538 case 45484:
4540 if(GetTypeId() != TYPEID_PLAYER)
4541 return false;
4543 // Get Aldor reputation rank
4544 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4546 target = this;
4547 triggered_spell_id = 45478;
4548 break;
4550 // Get Scryers reputation rank
4551 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4553 triggered_spell_id = 45430;
4554 break;
4556 return false;
4558 // Living Seed
4559 case 48504:
4561 triggered_spell_id = 48503;
4562 basepoints0 = triggeredByAura->GetModifier()->m_amount;
4563 target = this;
4564 break;
4566 // Vampiric Touch (generic, used by some boss)
4567 case 52723:
4568 case 60501:
4570 triggered_spell_id = 52724;
4571 basepoints0 = damage / 2;
4572 target = this;
4573 break;
4576 break;
4578 case SPELLFAMILY_MAGE:
4580 // Magic Absorption
4581 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4583 if (getPowerType() != POWER_MANA)
4584 return false;
4586 // mana reward
4587 basepoints0 = (triggeredByAura->GetModifier()->m_amount * GetMaxPower(POWER_MANA) / 100);
4588 target = this;
4589 triggered_spell_id = 29442;
4590 break;
4592 // Master of Elements
4593 if (dummySpell->SpellIconID == 1920)
4595 if(!procSpell)
4596 return false;
4598 // mana cost save
4599 basepoints0 = procSpell->manaCost * triggeredByAura->GetModifier()->m_amount/100;
4600 if( basepoints0 <=0 )
4601 return false;
4603 target = this;
4604 triggered_spell_id = 29077;
4605 break;
4607 // Hot Streak
4608 if (dummySpell->SpellIconID == 2999)
4610 if (triggeredByAura->GetEffIndex()!=0)
4611 return true;
4612 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4613 if (!counter)
4614 return true;
4616 // Count spell criticals in a row in second aura
4617 Modifier *mod = counter->GetModifier();
4618 if (procEx & PROC_EX_CRITICAL_HIT)
4620 mod->m_amount *=2;
4621 if (mod->m_amount < 100) // not enough
4622 return true;
4623 // Crititcal counted -> roll chance
4624 if (roll_chance_i(triggeredByAura->GetModifier()->m_amount))
4625 CastSpell(this, 48108, true, castItem, triggeredByAura);
4627 mod->m_amount = 25;
4628 return true;
4630 // Incanter's Regalia set (add trigger chance to Mana Shield)
4631 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4633 if(GetTypeId() != TYPEID_PLAYER)
4634 return false;
4636 target = this;
4637 triggered_spell_id = 37436;
4638 break;
4640 switch(dummySpell->Id)
4642 // Ignite
4643 case 11119:
4644 case 11120:
4645 case 12846:
4646 case 12847:
4647 case 12848:
4649 switch (dummySpell->Id)
4651 case 11119: basepoints0 = int32(0.04f*damage); break;
4652 case 11120: basepoints0 = int32(0.08f*damage); break;
4653 case 12846: basepoints0 = int32(0.12f*damage); break;
4654 case 12847: basepoints0 = int32(0.16f*damage); break;
4655 case 12848: basepoints0 = int32(0.20f*damage); break;
4656 default:
4657 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4658 return false;
4661 triggered_spell_id = 12654;
4662 break;
4664 // Combustion
4665 case 11129:
4667 //last charge and crit
4668 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4670 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4671 return true; // charge counting (will removed)
4674 CastSpell(this, 28682, true, castItem, triggeredByAura);
4675 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4678 break;
4680 case SPELLFAMILY_WARRIOR:
4682 // Retaliation
4683 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4685 // check attack comes not from behind
4686 if (!HasInArc(M_PI, pVictim))
4687 return false;
4689 triggered_spell_id = 22858;
4690 break;
4692 else if (dummySpell->SpellIconID == 1697) // Second Wind
4694 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4695 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4696 return false;
4697 // Need stun or root mechanic
4698 if (procSpell->Mechanic != MECHANIC_ROOT && procSpell->Mechanic != MECHANIC_STUN)
4700 int32 i;
4701 for (i=0; i<3; i++)
4702 if (procSpell->EffectMechanic[i] == MECHANIC_ROOT || procSpell->EffectMechanic[i] == MECHANIC_STUN)
4703 break;
4704 if (i == 3)
4705 return false;
4708 switch (dummySpell->Id)
4710 case 29838: triggered_spell_id=29842; break;
4711 case 29834: triggered_spell_id=29841; break;
4712 default:
4713 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4714 return false;
4717 target = this;
4718 break;
4720 break;
4722 case SPELLFAMILY_WARLOCK:
4724 // Seed of Corruption
4725 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4727 Modifier* mod = triggeredByAura->GetModifier();
4728 // if damage is more than need or target die from damage deal finish spell
4729 if( mod->m_amount <= damage || GetHealth() <= damage )
4731 // remember guid before aura delete
4732 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4734 // Remove aura (before cast for prevent infinite loop handlers)
4735 RemoveAurasDueToSpell(triggeredByAura->GetId());
4737 // Cast finish spell (triggeredByAura already not exist!)
4738 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4739 return true; // no hidden cooldown
4742 // Damage counting
4743 mod->m_amount-=damage;
4744 return true;
4746 // Seed of Corruption (Mobs cast) - no die req
4747 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4749 Modifier* mod = triggeredByAura->GetModifier();
4750 // if damage is more than need deal finish spell
4751 if( mod->m_amount <= damage )
4753 // remember guid before aura delete
4754 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4756 // Remove aura (before cast for prevent infinite loop handlers)
4757 RemoveAurasDueToSpell(triggeredByAura->GetId());
4759 // Cast finish spell (triggeredByAura already not exist!)
4760 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
4761 return true; // no hidden cooldown
4763 // Damage counting
4764 mod->m_amount-=damage;
4765 return true;
4767 switch(dummySpell->Id)
4769 // Nightfall
4770 case 18094:
4771 case 18095:
4773 target = this;
4774 triggered_spell_id = 17941;
4775 break;
4777 //Soul Leech
4778 case 30293:
4779 case 30295:
4780 case 30296:
4782 // health
4783 basepoints0 = int32(damage*triggeredByAura->GetModifier()->m_amount/100);
4784 target = this;
4785 triggered_spell_id = 30294;
4786 break;
4788 // Shadowflame (Voidheart Raiment set bonus)
4789 case 37377:
4791 triggered_spell_id = 37379;
4792 break;
4794 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
4795 case 37381:
4797 target = GetPet();
4798 if(!target)
4799 return false;
4801 // heal amount
4802 basepoints0 = damage * triggeredByAura->GetModifier()->m_amount/100;
4803 triggered_spell_id = 37382;
4804 break;
4806 // Shadowflame Hellfire (Voidheart Raiment set bonus)
4807 case 39437:
4809 triggered_spell_id = 37378;
4810 break;
4813 break;
4815 case SPELLFAMILY_PRIEST:
4817 // Vampiric Touch
4818 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
4820 if(!pVictim || !pVictim->isAlive())
4821 return false;
4823 // pVictim is caster of aura
4824 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
4825 return false;
4827 // energize amount
4828 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
4829 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4830 return true; // no hidden cooldown
4832 switch(dummySpell->Id)
4834 // Vampiric Embrace
4835 case 15286:
4837 if(!pVictim || !pVictim->isAlive())
4838 return false;
4840 // pVictim is caster of aura
4841 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
4842 return false;
4844 // heal amount
4845 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
4846 pVictim->CastCustomSpell(pVictim,15290,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4847 return true; // no hidden cooldown
4849 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
4850 case 40438:
4852 // Shadow Word: Pain
4853 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
4854 triggered_spell_id = 40441;
4855 // Renew
4856 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
4857 triggered_spell_id = 40440;
4858 else
4859 return false;
4861 target = this;
4862 break;
4864 // Oracle Healing Bonus ("Garments of the Oracle" set)
4865 case 26169:
4867 // heal amount
4868 basepoints0 = int32(damage * 10/100);
4869 target = this;
4870 triggered_spell_id = 26170;
4871 break;
4873 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
4874 case 39372:
4876 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
4877 return false;
4879 // heal amount
4880 basepoints0 = int32(damage * 2 / 100);
4881 target = this;
4882 triggered_spell_id = 39373;
4883 break;
4885 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
4886 case 28809:
4888 triggered_spell_id = 28810;
4889 break;
4892 break;
4894 case SPELLFAMILY_DRUID:
4896 switch(dummySpell->Id)
4898 // Healing Touch (Dreamwalker Raiment set)
4899 case 28719:
4901 // mana back
4902 basepoints0 = int32(procSpell->manaCost * 30 / 100);
4903 target = this;
4904 triggered_spell_id = 28742;
4905 break;
4907 // Healing Touch Refund (Idol of Longevity trinket)
4908 case 28847:
4910 target = this;
4911 triggered_spell_id = 28848;
4912 break;
4914 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
4915 case 37288:
4916 case 37295:
4918 target = this;
4919 triggered_spell_id = 37238;
4920 break;
4922 // Druid Tier 6 Trinket
4923 case 40442:
4925 float chance;
4927 // Starfire
4928 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
4930 triggered_spell_id = 40445;
4931 chance = 25.f;
4933 // Rejuvenation
4934 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
4936 triggered_spell_id = 40446;
4937 chance = 25.f;
4939 // Mangle (cat/bear)
4940 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
4942 triggered_spell_id = 40452;
4943 chance = 40.f;
4945 else
4946 return false;
4948 if (!roll_chance_f(chance))
4949 return false;
4951 target = this;
4952 break;
4954 // Maim Interrupt
4955 case 44835:
4957 // Deadly Interrupt Effect
4958 triggered_spell_id = 32747;
4959 break;
4962 // Eclipse
4963 if (dummySpell->SpellIconID == 2856)
4965 if (!procSpell)
4966 return false;
4967 // Only 0 aura can proc
4968 if (triggeredByAura->GetEffIndex()!=0)
4969 return true;
4970 // Wrath crit
4971 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
4973 if (!roll_chance_i(60))
4974 return false;
4975 triggered_spell_id = 48518;
4976 target = this;
4977 break;
4979 // Starfire crit
4980 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
4982 triggered_spell_id = 48517;
4983 target = this;
4984 break;
4986 return false;
4988 // Living Seed
4989 else if (dummySpell->SpellIconID == 2860)
4991 triggered_spell_id = 48504;
4992 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
4993 break;
4995 break;
4997 case SPELLFAMILY_ROGUE:
4999 switch(dummySpell->Id)
5001 // Deadly Throw Interrupt
5002 case 32748:
5004 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5005 if(this == pVictim)
5006 return false;
5008 triggered_spell_id = 32747;
5009 break;
5012 // Quick Recovery
5013 if( dummySpell->SpellIconID == 2116 )
5015 if(!procSpell)
5016 return false;
5018 // energy cost save
5019 basepoints0 = procSpell->manaCost * triggeredByAura->GetModifier()->m_amount/100;
5020 if(basepoints0 <= 0)
5021 return false;
5023 target = this;
5024 triggered_spell_id = 31663;
5025 break;
5027 break;
5029 case SPELLFAMILY_HUNTER:
5031 // Thrill of the Hunt
5032 if ( dummySpell->SpellIconID == 2236 )
5034 if(!procSpell)
5035 return false;
5037 // mana cost save
5038 basepoints0 = procSpell->manaCost * 40/100;
5039 if(basepoints0 <= 0)
5040 return false;
5042 target = this;
5043 triggered_spell_id = 34720;
5044 break;
5046 break;
5048 case SPELLFAMILY_PALADIN:
5050 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5051 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && triggeredByAura->GetEffIndex()==0)
5053 triggered_spell_id = 25742;
5054 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5055 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5056 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5057 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5058 break;
5060 // Seal of Blood do damage trigger
5061 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5063 switch(triggeredByAura->GetEffIndex())
5065 case 0:
5066 triggered_spell_id = 31893;
5067 break;
5068 case 1:
5070 // damage
5071 damage += CalculateDamage(BASE_ATTACK, false) * 35 / 100; // add spell damage from prev effect (35%)
5072 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5074 target = this;
5075 triggered_spell_id = 32221;
5076 break;
5081 switch(dummySpell->Id)
5083 // Holy Power (Redemption Armor set)
5084 case 28789:
5086 if(!pVictim)
5087 return false;
5089 // Set class defined buff
5090 switch (pVictim->getClass())
5092 case CLASS_PALADIN:
5093 case CLASS_PRIEST:
5094 case CLASS_SHAMAN:
5095 case CLASS_DRUID:
5096 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5097 break;
5098 case CLASS_MAGE:
5099 case CLASS_WARLOCK:
5100 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5101 break;
5102 case CLASS_HUNTER:
5103 case CLASS_ROGUE:
5104 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5105 break;
5106 case CLASS_WARRIOR:
5107 triggered_spell_id = 28790; // Increases the friendly target's armor
5108 break;
5109 default:
5110 return false;
5112 break;
5114 // Seal of Vengeance (damage calc on apply aura)
5115 case 31801:
5117 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5118 return false;
5120 triggered_spell_id = 31803;
5121 break;
5123 // Spiritual Attunement
5124 case 31785:
5125 case 33776:
5127 // if healed by another unit (pVictim)
5128 if(this == pVictim)
5129 return false;
5131 // heal amount
5132 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5133 target = this;
5134 triggered_spell_id = 31786;
5135 break;
5137 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5138 case 40470:
5140 if( !procSpell )
5141 return false;
5143 float chance;
5145 // Flash of light/Holy light
5146 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5148 triggered_spell_id = 40471;
5149 chance = 15.f;
5151 // Judgement
5152 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5154 triggered_spell_id = 40472;
5155 chance = 50.f;
5157 else
5158 return false;
5160 if (!roll_chance_f(chance))
5161 return false;
5163 break;
5165 // Glyph of Divinity
5166 case 54939:
5168 // Lookup base amount mana restore
5169 for (int i=0; i<3;i++)
5170 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5172 int32 mana = procSpell->EffectBasePoints[i];
5173 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5174 break;
5176 return true;
5178 // Glyph of Flash of Light
5179 case 54936:
5181 triggered_spell_id = 54957;
5182 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5183 break;
5185 // Glyph of Holy Light
5186 case 54937:
5188 triggered_spell_id = 54968;
5189 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5190 break;
5193 break;
5195 case SPELLFAMILY_SHAMAN:
5197 switch(dummySpell->Id)
5199 // Totemic Power (The Earthshatterer set)
5200 case 28823:
5202 if( !pVictim )
5203 return false;
5205 // Set class defined buff
5206 switch (pVictim->getClass())
5208 case CLASS_PALADIN:
5209 case CLASS_PRIEST:
5210 case CLASS_SHAMAN:
5211 case CLASS_DRUID:
5212 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5213 break;
5214 case CLASS_MAGE:
5215 case CLASS_WARLOCK:
5216 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5217 break;
5218 case CLASS_HUNTER:
5219 case CLASS_ROGUE:
5220 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5221 break;
5222 case CLASS_WARRIOR:
5223 triggered_spell_id = 28827; // Increases the friendly target's armor
5224 break;
5225 default:
5226 return false;
5228 break;
5230 // Lesser Healing Wave (Totem of Flowing Water Relic)
5231 case 28849:
5233 target = this;
5234 triggered_spell_id = 28850;
5235 break;
5237 // Windfury Weapon (Passive) 1-5 Ranks
5238 case 33757:
5240 if(GetTypeId()!=TYPEID_PLAYER)
5241 return false;
5243 if(!castItem || !castItem->IsEquipped())
5244 return false;
5246 // custom cooldown processing case
5247 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5248 return false;
5250 uint32 spellId;
5251 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5253 case 283: spellId = 33757; break; //1 Rank
5254 case 284: spellId = 33756; break; //2 Rank
5255 case 525: spellId = 33755; break; //3 Rank
5256 case 1669:spellId = 33754; break; //4 Rank
5257 case 2636:spellId = 33727; break; //5 Rank
5258 default:
5260 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5261 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5262 return false;
5266 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5267 if(!windfurySpellEntry)
5269 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5270 return false;
5273 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry,0,windfurySpellEntry->EffectBasePoints[0],pVictim);
5275 // Off-Hand case
5276 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5278 // Value gained from additional AP
5279 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5280 triggered_spell_id = 33750;
5282 // Main-Hand case
5283 else
5285 // Value gained from additional AP
5286 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5287 triggered_spell_id = 25504;
5290 // apply cooldown before cast to prevent processing itself
5291 if( cooldown )
5292 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5294 // Attack Twice
5295 for ( uint32 i = 0; i<2; ++i )
5296 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5298 return true;
5300 // Shaman Tier 6 Trinket
5301 case 40463:
5303 if( !procSpell )
5304 return false;
5306 float chance;
5307 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5309 triggered_spell_id = 40465; // Lightning Bolt
5310 chance = 15.f;
5312 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5314 triggered_spell_id = 40465; // Lesser Healing Wave
5315 chance = 10.f;
5317 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5319 triggered_spell_id = 40466; // Stormstrike
5320 chance = 50.f;
5322 else
5323 return false;
5325 if (!roll_chance_f(chance))
5326 return false;
5328 target = this;
5329 break;
5331 // Glyph of Healing Wave
5332 case 55440:
5334 // Not proc from self heals
5335 if (this==pVictim)
5336 return false;
5337 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5338 target = this;
5339 triggered_spell_id = 55533;
5340 break;
5344 // Earth Shield
5345 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5347 basepoints0 = triggeredByAura->GetModifier()->m_amount;
5348 target = this;
5349 triggered_spell_id = 379;
5350 break;
5352 // Lightning Overload
5353 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5355 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5356 return false;
5358 // custom cooldown processing case
5359 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5360 return false;
5362 uint32 spellId = 0;
5363 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5364 switch (procSpell->Id)
5366 // Lightning Bolt
5367 case 403: spellId = 45284; break; // Rank 1
5368 case 529: spellId = 45286; break; // Rank 2
5369 case 548: spellId = 45287; break; // Rank 3
5370 case 915: spellId = 45288; break; // Rank 4
5371 case 943: spellId = 45289; break; // Rank 5
5372 case 6041: spellId = 45290; break; // Rank 6
5373 case 10391: spellId = 45291; break; // Rank 7
5374 case 10392: spellId = 45292; break; // Rank 8
5375 case 15207: spellId = 45293; break; // Rank 9
5376 case 15208: spellId = 45294; break; // Rank 10
5377 case 25448: spellId = 45295; break; // Rank 11
5378 case 25449: spellId = 45296; break; // Rank 12
5379 case 49237: spellId = 49239; break; // Rank 13
5380 case 49238: spellId = 49240; break; // Rank 14
5381 // Chain Lightning
5382 case 421: spellId = 45297; break; // Rank 1
5383 case 930: spellId = 45298; break; // Rank 2
5384 case 2860: spellId = 45299; break; // Rank 3
5385 case 10605: spellId = 45300; break; // Rank 4
5386 case 25439: spellId = 45301; break; // Rank 5
5387 case 25442: spellId = 45302; break; // Rank 6
5388 case 49268: spellId = 49270; break; // Rank 7
5389 case 49269: spellId = 49271; break; // Rank 8
5390 default:
5391 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5392 return false;
5394 // No thread generated mod
5395 SpellModifier *mod = new SpellModifier;
5396 mod->op = SPELLMOD_THREAT;
5397 mod->value = -100;
5398 mod->type = SPELLMOD_PCT;
5399 mod->spellId = dummySpell->Id;
5400 mod->mask = 0x0000000000000003LL;
5401 mod->mask2= 0LL;
5402 ((Player*)this)->AddSpellMod(mod, true);
5404 // Remove cooldown (Chain Lightning - have Category Recovery time)
5405 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5406 ((Player*)this)->RemoveSpellCooldown(spellId);
5408 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5410 ((Player*)this)->AddSpellMod(mod, false);
5412 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5413 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5415 return true;
5417 break;
5419 case SPELLFAMILY_DEATHKNIGHT:
5421 // Vendetta
5422 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
5424 basepoints0 = triggeredByAura->GetModifier()->m_amount * GetMaxHealth() / 100;
5425 triggered_spell_id = 50181;
5426 target = this;
5427 break;
5429 // Necrosis
5430 else if (dummySpell->SpellIconID == 2709)
5432 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5433 triggered_spell_id = 51460;
5434 break;
5436 // Butchery
5437 else if (dummySpell->SpellIconID == 2664)
5439 basepoints0 = triggeredByAura->GetModifier()->m_amount;
5440 triggered_spell_id = 50163;
5441 target = this;
5442 break;
5444 break;
5446 default:
5447 break;
5450 // processed charge only counting case
5451 if(!triggered_spell_id)
5452 return true;
5454 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5456 if(!triggerEntry)
5458 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5459 return false;
5462 // default case
5463 if(!target || target!=this && !target->isAlive())
5464 return false;
5466 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5467 return false;
5469 if(basepoints0)
5470 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5471 else
5472 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5474 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5475 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5477 return true;
5480 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5482 // Get triggered aura spell info
5483 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5485 // Basepoints of trigger aura
5486 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5488 // Set trigger spell id, target, custom basepoints
5489 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
5490 Unit* target = NULL;
5491 int32 basepoints0 = 0;
5493 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
5494 basepoints0 = triggerAmount;
5496 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5497 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5499 // Try handle uncnown trigger spells
5500 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
5502 switch (auraSpellInfo->SpellFamilyName)
5504 case SPELLFAMILY_GENERIC:
5505 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
5506 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
5507 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
5508 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
5509 trigger_spell_id = 23781;
5510 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
5511 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
5513 // trigger_spell_id = 48877;
5515 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
5517 // trigger_spell_id = 59233;
5519 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
5521 // trigger_spell_id = 29471; // gain mana
5522 // 27526; // drain mana if possible
5524 //else if (auraSpellInfo->Id==50844) // Blood Mirror
5525 //else if (auraSpellInfo->Id==54476) // Blood Presence
5526 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
5527 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
5528 //else if (auraSpellInfo->Id==52856) // Charge
5529 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
5531 // Pct value stored in dummy
5532 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
5533 target = pVictim;
5534 break;
5536 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
5537 // trigger_spell_id = 41249;
5538 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
5539 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
5540 //else if (auraSpellInfo->Id==41054) // Copy Weapon
5541 // trigger_spell_id = 41055;
5542 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
5543 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
5544 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
5546 uint32 stat = 0;
5547 // strength
5548 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
5549 // agility
5550 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
5551 // intellect
5552 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
5553 // spirit
5554 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
5556 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
5557 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
5558 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
5559 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
5560 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
5561 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
5562 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
5563 trigger_spell_id = 33898;
5564 //else if (auraSpellInfo->Id==18943) // Double Attack
5565 //else if (auraSpellInfo->Id==19194) // Double Attack
5566 //else if (auraSpellInfo->Id==19817) // Double Attack
5567 //else if (auraSpellInfo->Id==19818) // Double Attack
5568 //else if (auraSpellInfo->Id==22835) // Drunken Rage
5569 // trigger_spell_id = 14822;
5571 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
5573 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
5575 case 34191:
5576 case 34329:
5577 case 34524:
5578 case 34582:
5579 case 36733:
5580 break;
5581 default:
5582 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
5583 return false;
5585 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
5586 switch (procSpell->School)
5588 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
5589 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
5590 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
5591 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
5592 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
5593 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
5594 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
5595 default:
5596 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
5597 return false;
5601 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
5602 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
5603 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
5604 //else if (auraSpellInfo->Id==35321) // Gushing Wound
5605 //else if (auraSpellInfo->Id==38363) // Gushing Wound
5606 //else if (auraSpellInfo->Id==39215) // Gushing Wound
5607 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
5608 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
5609 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
5610 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
5611 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
5612 //else if (auraSpellInfo->Id==40250) // Improved Duration
5613 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
5614 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
5615 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
5616 // Mana Drain Trigger
5618 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
5619 if (this && this->isAlive())
5620 CastSpell(this, 29471, true, castItem, triggeredByAura);
5621 if (pVictim && pVictim->isAlive())
5622 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
5623 return true;
5625 //else if (auraSpellInfo->Id==55580) // Mana Link
5626 //else if (auraSpellInfo->Id==45903) // Offensive State
5627 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
5628 //else if (auraSpellInfo->Id==43453) // Rune Ward
5629 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
5630 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
5631 //else if (auraSpellInfo->Id==34783) // Spell Reflection
5632 //else if (auraSpellInfo->Id==36096) // Spell Reflection
5633 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
5634 //else if (auraSpellInfo->Id==36207) // Steal Weapon
5635 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
5636 //else if (auraSpellInfo->Id==35205) // Vanish
5637 //else if (auraSpellInfo->Id==42730) // Woe Strike
5638 //else if (auraSpellInfo->Id==59735) // Woe Strike
5639 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
5640 break;
5641 case SPELLFAMILY_MAGE:
5642 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
5644 switch (auraSpellInfo->Id)
5646 case 31641: // Rank 1
5647 case 31642: // Rank 2
5648 trigger_spell_id = 31643;
5649 break;
5650 default:
5651 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
5652 return false;
5655 break;
5656 case SPELLFAMILY_WARRIOR:
5657 if (auraSpellInfo->Id == 50421) // Scent of Blood
5658 trigger_spell_id = 50422;
5659 break;
5660 case SPELLFAMILY_WARLOCK:
5662 // Pyroclasm
5663 if (auraSpellInfo->SpellIconID == 1137)
5665 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
5666 return false;
5667 // Calculate spell tick count for spells
5668 uint32 tick = 1; // Default tick = 1
5670 // Hellfire have 15 tick
5671 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
5672 tick = 15;
5673 // Rain of Fire have 4 tick
5674 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
5675 tick = 4;
5676 else
5677 return false;
5679 // Calculate chance = baseChance / tick
5680 float chance = 0;
5681 switch (auraSpellInfo->Id)
5683 case 18096: chance = 13.0f / tick; break;
5684 case 18073: chance = 26.0f / tick; break;
5686 // Roll chance
5687 if (!roll_chance_f(chance))
5688 return false;
5690 trigger_spell_id = 18093;
5692 // Drain Soul
5693 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
5695 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
5696 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
5698 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
5700 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
5701 // Drain Soul
5702 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
5703 break;
5706 // Not remove charge (aura removed on death in any cases)
5707 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
5708 return false;
5710 // Nether Protection
5711 else if (auraSpellInfo->SpellIconID == 1985)
5713 if (!procSpell)
5714 return false;
5715 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5717 case SPELL_SCHOOL_NORMAL:
5718 case SPELL_SCHOOL_HOLY:
5719 return false; // ignore
5720 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
5721 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
5722 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
5723 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
5724 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
5725 default:
5726 return false;
5729 break;
5731 case SPELLFAMILY_PRIEST:
5733 // Greater Heal Refund
5734 if (auraSpellInfo->Id==37594)
5735 trigger_spell_id = 37595;
5736 // Blessed Recovery
5737 else if (auraSpellInfo->SpellIconID == 1875)
5739 switch (auraSpellInfo->Id)
5741 case 27811: trigger_spell_id = 27813; break;
5742 case 27815: trigger_spell_id = 27817; break;
5743 case 27816: trigger_spell_id = 27818; break;
5744 default:
5745 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
5746 return false;
5748 basepoints0 = damage * triggerAmount / 100 / 3;
5749 target = this;
5751 break;
5753 case SPELLFAMILY_DRUID:
5755 // Druid Forms Trinket
5756 if (auraSpellInfo->Id==37336)
5758 switch(m_form)
5760 case FORM_NONE: trigger_spell_id = 37344;break;
5761 case FORM_CAT: trigger_spell_id = 37341;break;
5762 case FORM_BEAR:
5763 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
5764 case FORM_TREE: trigger_spell_id = 37342;break;
5765 case FORM_MOONKIN: trigger_spell_id = 37343;break;
5766 default:
5767 return false;
5770 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
5771 // trigger_spell_id = ????;
5772 // Leader of the Pack
5773 else if (auraSpellInfo->Id == 24932)
5775 if (triggerAmount == 0)
5776 return false;
5777 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5778 trigger_spell_id = 34299;
5780 break;
5782 case SPELLFAMILY_HUNTER:
5783 break;
5784 case SPELLFAMILY_PALADIN:
5787 // Blessed Life
5788 if (auraSpellInfo->SpellIconID == 2137)
5790 switch (auraSpellInfo->Id)
5792 case 31828: // Rank 1
5793 case 31829: // Rank 2
5794 case 31830: // Rank 3
5795 break;
5796 default:
5797 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
5798 return false;
5802 // Healing Discount
5803 if (auraSpellInfo->Id==37705)
5805 trigger_spell_id = 37706;
5806 target = this;
5808 // Soul Preserver
5809 if (auraSpellInfo->Id==60510)
5811 trigger_spell_id = 60515;
5812 target = this;
5814 // Illumination
5815 else if (auraSpellInfo->SpellIconID==241)
5817 if(!procSpell)
5818 return false;
5819 // procspell is triggered spell but we need mana cost of original casted spell
5820 uint32 originalSpellId = procSpell->Id;
5821 // Holy Shock
5822 if(procSpell->SpellFamilyFlags & 0x00200000)
5824 switch(procSpell->Id)
5826 case 25914: originalSpellId = 20473; break;
5827 case 25913: originalSpellId = 20929; break;
5828 case 25903: originalSpellId = 20930; break;
5829 case 27175: originalSpellId = 27174; break;
5830 case 33074: originalSpellId = 33072; break;
5831 default:
5832 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
5833 return false;
5836 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
5837 if(!originalSpell)
5839 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
5840 return false;
5842 // percent stored in effect 1 (class scripts) base points
5843 basepoints0 = originalSpell->manaCost*(auraSpellInfo->EffectBasePoints[1]+1)/100;
5844 trigger_spell_id = 20272;
5845 target = this;
5847 // Lightning Capacitor
5848 else if (auraSpellInfo->Id==37657)
5850 if(!pVictim || !pVictim->isAlive())
5851 return false;
5852 // stacking
5853 CastSpell(this, 37658, true, NULL, triggeredByAura);
5854 // counting
5855 uint32 count = 0;
5856 AuraList const& dummyAura = GetAurasByType(SPELL_AURA_DUMMY);
5857 for(AuraList::const_iterator itr = dummyAura.begin(); itr != dummyAura.end(); ++itr)
5858 if((*itr)->GetId()==37658)
5859 ++count;
5860 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
5861 if(count < triggerAmount)
5862 return false;
5864 RemoveAurasDueToSpell(37658);
5865 trigger_spell_id = 37661;
5866 target = pVictim;
5868 // Thunder Capacitor
5869 else if (auraSpellInfo->Id == 54841)
5871 if(!pVictim || !pVictim->isAlive())
5872 return false;
5873 // stacking
5874 CastSpell(this, 54842, true, NULL, triggeredByAura);
5875 // counting
5876 uint32 count = 0;
5877 AuraList const& dummyAura = GetAurasByType(SPELL_AURA_DUMMY);
5878 for(AuraList::const_iterator itr = dummyAura.begin(); itr != dummyAura.end(); ++itr)
5879 if((*itr)->GetId()==54842)
5880 ++count;
5881 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
5882 if(count < triggerAmount)
5883 return false;
5885 RemoveAurasDueToSpell(54842);
5886 trigger_spell_id = 54843;
5887 target = pVictim;
5889 break;
5891 case SPELLFAMILY_SHAMAN:
5893 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
5894 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
5896 switch(auraSpellInfo->Id)
5898 case 324: // Rank 1
5899 trigger_spell_id = 26364; break;
5900 case 325: // Rank 2
5901 trigger_spell_id = 26365; break;
5902 case 905: // Rank 3
5903 trigger_spell_id = 26366; break;
5904 case 945: // Rank 4
5905 trigger_spell_id = 26367; break;
5906 case 8134: // Rank 5
5907 trigger_spell_id = 26369; break;
5908 case 10431: // Rank 6
5909 trigger_spell_id = 26370; break;
5910 case 10432: // Rank 7
5911 trigger_spell_id = 26363; break;
5912 case 25469: // Rank 8
5913 trigger_spell_id = 26371; break;
5914 case 25472: // Rank 9
5915 trigger_spell_id = 26372; break;
5916 case 49280: // Rank 10
5917 trigger_spell_id = 49278; break;
5918 case 49281: // Rank 11
5919 trigger_spell_id = 49279; break;
5920 default:
5921 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
5922 return false;
5925 // Lightning Shield (The Ten Storms set)
5926 else if (auraSpellInfo->Id == 23551)
5928 trigger_spell_id = 23552;
5929 target = pVictim;
5931 // Damage from Lightning Shield (The Ten Storms set)
5932 else if (auraSpellInfo->Id == 23552)
5933 trigger_spell_id = 27635;
5934 // Mana Surge (The Earthfury set)
5935 else if (auraSpellInfo->Id == 23572)
5937 if(!procSpell)
5938 return false;
5939 basepoints0 = procSpell->manaCost * 35 / 100;
5940 trigger_spell_id = 23571;
5941 target = this;
5943 // Nature's Guardian
5944 else if (auraSpellInfo->SpellIconID == 2013)
5946 // Check health condition - should drop to less 30% (damage deal after this!)
5947 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
5948 return false;
5950 if(pVictim && pVictim->isAlive())
5951 pVictim->getThreatManager().modifyThreatPercent(this,-10);
5953 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5954 trigger_spell_id = 31616;
5955 target = this;
5957 break;
5959 case SPELLFAMILY_DEATHKNIGHT:
5961 // Acclimation
5962 if (auraSpellInfo->SpellIconID == 1930)
5964 if (!procSpell)
5965 return false;
5966 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5968 case SPELL_SCHOOL_NORMAL:
5969 return false; // ignore
5970 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
5971 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
5972 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
5973 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
5974 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
5975 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
5976 default:
5977 return false;
5980 // Blood Presence
5981 else if (auraSpellInfo->Id == 48266)
5983 if (GetTypeId() != TYPEID_PLAYER)
5984 return false;
5985 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
5986 return false;
5987 trigger_spell_id = 50475;
5988 basepoints0 = damage * triggerAmount / 100;
5990 break;
5992 default:
5993 break;
5997 // All ok. Check current trigger spell
5998 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
5999 if ( triggerEntry == NULL )
6001 // Not cast unknown spell
6002 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6003 return false;
6006 // not allow proc extra attack spell at extra attack
6007 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6008 return false;
6010 // Costum requirements (not listed in procEx) Warning! damage dealing after this
6011 // Custom triggered spells
6012 switch (auraSpellInfo->Id)
6014 // Persistent Shield (Scarab Brooch trinket)
6015 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6016 case 26467:
6018 basepoints0 = damage * 15 / 100;
6019 target = pVictim;
6020 trigger_spell_id = 26470;
6021 break;
6023 // Cheat Death
6024 case 28845:
6026 // When your health drops below 20% ....
6027 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6028 return false;
6029 break;
6031 // Deadly Swiftness (Rank 1)
6032 case 31255:
6034 // whenever you deal damage to a target who is below 20% health.
6035 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6036 return false;
6038 target = this;
6039 trigger_spell_id = 22588;
6041 // Greater Heal Refund (Avatar Raiment set)
6042 case 37594:
6044 // Not give if target alredy have full health
6045 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6046 return false;
6047 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6048 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6049 return false;
6050 break;
6052 // Bonus Healing (Crystal Spire of Karabor mace)
6053 case 40971:
6055 // If your target is below $s1% health
6056 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6057 return false;
6058 break;
6060 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6061 case 45057:
6063 // reduce you below $s1% health
6064 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6065 return false;
6066 break;
6070 // Costum basepoints/target for exist spell
6071 // dummy basepoints or other customs
6072 switch(trigger_spell_id)
6074 // Cast positive spell on enemy target
6075 case 7099: // Curse of Mending
6076 case 39647: // Curse of Mending
6077 case 29494: // Temptation
6078 case 20233: // Improved Lay on Hands (cast on target)
6080 target = pVictim;
6081 break;
6083 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
6084 case 15250: // Rogue Setup
6086 if(!pVictim || pVictim != getVictim()) // applied only for main target
6087 return false;
6088 break; // continue normal case
6090 // Finish movies that add combo
6091 case 14189: // Seal Fate (Netherblade set)
6092 case 14157: // Ruthlessness
6094 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6095 break;
6097 // Shamanistic Rage triggered spell
6098 case 30824:
6100 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6101 trigger_spell_id = 30824;
6102 break;
6104 // Enlightenment (trigger only from mana cost spells)
6105 case 35095:
6107 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6108 return false;
6109 break;
6113 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6114 return false;
6116 // try detect target manually if not set
6117 if ( target == NULL )
6118 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6120 // default case
6121 if(!target || target!=this && !target->isAlive())
6122 return false;
6124 if(basepoints0)
6125 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6126 else
6127 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6129 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6130 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6132 return true;
6135 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6137 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6139 if(!pVictim || !pVictim->isAlive())
6140 return false;
6142 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6143 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6145 uint32 triggered_spell_id = 0;
6147 switch(scriptId)
6149 case 836: // Improved Blizzard (Rank 1)
6151 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6152 return false;
6153 triggered_spell_id = 12484;
6154 break;
6156 case 988: // Improved Blizzard (Rank 2)
6158 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6159 return false;
6160 triggered_spell_id = 12485;
6161 break;
6163 case 989: // Improved Blizzard (Rank 3)
6165 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6166 return false;
6167 triggered_spell_id = 12486;
6168 break;
6170 case 4086: // Improved Mend Pet (Rank 1)
6171 case 4087: // Improved Mend Pet (Rank 2)
6173 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6174 if(!roll_chance_i(chance))
6175 return false;
6177 triggered_spell_id = 24406;
6178 break;
6180 case 4533: // Dreamwalker Raiment 2 pieces bonus
6182 // Chance 50%
6183 if (!roll_chance_i(50))
6184 return false;
6186 switch (pVictim->getPowerType())
6188 case POWER_MANA: triggered_spell_id = 28722; break;
6189 case POWER_RAGE: triggered_spell_id = 28723; break;
6190 case POWER_ENERGY: triggered_spell_id = 28724; break;
6191 default:
6192 return false;
6194 break;
6196 case 4537: // Dreamwalker Raiment 6 pieces bonus
6197 triggered_spell_id = 28750; // Blessing of the Claw
6198 break;
6199 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6200 triggered_spell_id = 37445; // Mana Surge
6201 break;
6204 // not processed
6205 if(!triggered_spell_id)
6206 return false;
6208 // standard non-dummy case
6209 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6211 if(!triggerEntry)
6213 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6214 return false;
6217 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6218 return false;
6220 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6222 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6223 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6225 return true;
6228 void Unit::setPowerType(Powers new_powertype)
6230 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6232 if(GetTypeId() == TYPEID_PLAYER)
6234 if(((Player*)this)->GetGroup())
6235 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6237 else if(((Creature*)this)->isPet())
6239 Pet *pet = ((Pet*)this);
6240 if(pet->isControlled())
6242 Unit *owner = GetOwner();
6243 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6244 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6248 switch(new_powertype)
6250 default:
6251 case POWER_MANA:
6252 break;
6253 case POWER_RAGE:
6254 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6255 SetPower( POWER_RAGE,0);
6256 break;
6257 case POWER_FOCUS:
6258 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6259 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6260 break;
6261 case POWER_ENERGY:
6262 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6263 SetPower( POWER_ENERGY,0);
6264 break;
6265 case POWER_HAPPINESS:
6266 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6267 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6268 break;
6272 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6274 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6275 if(!entry)
6277 static uint64 guid = 0; // prevent repeating spam same faction problem
6279 if(GetGUID() != guid)
6281 if(GetTypeId() == TYPEID_PLAYER)
6282 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6283 else
6284 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6285 guid = GetGUID();
6288 return entry;
6291 bool Unit::IsHostileTo(Unit const* unit) const
6293 // always non-hostile to self
6294 if(unit==this)
6295 return false;
6297 // always non-hostile to GM in GM mode
6298 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6299 return false;
6301 // always hostile to enemy
6302 if(getVictim()==unit || unit->getVictim()==this)
6303 return true;
6305 // test pet/charm masters instead pers/charmeds
6306 Unit const* testerOwner = GetCharmerOrOwner();
6307 Unit const* targetOwner = unit->GetCharmerOrOwner();
6309 // always hostile to owner's enemy
6310 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6311 return true;
6313 // always hostile to enemy owner
6314 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6315 return true;
6317 // always hostile to owner of owner's enemy
6318 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6319 return true;
6321 Unit const* tester = testerOwner ? testerOwner : this;
6322 Unit const* target = targetOwner ? targetOwner : unit;
6324 // always non-hostile to target with common owner, or to owner/pet
6325 if(tester==target)
6326 return false;
6328 // special cases (Duel, etc)
6329 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6331 Player const* pTester = (Player const*)tester;
6332 Player const* pTarget = (Player const*)target;
6334 // Duel
6335 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6336 return true;
6338 // Group
6339 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6340 return false;
6342 // Sanctuary
6343 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6344 return false;
6346 // PvP FFA state
6347 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))
6348 return true;
6350 //= PvP states
6351 // Green/Blue (can't attack)
6352 if(pTester->GetTeam()==pTarget->GetTeam())
6353 return false;
6355 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6356 return pTester->IsPvP() && pTarget->IsPvP();
6359 // faction base cases
6360 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6361 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6362 if(!tester_faction || !target_faction)
6363 return false;
6365 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6366 return true;
6368 // PvC forced reaction and reputation case
6369 if(tester->GetTypeId()==TYPEID_PLAYER)
6371 // forced reaction
6372 ForcedReactions::const_iterator forceItr = ((Player*)tester)->m_forcedReactions.find(target_faction->faction);
6373 if(forceItr!=((Player*)tester)->m_forcedReactions.end())
6374 return forceItr->second <= REP_HOSTILE;
6376 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6377 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6378 if(raw_target_faction->reputationListID >=0)
6379 if(FactionState const* factionState = ((Player*)tester)->GetFactionState(raw_target_faction))
6380 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6382 // CvP forced reaction and reputation case
6383 else if(target->GetTypeId()==TYPEID_PLAYER)
6385 // forced reaction
6386 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
6387 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
6388 return forceItr->second <= REP_HOSTILE;
6390 // apply reputation state
6391 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6392 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6393 return ((Player const*)target)->GetReputationRank(raw_tester_faction) <= REP_HOSTILE;
6396 // common faction based case (CvC,PvC,CvP)
6397 return tester_faction->IsHostileTo(*target_faction);
6400 bool Unit::IsFriendlyTo(Unit const* unit) const
6402 // always friendly to self
6403 if(unit==this)
6404 return true;
6406 // always friendly to GM in GM mode
6407 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6408 return true;
6410 // always non-friendly to enemy
6411 if(getVictim()==unit || unit->getVictim()==this)
6412 return false;
6414 // test pet/charm masters instead pers/charmeds
6415 Unit const* testerOwner = GetCharmerOrOwner();
6416 Unit const* targetOwner = unit->GetCharmerOrOwner();
6418 // always non-friendly to owner's enemy
6419 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6420 return false;
6422 // always non-friendly to enemy owner
6423 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6424 return false;
6426 // always non-friendly to owner of owner's enemy
6427 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6428 return false;
6430 Unit const* tester = testerOwner ? testerOwner : this;
6431 Unit const* target = targetOwner ? targetOwner : unit;
6433 // always friendly to target with common owner, or to owner/pet
6434 if(tester==target)
6435 return true;
6437 // special cases (Duel)
6438 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6440 Player const* pTester = (Player const*)tester;
6441 Player const* pTarget = (Player const*)target;
6443 // Duel
6444 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
6445 return false;
6447 // Group
6448 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6449 return true;
6451 // Sanctuary
6452 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6453 return true;
6455 // PvP FFA state
6456 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))
6457 return false;
6459 //= PvP states
6460 // Green/Blue (non-attackable)
6461 if(pTester->GetTeam()==pTarget->GetTeam())
6462 return true;
6464 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
6465 return !pTarget->IsPvP();
6468 // faction base cases
6469 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6470 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6471 if(!tester_faction || !target_faction)
6472 return false;
6474 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6475 return false;
6477 // PvC forced reaction and reputation case
6478 if(tester->GetTypeId()==TYPEID_PLAYER)
6480 // forced reaction
6481 ForcedReactions::const_iterator forceItr = ((Player const*)tester)->m_forcedReactions.find(target_faction->faction);
6482 if(forceItr!=((Player const*)tester)->m_forcedReactions.end())
6483 return forceItr->second >= REP_FRIENDLY;
6485 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
6486 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6487 if(raw_target_faction->reputationListID >=0)
6488 if(FactionState const* FactionState = ((Player*)tester)->GetFactionState(raw_target_faction))
6489 return !(FactionState->Flags & FACTION_FLAG_AT_WAR);
6491 // CvP forced reaction and reputation case
6492 else if(target->GetTypeId()==TYPEID_PLAYER)
6494 // forced reaction
6495 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
6496 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
6497 return forceItr->second >= REP_FRIENDLY;
6499 // apply reputation state
6500 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
6501 if(raw_tester_faction->reputationListID >=0 )
6502 return ((Player const*)target)->GetReputationRank(raw_tester_faction) >= REP_FRIENDLY;
6505 // common faction based case (CvC,PvC,CvP)
6506 return tester_faction->IsFriendlyTo(*target_faction);
6509 bool Unit::IsHostileToPlayers() const
6511 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
6512 if(!my_faction)
6513 return false;
6515 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
6516 if(raw_faction && raw_faction->reputationListID >=0 )
6517 return false;
6519 return my_faction->IsHostileToPlayers();
6522 bool Unit::IsNeutralToAll() const
6524 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
6525 if(!my_faction)
6526 return true;
6528 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
6529 if(raw_faction && raw_faction->reputationListID >=0 )
6530 return false;
6532 return my_faction->IsNeutralToAll();
6535 bool Unit::Attack(Unit *victim, bool meleeAttack)
6537 if(!victim || victim == this)
6538 return false;
6540 // dead units can neither attack nor be attacked
6541 if(!isAlive() || !victim->isAlive())
6542 return false;
6544 // player cannot attack in mount state
6545 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
6546 return false;
6548 // nobody can attack GM in GM-mode
6549 if(victim->GetTypeId()==TYPEID_PLAYER)
6551 if(((Player*)victim)->isGameMaster())
6552 return false;
6554 else
6556 if(((Creature*)victim)->IsInEvadeMode())
6557 return false;
6560 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
6561 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
6562 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
6564 if (m_attacking)
6566 if (m_attacking == victim)
6568 // switch to melee attack from ranged/magic
6569 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
6571 addUnitState(UNIT_STAT_MELEE_ATTACKING);
6572 SendAttackStart(victim);
6573 return true;
6575 return false;
6577 AttackStop();
6580 //Set our target
6581 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
6583 if(meleeAttack)
6584 addUnitState(UNIT_STAT_MELEE_ATTACKING);
6585 m_attacking = victim;
6586 m_attacking->_addAttacker(this);
6588 if(m_attacking->GetTypeId()==TYPEID_UNIT && ((Creature*)m_attacking)->AI())
6589 ((Creature*)m_attacking)->AI()->AttackedBy(this);
6591 if(GetTypeId()==TYPEID_UNIT)
6593 WorldPacket data(SMSG_AI_REACTION, 12);
6594 data << uint64(GetGUID());
6595 data << uint32(AI_REACTION_AGGRO); // Aggro sound
6596 ((WorldObject*)this)->SendMessageToSet(&data, true);
6598 ((Creature*)this)->CallAssistance();
6599 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
6602 // delay offhand weapon attack to next attack time
6603 if(haveOffhandWeapon())
6604 resetAttackTimer(OFF_ATTACK);
6606 if(meleeAttack)
6607 SendAttackStart(victim);
6609 return true;
6612 bool Unit::AttackStop()
6614 if (!m_attacking)
6615 return false;
6617 Unit* victim = m_attacking;
6619 m_attacking->_removeAttacker(this);
6620 m_attacking = NULL;
6622 //Clear our target
6623 SetUInt64Value(UNIT_FIELD_TARGET, 0);
6625 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
6627 InterruptSpell(CURRENT_MELEE_SPELL);
6629 if( GetTypeId()==TYPEID_UNIT )
6631 // reset call assistance
6632 ((Creature*)this)->SetNoCallAssistance(false);
6635 SendAttackStop(victim);
6637 return true;
6640 void Unit::CombatStop(bool cast)
6642 if(cast& IsNonMeleeSpellCasted(false))
6643 InterruptNonMeleeSpells(false);
6645 AttackStop();
6646 RemoveAllAttackers();
6647 if( GetTypeId()==TYPEID_PLAYER )
6648 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
6649 ClearInCombat();
6652 void Unit::CombatStopWithPets(bool cast)
6654 CombatStop(cast);
6655 if(Pet* pet = GetPet())
6656 pet->CombatStop(cast);
6657 if(Unit* charm = GetCharm())
6658 charm->CombatStop(cast);
6659 if(GetTypeId()==TYPEID_PLAYER)
6661 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
6662 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
6663 if(Unit* guardian = Unit::GetUnit(*this,*itr))
6664 guardian->CombatStop(cast);
6668 bool Unit::isAttackingPlayer() const
6670 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
6671 return true;
6673 Pet* pet = GetPet();
6674 if(pet && pet->isAttackingPlayer())
6675 return true;
6677 Unit* charmed = GetCharm();
6678 if(charmed && charmed->isAttackingPlayer())
6679 return true;
6681 for (int8 i = 0; i < MAX_TOTEM; i++)
6683 if(m_TotemSlot[i])
6685 Creature *totem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
6686 if(totem && totem->isAttackingPlayer())
6687 return true;
6691 return false;
6694 void Unit::RemoveAllAttackers()
6696 while (!m_attackers.empty())
6698 AttackerSet::iterator iter = m_attackers.begin();
6699 if(!(*iter)->AttackStop())
6701 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
6702 m_attackers.erase(iter);
6707 void Unit::ModifyAuraState(AuraState flag, bool apply)
6709 if (apply)
6711 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
6713 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
6714 if(GetTypeId() == TYPEID_PLAYER)
6716 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
6717 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
6719 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
6720 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
6721 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
6722 if (spellInfo->CasterAuraState == flag)
6723 CastSpell(this, itr->first, true, NULL);
6728 else
6730 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
6732 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
6733 Unit::AuraMap& tAuras = GetAuras();
6734 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
6736 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
6737 if (spellProto->CasterAuraState == flag)
6739 // exceptions (applied at state but not removed at state change)
6740 // Rampage
6741 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
6743 ++itr;
6744 continue;
6747 RemoveAura(itr);
6749 else
6750 ++itr;
6756 Unit *Unit::GetOwner() const
6758 uint64 ownerid = GetOwnerGUID();
6759 if(!ownerid)
6760 return NULL;
6761 return ObjectAccessor::GetUnit(*this, ownerid);
6764 Unit *Unit::GetCharmer() const
6766 if(uint64 charmerid = GetCharmerGUID())
6767 return ObjectAccessor::GetUnit(*this, charmerid);
6768 return NULL;
6771 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
6773 uint64 guid = GetCharmerOrOwnerGUID();
6774 if(IS_PLAYER_GUID(guid))
6775 return ObjectAccessor::GetPlayer(*this, guid);
6777 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
6780 Pet* Unit::GetPet() const
6782 if(uint64 pet_guid = GetPetGUID())
6784 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
6785 return pet;
6787 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
6788 const_cast<Unit*>(this)->SetPet(0);
6791 return NULL;
6794 Unit* Unit::GetCharm() const
6796 if(uint64 charm_guid = GetCharmGUID())
6798 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
6799 return pet;
6801 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
6802 const_cast<Unit*>(this)->SetCharm(0);
6805 return NULL;
6808 void Unit::SetPet(Pet* pet)
6810 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
6812 // FIXME: hack, speed must be set only at follow
6813 if(pet)
6814 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
6815 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
6818 void Unit::SetCharm(Unit* pet)
6820 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
6822 if(GetTypeId() == TYPEID_PLAYER)
6823 ((Player*)this)->m_mover = pet ? pet : this;
6826 void Unit::UnsummonAllTotems()
6828 for (int8 i = 0; i < MAX_TOTEM; ++i)
6830 if(!m_TotemSlot[i])
6831 continue;
6833 Creature *OldTotem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
6834 if (OldTotem && OldTotem->isTotem())
6835 ((Totem*)OldTotem)->UnSummon();
6839 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
6841 // we guess size
6842 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
6843 data.append(pVictim->GetPackGUID());
6844 data.append(GetPackGUID());
6845 data << uint32(SpellID);
6846 data << uint32(Damage);
6847 data << uint32(0); // over healing?
6848 data << uint8(critical ? 1 : 0);
6849 data << uint8(0); // unused in client?
6850 SendMessageToSet(&data, true);
6853 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
6855 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
6856 data.append(pVictim->GetPackGUID());
6857 data.append(GetPackGUID());
6858 data << uint32(SpellID);
6859 data << uint32(powertype);
6860 data << uint32(Damage);
6861 SendMessageToSet(&data, true);
6864 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype)
6866 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
6867 return pdamage;
6869 int32 BonusDamage = 0;
6870 if( GetTypeId()==TYPEID_UNIT )
6872 // Pets just add their bonus damage to their spell damage
6873 // note that their spell damage is just gain of their own auras
6874 if (((Creature*)this)->isPet())
6876 BonusDamage = ((Pet*)this)->GetBonusDamage();
6878 // For totems get damage bonus from owner (statue isn't totem in fact)
6879 else if (((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
6881 if(Unit* owner = GetOwner())
6882 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
6886 // Damage Done
6887 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
6889 // Taken/Done fixed damage bonus auras
6890 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto))+BonusDamage;
6891 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
6893 // Damage over Time spells bonus calculation
6894 float DotFactor = 1.0f;
6895 if(damagetype == DOT)
6897 int32 DotDuration = GetSpellDuration(spellProto);
6898 // 200% limit
6899 if(DotDuration > 0)
6901 if(DotDuration > 30000) DotDuration = 30000;
6902 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
6903 int x = 0;
6904 for(int j = 0; j < 3; j++)
6906 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
6907 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
6908 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
6910 x = j;
6911 break;
6914 int DotTicks = 6;
6915 if(spellProto->EffectAmplitude[x] != 0)
6916 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
6917 if(DotTicks)
6919 DoneAdvertisedBenefit /= DotTicks;
6920 TakenAdvertisedBenefit /= DotTicks;
6925 // Taken/Done total percent damage auras
6926 float DoneTotalMod = 1.0f;
6927 float TakenTotalMod = 1.0f;
6929 // ..done
6930 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6931 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
6933 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
6934 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
6935 // -1 == any item class (not wand then)
6936 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
6937 // 0 == any inventory type (not wand then)
6939 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
6943 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
6944 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
6945 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
6946 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
6947 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
6949 // ..taken
6950 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
6951 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
6952 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
6953 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
6955 // .. taken pct: scripted (increases damage of * against targets *)
6956 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6957 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6959 switch((*i)->GetModifier()->m_miscvalue)
6961 //Molten Fury
6962 case 4920: case 4919:
6963 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
6964 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f; break;
6968 // .. taken pct: dummy auras
6969 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
6970 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
6972 switch((*i)->GetSpellProto()->SpellIconID)
6974 //Cheat Death
6975 case 2109:
6976 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) )
6978 if(pVictim->GetTypeId() != TYPEID_PLAYER)
6979 continue;
6980 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
6981 if (mod < (*i)->GetModifier()->m_amount)
6982 mod = (*i)->GetModifier()->m_amount;
6983 TakenTotalMod *= (mod+100.0f)/100.0f;
6985 break;
6986 //Mangle
6987 case 2312:
6988 for(int j=0;j<3;j++)
6990 if(GetEffectMechanic(spellProto, j)==MECHANIC_BLEED)
6992 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
6993 break;
6996 break;
7000 // Distribute Damage over multiple effects, reduce by AoE
7001 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7003 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7004 for(int j = 0; j < 3; ++j)
7006 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7007 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7009 CastingTime /= 2;
7010 break;
7014 switch(spellProto->SpellFamilyName)
7016 case SPELLFAMILY_MAGE:
7017 // Ignite - do not modify, it is (8*Rank)% damage of procing Spell
7018 if(spellProto->Id==12654)
7020 return pdamage;
7022 // Ice Lance
7023 else if((spellProto->SpellFamilyFlags & 0x20000LL) && spellProto->SpellIconID == 186)
7025 CastingTime /= 3; // applied 1/3 bonuses in case generic target
7026 if(pVictim->isFrozen()) // and compensate this for frozen target.
7027 TakenTotalMod *= 3.0f;
7029 // Pyroblast - 115% of Fire Damage, DoT - 20% of Fire Damage
7030 else if((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 184 )
7032 DotFactor = damagetype == DOT ? 0.2f : 1.0f;
7033 CastingTime = damagetype == DOT ? 3500 : 4025;
7035 // Fireball - 100% of Fire Damage, DoT - 0% of Fire Damage
7036 else if((spellProto->SpellFamilyFlags & 0x1LL) && spellProto->SpellIconID == 185)
7038 CastingTime = 3500;
7039 DotFactor = damagetype == DOT ? 0.0f : 1.0f;
7041 // Molten armor
7042 else if (spellProto->SpellFamilyFlags & 0x0000000800000000LL)
7044 CastingTime = 0;
7046 // Arcane Missiles triggered spell
7047 else if ((spellProto->SpellFamilyFlags & 0x200000LL) && spellProto->SpellIconID == 225)
7049 CastingTime = 1000;
7051 // Blizzard triggered spell
7052 else if ((spellProto->SpellFamilyFlags & 0x80080LL) && spellProto->SpellIconID == 285)
7054 CastingTime = 500;
7056 break;
7057 case SPELLFAMILY_WARLOCK:
7058 // Life Tap
7059 if((spellProto->SpellFamilyFlags & 0x40000LL) && spellProto->SpellIconID == 208)
7061 CastingTime = 2800; // 80% from +shadow damage
7062 DoneTotalMod = 1.0f;
7063 TakenTotalMod = 1.0f;
7065 // Dark Pact
7066 else if((spellProto->SpellFamilyFlags & 0x80000000LL) && spellProto->SpellIconID == 154 && GetPetGUID())
7068 CastingTime = 3360; // 96% from +shadow damage
7069 DoneTotalMod = 1.0f;
7070 TakenTotalMod = 1.0f;
7072 // Soul Fire - 115% of Fire Damage
7073 else if((spellProto->SpellFamilyFlags & 0x8000000000LL) && spellProto->SpellIconID == 184)
7075 CastingTime = 4025;
7077 // Curse of Agony - 120% of Shadow Damage
7078 else if((spellProto->SpellFamilyFlags & 0x0000000400LL) && spellProto->SpellIconID == 544)
7080 DotFactor = 1.2f;
7082 // Drain Mana - 0% of Shadow Damage
7083 else if((spellProto->SpellFamilyFlags & 0x10LL) && spellProto->SpellIconID == 548)
7085 CastingTime = 0;
7087 // Drain Soul 214.3%
7088 else if ((spellProto->SpellFamilyFlags & 0x4000LL) && spellProto->SpellIconID == 113 )
7090 CastingTime = 7500;
7092 // Hellfire
7093 else if ((spellProto->SpellFamilyFlags & 0x40LL) && spellProto->SpellIconID == 937)
7095 CastingTime = damagetype == DOT ? 5000 : 500; // self damage seems to be so
7097 // Unstable Affliction - 180%
7098 else if (spellProto->Id == 31117 && spellProto->SpellIconID == 232)
7100 CastingTime = 6300;
7102 // Corruption 93%
7103 else if ((spellProto->SpellFamilyFlags & 0x2LL) && spellProto->SpellIconID == 313)
7105 DotFactor = 0.93f;
7107 break;
7108 case SPELLFAMILY_PALADIN:
7109 // Consecration - 95% of Holy Damage
7110 if((spellProto->SpellFamilyFlags & 0x20LL) && spellProto->SpellIconID == 51)
7112 DotFactor = 0.95f;
7113 CastingTime = 3500;
7115 // Seal of Righteousness - 10.2%/9.8% ( based on weapon type ) of Holy Damage, multiplied by weapon speed
7116 else if((spellProto->SpellFamilyFlags & 0x8000000LL) && spellProto->SpellIconID == 25)
7118 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
7119 float wspeed = GetAttackTime(BASE_ATTACK)/1000.0f;
7121 if( item && item->GetProto()->InventoryType == INVTYPE_2HWEAPON)
7122 CastingTime = uint32(wspeed*3500*0.102f);
7123 else
7124 CastingTime = uint32(wspeed*3500*0.098f);
7126 // Judgement of Righteousness - 73%
7127 else if ((spellProto->SpellFamilyFlags & 1024) && spellProto->SpellIconID == 25)
7129 CastingTime = 2555;
7131 // Seal of Vengeance - 17% per Fully Stacked Tick - 5 Applications
7132 else if ((spellProto->SpellFamilyFlags & 0x80000000000LL) && spellProto->SpellIconID == 2292)
7134 DotFactor = 0.17f;
7135 CastingTime = 3500;
7137 // Holy shield - 5% of Holy Damage
7138 else if ((spellProto->SpellFamilyFlags & 0x4000000000LL) && spellProto->SpellIconID == 453)
7140 CastingTime = 175;
7142 // Blessing of Sanctuary - 0%
7143 else if ((spellProto->SpellFamilyFlags & 0x10000000LL) && spellProto->SpellIconID == 29)
7145 CastingTime = 0;
7147 // Seal of Righteousness trigger - already computed for parent spell
7148 else if ( spellProto->SpellFamilyName==SPELLFAMILY_PALADIN && spellProto->SpellIconID==25 && spellProto->AttributesEx4 & 0x00800000LL )
7150 return pdamage;
7152 break;
7153 case SPELLFAMILY_SHAMAN:
7154 // totem attack
7155 if (spellProto->SpellFamilyFlags & 0x000040000000LL)
7157 if (spellProto->SpellIconID == 33) // Fire Nova totem attack must be 21.4%(untested)
7158 CastingTime = 749; // ignore CastingTime and use as modifier
7159 else if (spellProto->SpellIconID == 680) // Searing Totem attack 8%
7160 CastingTime = 280; // ignore CastingTime and use as modifier
7161 else if (spellProto->SpellIconID == 37) // Magma totem attack must be 6.67%(untested)
7162 CastingTime = 234; // ignore CastingTimePenalty and use as modifier
7164 // Lightning Shield (and proc shield from T2 8 pieces bonus ) 33% per charge
7165 else if( (spellProto->SpellFamilyFlags & 0x00000000400LL) || spellProto->Id == 23552)
7166 CastingTime = 1155; // ignore CastingTimePenalty and use as modifier
7167 break;
7168 case SPELLFAMILY_PRIEST:
7169 // Mana Burn - 0% of Shadow Damage
7170 if((spellProto->SpellFamilyFlags & 0x10LL) && spellProto->SpellIconID == 212)
7172 CastingTime = 0;
7174 // Mind Flay - 59% of Shadow Damage
7175 else if((spellProto->SpellFamilyFlags & 0x800000LL) && spellProto->SpellIconID == 548)
7177 CastingTime = 2065;
7179 // Holy Fire - 86.71%, DoT - 16.5%
7180 else if ((spellProto->SpellFamilyFlags & 0x100000LL) && spellProto->SpellIconID == 156)
7182 DotFactor = damagetype == DOT ? 0.165f : 1.0f;
7183 CastingTime = damagetype == DOT ? 3500 : 3035;
7185 // Shadowguard - 28% per charge
7186 else if ((spellProto->SpellFamilyFlags & 0x2000000LL) && spellProto->SpellIconID == 19)
7188 CastingTime = 980;
7190 // Touch of Weakeness - 10%
7191 else if ((spellProto->SpellFamilyFlags & 0x80000LL) && spellProto->SpellIconID == 1591)
7193 CastingTime = 350;
7195 // Reflective Shield (back damage) - 0% (other spells fit to check not have damage effects/auras)
7196 else if (spellProto->SpellFamilyFlags == 0 && spellProto->SpellIconID == 566)
7198 CastingTime = 0;
7200 // Holy Nova - 14%
7201 else if ((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 1874)
7203 CastingTime = 500;
7205 break;
7206 case SPELLFAMILY_DRUID:
7207 // Hurricane triggered spell
7208 if((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 220)
7210 CastingTime = 500;
7212 break;
7213 case SPELLFAMILY_WARRIOR:
7214 case SPELLFAMILY_HUNTER:
7215 case SPELLFAMILY_ROGUE:
7216 CastingTime = 0;
7217 break;
7218 default:
7219 break;
7222 float LvlPenalty = CalculateLevelPenalty(spellProto);
7224 // Spellmod SpellDamage
7225 float SpellModSpellDamage = 100.0f;
7227 if(Player* modOwner = GetSpellModOwner())
7228 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7230 SpellModSpellDamage /= 100.0f;
7232 float DoneActualBenefit = DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * SpellModSpellDamage * LvlPenalty;
7233 float TakenActualBenefit = TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
7235 float tmpDamage = (float(pdamage)+DoneActualBenefit)*DoneTotalMod;
7237 // Add flat bonus from spell damage versus
7238 tmpDamage += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7240 // apply spellmod to Done damage
7241 if(Player* modOwner = GetSpellModOwner())
7242 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7244 tmpDamage = (tmpDamage+TakenActualBenefit)*TakenTotalMod;
7246 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7247 tmpDamage *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7249 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7252 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7254 int32 DoneAdvertisedBenefit = 0;
7256 // ..done
7257 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7258 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7259 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7260 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7261 // -1 == any item class (not wand then)
7262 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7263 // 0 == any inventory type (not wand then)
7264 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7266 if (GetTypeId() == TYPEID_PLAYER)
7268 // Damage bonus from stats
7269 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7270 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7272 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7274 // stat used stored in miscValueB for this aura
7275 Stats usedStat = Stats((*i)->GetMiscBValue());
7276 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7279 // ... and attack power
7280 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7281 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7282 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7283 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7286 return DoneAdvertisedBenefit;
7289 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7291 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7293 int32 TakenAdvertisedBenefit = 0;
7294 // ..done (for creature type by mask) in taken
7295 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7296 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7297 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7298 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7300 // ..taken
7301 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7302 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7303 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7304 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7306 return TakenAdvertisedBenefit;
7309 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7311 // not critting spell
7312 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7313 return false;
7315 float crit_chance = 0.0f;
7316 switch(spellProto->DmgClass)
7318 case SPELL_DAMAGE_CLASS_NONE:
7319 return false;
7320 case SPELL_DAMAGE_CLASS_MAGIC:
7322 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7323 crit_chance = 0.0f;
7324 // For other schools
7325 else if (GetTypeId() == TYPEID_PLAYER)
7326 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7327 else
7329 crit_chance = m_baseSpellCritChance;
7330 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7332 // taken
7333 if (pVictim && !IsPositiveSpell(spellProto->Id))
7335 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7336 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7337 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7338 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7339 // Modify by player victim resilience
7340 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7341 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7342 // scripted (increase crit chance ... against ... target by x%
7343 if(pVictim->isFrozen()) // Shatter
7345 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7346 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7348 switch((*i)->GetModifier()->m_miscvalue)
7350 case 849: crit_chance+= 17.0f; break; //Shatter Rank 1
7351 case 910: crit_chance+= 34.0f; break; //Shatter Rank 2
7352 case 911: crit_chance+= 50.0f; break; //Shatter Rank 3
7356 // Glyph of Shadowburn
7357 if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK &&
7358 spellProto->SpellFamilyFlags & 0x0000000000000080 &&
7359 pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7361 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7362 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7363 if((*i)->GetModifier()->m_miscvalue == 7917)
7364 crit_chance+=(*i)->GetModifier()->m_amount;
7367 break;
7369 case SPELL_DAMAGE_CLASS_MELEE:
7370 case SPELL_DAMAGE_CLASS_RANGED:
7372 if (pVictim)
7374 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7375 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7377 break;
7379 default:
7380 return false;
7382 // percent done
7383 // only players use intelligence for critical chance computations
7384 if(Player* modOwner = GetSpellModOwner())
7385 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7387 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7388 if (roll_chance_f(crit_chance))
7389 return true;
7390 return false;
7393 uint32 Unit::SpellCriticalBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7395 // Calculate critical bonus
7396 int32 crit_bonus;
7397 switch(spellProto->DmgClass)
7399 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7400 case SPELL_DAMAGE_CLASS_RANGED:
7401 // TODO: write here full calculation for melee/ranged spells
7402 crit_bonus = damage;
7403 break;
7404 default:
7405 crit_bonus = damage / 2; // for spells is 50%
7406 break;
7409 // adds additional damage to crit_bonus (from talents)
7410 if(Player* modOwner = GetSpellModOwner())
7411 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
7413 if(pVictim)
7415 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7416 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7419 if(crit_bonus > 0)
7420 damage += crit_bonus;
7422 return damage;
7425 uint32 Unit::SpellHealingBonus(SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, Unit *pVictim)
7427 // For totems get healing bonus from owner (statue isn't totem in fact)
7428 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7429 if(Unit* owner = GetOwner())
7430 return owner->SpellHealingBonus(spellProto, healamount, damagetype, pVictim);
7432 // Healing Done
7434 // These Spells are doing fixed amount of healing (TODO found less hack-like check)
7435 if (spellProto->Id == 15290 || spellProto->Id == 39373 ||
7436 spellProto->Id == 33778 || spellProto->Id == 379 ||
7437 spellProto->Id == 38395 || spellProto->Id == 40972)
7438 return healamount;
7440 int32 AdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
7441 uint32 CastingTime = GetSpellCastTime(spellProto);
7443 // Healing Taken
7444 AdvertisedBenefit += SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7446 // Blessing of Light dummy effects healing taken from Holy Light and Flash of Light
7447 if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && (spellProto->SpellFamilyFlags & 0x00000000C0000000LL))
7449 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7450 for(AuraList::const_iterator i = mDummyAuras.begin();i != mDummyAuras.end(); ++i)
7452 if((*i)->GetSpellProto()->SpellVisual[0] == 9180)
7454 // Flash of Light
7455 if ((spellProto->SpellFamilyFlags & 0x0000000040000000LL) && (*i)->GetEffIndex() == 1)
7456 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7457 // Holy Light
7458 else if ((spellProto->SpellFamilyFlags & 0x0000000080000000LL) && (*i)->GetEffIndex() == 0)
7459 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7464 float ActualBenefit = 0.0f;
7466 if (AdvertisedBenefit != 0)
7468 // Healing over Time spells
7469 float DotFactor = 1.0f;
7470 if(damagetype == DOT)
7472 int32 DotDuration = GetSpellDuration(spellProto);
7473 if(DotDuration > 0)
7475 // 200% limit
7476 if(DotDuration > 30000) DotDuration = 30000;
7477 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7478 int x = 0;
7479 for(int j = 0; j < 3; j++)
7481 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7482 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_HEAL ||
7483 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7485 x = j;
7486 break;
7489 int DotTicks = 6;
7490 if(spellProto->EffectAmplitude[x] != 0)
7491 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7492 if(DotTicks)
7493 AdvertisedBenefit /= DotTicks;
7497 // distribute healing to all effects, reduce AoE damage
7498 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7500 // 0% bonus for damage and healing spells for leech spells from healing bonus
7501 for(int j = 0; j < 3; ++j)
7503 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7504 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7506 CastingTime = 0;
7507 break;
7511 // Exception
7512 switch (spellProto->SpellFamilyName)
7514 case SPELLFAMILY_SHAMAN:
7515 // Healing stream from totem (add 6% per tick from hill bonus owner)
7516 if (spellProto->SpellFamilyFlags & 0x000000002000LL)
7517 CastingTime = 210;
7518 // Earth Shield 30% per charge
7519 else if (spellProto->SpellFamilyFlags & 0x40000000000LL)
7520 CastingTime = 1050;
7521 break;
7522 case SPELLFAMILY_DRUID:
7523 // Lifebloom
7524 if (spellProto->SpellFamilyFlags & 0x1000000000LL)
7526 CastingTime = damagetype == DOT ? 3500 : 1200;
7527 DotFactor = damagetype == DOT ? 0.519f : 1.0f;
7529 // Tranquility triggered spell
7530 else if (spellProto->SpellFamilyFlags & 0x80LL)
7531 CastingTime = 667;
7532 // Rejuvenation
7533 else if (spellProto->SpellFamilyFlags & 0x10LL)
7534 DotFactor = 0.845f;
7535 // Regrowth
7536 else if (spellProto->SpellFamilyFlags & 0x40LL)
7538 DotFactor = damagetype == DOT ? 0.705f : 1.0f;
7539 CastingTime = damagetype == DOT ? 3500 : 1010;
7541 break;
7542 case SPELLFAMILY_PRIEST:
7543 // Holy Nova - 14%
7544 if ((spellProto->SpellFamilyFlags & 0x8000000LL) && spellProto->SpellIconID == 1874)
7545 CastingTime = 500;
7546 break;
7547 case SPELLFAMILY_PALADIN:
7548 // Seal and Judgement of Light
7549 if ( spellProto->SpellFamilyFlags & 0x100040000LL )
7550 CastingTime = 0;
7551 break;
7552 case SPELLFAMILY_WARRIOR:
7553 case SPELLFAMILY_ROGUE:
7554 case SPELLFAMILY_HUNTER:
7555 CastingTime = 0;
7556 break;
7559 float LvlPenalty = CalculateLevelPenalty(spellProto);
7561 // Spellmod SpellDamage
7562 float SpellModSpellDamage = 100.0f;
7564 if(Player* modOwner = GetSpellModOwner())
7565 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7567 SpellModSpellDamage /= 100.0f;
7569 ActualBenefit = (float)AdvertisedBenefit * ((float)CastingTime / 3500.0f) * DotFactor * SpellModSpellDamage * LvlPenalty;
7572 // use float as more appropriate for negative values and percent applying
7573 float heal = healamount + ActualBenefit;
7575 // TODO: check for ALL/SPELLS type
7576 // Healing done percent
7577 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
7578 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
7579 heal *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
7581 // apply spellmod to Done amount
7582 if(Player* modOwner = GetSpellModOwner())
7583 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
7585 // Healing Wave cast
7586 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
7588 // Search for Healing Way on Victim (stack up to 3 time)
7589 int32 pctMod = 0;
7590 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7591 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
7592 if((*itr)->GetId() == 29203)
7593 pctMod += (*itr)->GetModifier()->m_amount;
7594 // Apply bonus
7595 if (pctMod)
7596 heal = heal * (100 + pctMod) / 100;
7599 // Healing taken percent
7600 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
7601 if(minval)
7602 heal *= (100.0f + minval) / 100.0f;
7604 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
7605 if(maxval)
7606 heal *= (100.0f + maxval) / 100.0f;
7608 if (heal < 0) heal = 0;
7610 return uint32(heal);
7613 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
7615 int32 AdvertisedBenefit = 0;
7617 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
7618 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
7619 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7620 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7622 // Healing bonus of spirit, intellect and strength
7623 if (GetTypeId() == TYPEID_PLAYER)
7625 // Healing bonus from stats
7626 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
7627 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
7629 // stat used dependent from misc value (stat index)
7630 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
7631 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7634 // ... and attack power
7635 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
7636 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
7637 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7638 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7640 return AdvertisedBenefit;
7643 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7645 int32 AdvertisedBenefit = 0;
7646 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
7647 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7648 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7649 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7650 return AdvertisedBenefit;
7653 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
7655 //If m_immuneToSchool type contain this school type, IMMUNE damage.
7656 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
7657 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
7658 if(itr->type & shoolMask)
7659 return true;
7661 //If m_immuneToDamage type contain magic, IMMUNE damage.
7662 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
7663 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
7664 if(itr->type & shoolMask)
7665 return true;
7667 return false;
7670 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
7672 if (!spellInfo)
7673 return false;
7675 //FIX ME this hack: don't get feared if stunned
7676 if (spellInfo->Mechanic == MECHANIC_FEAR )
7678 if ( hasUnitState(UNIT_STAT_STUNNED) )
7679 return true;
7682 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
7683 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
7684 if(itr->type == spellInfo->Dispel)
7685 return true;
7687 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
7688 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
7690 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
7691 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
7692 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
7693 (itr->type & GetSpellSchoolMask(spellInfo)) )
7694 return true;
7697 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
7698 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
7700 if(itr->type == spellInfo->Mechanic)
7702 return true;
7706 return false;
7709 bool Unit::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
7711 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
7712 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
7713 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
7714 if(itr->type == effect)
7715 return true;
7717 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
7718 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
7719 if(itr->type == mechanic)
7720 return true;
7722 return false;
7725 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
7727 if(!spellInfo)
7728 return false;
7730 uint32 family = spellInfo->SpellFamilyName;
7731 uint64 flags = spellInfo->SpellFamilyFlags;
7733 if((family == 5 && flags == 256) || //Searing Pain
7734 (family == 6 && flags == 8192) || //Mind Blast
7735 (family == 11 && flags == 1048576)) //Earth Shock
7736 return true;
7738 return false;
7741 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
7743 if(!pVictim)
7744 return;
7746 if(*pdamage == 0)
7747 return;
7749 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7751 // Taken/Done fixed damage bonus auras
7752 int32 DoneFlatBenefit = 0;
7753 int32 TakenFlatBenefit = 0;
7755 // ..done (for creature type by mask) in taken
7756 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7757 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7758 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7759 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
7761 // ..done
7762 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
7764 // ..done (base at attack power for marked target and base at attack power for creature type)
7765 int32 APbonus = 0;
7766 if(attType == RANGED_ATTACK)
7768 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
7770 // ..done (base at attack power and creature type)
7771 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
7772 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
7773 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7774 APbonus += (*i)->GetModifier()->m_amount;
7776 else
7778 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
7780 // ..done (base at attack power and creature type)
7781 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
7782 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
7783 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7784 APbonus += (*i)->GetModifier()->m_amount;
7787 if (APbonus!=0) // Can be negative
7789 bool normalized = false;
7790 if(spellProto)
7792 for (uint8 i = 0; i<3;i++)
7794 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
7796 normalized = true;
7797 break;
7802 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
7805 // ..taken
7806 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7807 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7808 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
7809 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
7811 if(attType!=RANGED_ATTACK)
7812 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
7813 else
7814 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
7816 // Done/Taken total percent damage auras
7817 float DoneTotalMod = 1;
7818 float TakenTotalMod = 1;
7820 // ..done
7821 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
7822 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
7824 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7825 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7826 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7827 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7829 // ..taken
7830 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7831 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7832 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
7833 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7835 // .. taken pct: dummy auras
7836 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7837 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
7839 switch((*i)->GetSpellProto()->SpellIconID)
7841 //Cheat Death
7842 case 2109:
7843 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
7845 if(pVictim->GetTypeId() != TYPEID_PLAYER)
7846 continue;
7847 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
7848 if (mod < (*i)->GetModifier()->m_amount)
7849 mod = (*i)->GetModifier()->m_amount;
7850 TakenTotalMod *= (mod+100.0f)/100.0f;
7852 break;
7853 //Mangle
7854 case 2312:
7855 if(spellProto==NULL)
7856 break;
7857 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
7858 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
7859 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7860 break;
7864 // .. taken pct: class scripts
7865 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7866 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
7868 switch((*i)->GetMiscValue())
7870 case 6427: case 6428: // Dirty Deeds
7871 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7873 Aura* eff0 = GetAura((*i)->GetId(),0);
7874 if(!eff0 || (*i)->GetEffIndex()!=1)
7876 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
7877 continue;
7880 // effect 0 have expected value but in negative state
7881 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
7883 break;
7887 if(attType != RANGED_ATTACK)
7889 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
7890 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
7891 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7893 else
7895 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
7896 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
7897 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7900 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
7902 // apply spellmod to Done damage
7903 if(spellProto)
7905 if(Player* modOwner = GetSpellModOwner())
7906 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
7909 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
7911 // bonus result can be negative
7912 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
7915 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
7917 if (apply)
7919 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
7921 next = itr; ++next;
7922 if(itr->type == type)
7924 m_spellImmune[op].erase(itr);
7925 next = m_spellImmune[op].begin();
7928 SpellImmune Immune;
7929 Immune.spellId = spellId;
7930 Immune.type = type;
7931 m_spellImmune[op].push_back(Immune);
7933 else
7935 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
7937 if(itr->spellId == spellId)
7939 m_spellImmune[op].erase(itr);
7940 break;
7947 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
7949 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
7951 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
7952 RemoveAurasWithDispelType(type);
7955 float Unit::GetWeaponProcChance() const
7957 // normalized proc chance for weapon attack speed
7958 // (odd formula...)
7959 if(isAttackReady(BASE_ATTACK))
7960 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
7961 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
7962 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
7963 return 0;
7966 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
7968 // proc per minute chance calculation
7969 if (PPM <= 0) return 0.0f;
7970 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
7971 return result;
7974 void Unit::Mount(uint32 mount)
7976 if(!mount)
7977 return;
7979 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
7981 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
7983 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
7985 // unsummon pet
7986 if(GetTypeId() == TYPEID_PLAYER)
7988 Pet* pet = GetPet();
7989 if(pet)
7991 if(pet->isControlled())
7993 ((Player*)this)->SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
7994 ((Player*)this)->SetOldPetSpell(pet->GetUInt32Value(UNIT_CREATED_BY_SPELL));
7997 ((Player*)this)->RemovePet(NULL,PET_SAVE_NOT_IN_SLOT);
7999 else
8000 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8004 void Unit::Unmount()
8006 if(!IsMounted())
8007 return;
8009 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8011 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8012 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8014 // only resummon old pet if the player is already added to a map
8015 // this prevents adding a pet to a not created map which would otherwise cause a crash
8016 // (it could probably happen when logging in after a previous crash)
8017 if(GetTypeId() == TYPEID_PLAYER && IsInWorld() && ((Player*)this)->GetTemporaryUnsummonedPetNumber() && isAlive())
8019 Pet* NewPet = new Pet;
8020 if(!NewPet->LoadPetFromDB((Player*)this, 0, ((Player*)this)->GetTemporaryUnsummonedPetNumber(), true))
8021 delete NewPet;
8023 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8027 void Unit::SetInCombatWith(Unit* enemy)
8029 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8030 if(eOwner->IsPvP())
8032 SetInCombatState(true);
8033 return;
8036 //check for duel
8037 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8039 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8040 if(((Player const*)eOwner)->duel->opponent == myOwner)
8042 SetInCombatState(true);
8043 return;
8046 SetInCombatState(false);
8049 void Unit::SetInCombatState(bool PvP)
8051 // only alive units can be in combat
8052 if(!isAlive())
8053 return;
8055 if(PvP)
8056 m_CombatTimer = 5000;
8057 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8059 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8060 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8063 void Unit::ClearInCombat()
8065 m_CombatTimer = 0;
8066 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8068 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8069 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8071 // Player's state will be cleared in Player::UpdateContestedPvP
8072 if(GetTypeId()!=TYPEID_PLAYER)
8073 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8076 bool Unit::isTargetableForAttack() const
8078 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8079 return false;
8081 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8082 return false;
8084 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8087 int32 Unit::ModifyHealth(int32 dVal)
8089 int32 gain = 0;
8091 if(dVal==0)
8092 return 0;
8094 int32 curHealth = (int32)GetHealth();
8096 int32 val = dVal + curHealth;
8097 if(val <= 0)
8099 SetHealth(0);
8100 return -curHealth;
8103 int32 maxHealth = (int32)GetMaxHealth();
8105 if(val < maxHealth)
8107 SetHealth(val);
8108 gain = val - curHealth;
8110 else if(curHealth != maxHealth)
8112 SetHealth(maxHealth);
8113 gain = maxHealth - curHealth;
8116 return gain;
8119 int32 Unit::ModifyPower(Powers power, int32 dVal)
8121 int32 gain = 0;
8123 if(dVal==0)
8124 return 0;
8126 int32 curPower = (int32)GetPower(power);
8128 int32 val = dVal + curPower;
8129 if(val <= 0)
8131 SetPower(power,0);
8132 return -curPower;
8135 int32 maxPower = (int32)GetMaxPower(power);
8137 if(val < maxPower)
8139 SetPower(power,val);
8140 gain = val - curPower;
8142 else if(curPower != maxPower)
8144 SetPower(power,maxPower);
8145 gain = maxPower - curPower;
8148 return gain;
8151 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8153 if(!u)
8154 return false;
8156 // Always can see self
8157 if (u==this)
8158 return true;
8160 // player visible for other player if not logout and at same transport
8161 // including case when player is out of world
8162 bool at_same_transport =
8163 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8164 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8165 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8166 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8168 // not in world
8169 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8170 return false;
8172 // forbidden to seen (at GM respawn command)
8173 if(m_Visibility==VISIBILITY_RESPAWN)
8174 return false;
8176 // always seen by owner
8177 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8178 return true;
8180 // Grid dead/alive checks
8181 if( u->GetTypeId()==TYPEID_PLAYER)
8183 // non visible at grid for any stealth state
8184 if(!IsVisibleInGridForPlayer((Player *)u))
8185 return false;
8187 // if player is dead then he can't detect anyone in any cases
8188 if(!u->isAlive())
8189 detect = false;
8191 else
8193 // all dead creatures/players not visible for any creatures
8194 if(!u->isAlive() || !isAlive())
8195 return false;
8198 // different visible distance checks
8199 if(u->isInFlight()) // what see player in flight
8201 // use object grey distance for all (only see objects any way)
8202 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8203 return false;
8205 else if(!isAlive()) // distance for show body
8207 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8208 return false;
8210 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8212 if(u->GetTypeId()==TYPEID_PLAYER)
8214 // Players far than max visible distance for player or not in our map are not visible too
8215 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8216 return false;
8218 else
8220 // Units far than max visible distance for creature or not in our map are not visible too
8221 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8222 return false;
8225 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8227 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8228 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8229 return false;
8231 else // distance for show creature
8233 // Units far than max visible distance for creature or not in our map are not visible too
8234 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8235 return false;
8238 // Visible units, always are visible for all units, except for units under invisibility
8239 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0)
8240 return true;
8242 // GMs see any players, not higher GMs and all units
8243 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8245 if(GetTypeId() == TYPEID_PLAYER)
8246 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8247 else
8248 return true;
8251 // non faction visibility non-breakable for non-GMs
8252 if (m_Visibility == VISIBILITY_OFF)
8253 return false;
8255 // raw invisibility
8256 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8258 // detectable invisibility case
8259 if( invisible && (
8260 // Invisible units, always are visible for units under same invisibility type
8261 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8262 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8263 u->canDetectInvisibilityOf(this) ||
8264 // Units that can detect invisibility always are visible for units that can be detected
8265 canDetectInvisibilityOf(u) ))
8267 invisible = false;
8270 // special cases for always overwrite invisibility/stealth
8271 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8273 // non-hostile case
8274 if (!u->IsHostileTo(this))
8276 // 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)
8277 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8279 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8280 return true;
8282 // else apply same rules as for hostile case (detecting check for stealth)
8285 // hostile case
8286 else
8288 // Hunter mark functionality
8289 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8290 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8291 if((*iter)->GetCasterGUID()==u->GetGUID())
8292 return true;
8294 // else apply detecting check for stealth
8297 // none other cases for detect invisibility, so invisible
8298 if(invisible)
8299 return false;
8301 // else apply stealth detecting check
8304 // unit got in stealth in this moment and must ignore old detected state
8305 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8306 return false;
8308 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8309 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8310 return true;
8312 // NOW ONLY STEALTH CASE
8314 // stealth and detected and visible for some seconds
8315 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8316 return true;
8318 //if in non-detect mode then invisible for unit
8319 if (!detect)
8320 return false;
8322 // Special cases
8324 // If is attacked then stealth is lost, some creature can use stealth too
8325 if( !getAttackers().empty() )
8326 return true;
8328 // If there is collision rogue is seen regardless of level difference
8329 // TODO: check sizes in DB
8330 float distance = GetDistance(u);
8331 if (distance < 0.24f)
8332 return true;
8334 //If a mob or player is stunned he will not be able to detect stealth
8335 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8336 return false;
8338 // Creature can detect target only in aggro radius
8339 if(u->GetTypeId() != TYPEID_PLAYER)
8341 //Always invisible from back and out of aggro range
8342 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
8343 if(!isInFront)
8344 return false;
8346 else
8348 //Always invisible from back
8349 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
8350 if(!isInFront)
8351 return false;
8354 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
8355 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
8357 //Calculation if target is in front
8359 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
8360 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
8362 //Visible distance is modified by
8363 //-Level Diff (every level diff = 1.0f in visible distance)
8364 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
8366 //This allows to check talent tree and will add addition stealth dependent on used points)
8367 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
8368 if(stealthMod < 0)
8369 stealthMod = 0;
8371 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
8372 //based on wowwiki every 5 mod we have 1 more level diff in calculation
8373 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
8375 if(distance > visibleDistance)
8376 return false;
8379 // Now check is target visible with LoS
8380 float ox,oy,oz;
8381 u->GetPosition(ox,oy,oz);
8382 return IsWithinLOS(ox,oy,oz);
8385 void Unit::SetVisibility(UnitVisibility x)
8387 m_Visibility = x;
8389 if(IsInWorld())
8391 Map *m = GetMap();
8393 if(GetTypeId()==TYPEID_PLAYER)
8394 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8395 else
8396 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8400 bool Unit::canDetectInvisibilityOf(Unit const* u) const
8402 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
8404 for(uint32 i = 0; i < 10; ++i)
8406 if(((1 << i) & mask)==0)
8407 continue;
8409 // find invisibility level
8410 uint32 invLevel = 0;
8411 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
8412 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
8413 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
8414 invLevel = (*itr)->GetModifier()->m_amount;
8416 // find invisibility detect level
8417 uint32 detectLevel = 0;
8418 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
8419 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
8420 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
8421 detectLevel = (*itr)->GetModifier()->m_amount;
8423 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
8425 detectLevel = ((Player*)this)->GetDrunkValue();
8428 if(invLevel <= detectLevel)
8429 return true;
8433 return false;
8436 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
8438 int32 main_speed_mod = 0;
8439 float stack_bonus = 1.0f;
8440 float non_stack_bonus = 1.0f;
8442 switch(mtype)
8444 case MOVE_WALK:
8445 return;
8446 case MOVE_RUN:
8448 if (IsMounted()) // Use on mount auras
8450 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
8451 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
8452 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
8454 else
8456 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
8457 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
8458 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
8460 break;
8462 case MOVE_RUN_BACK:
8463 return;
8464 case MOVE_SWIM:
8466 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
8467 break;
8469 case MOVE_SWIM_BACK:
8470 return;
8471 case MOVE_FLIGHT:
8473 if (IsMounted()) // Use on mount auras
8474 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
8475 else // Use not mount (shapeshift for example) auras (should stack)
8476 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
8477 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
8478 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
8479 break;
8481 case MOVE_FLIGHT_BACK:
8482 return;
8483 default:
8484 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
8485 return;
8488 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
8489 // now we ready for speed calculation
8490 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
8492 switch(mtype)
8494 case MOVE_RUN:
8495 case MOVE_SWIM:
8496 case MOVE_FLIGHT:
8498 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
8499 // TODO: possible affect only on MOVE_RUN
8500 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
8502 // Use speed from aura
8503 float max_speed = normalization / baseMoveSpeed[mtype];
8504 if (speed > max_speed)
8505 speed = max_speed;
8507 break;
8509 default:
8510 break;
8513 // Apply strongest slow aura mod to speed
8514 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
8515 if (slow)
8516 speed *=(100.0f + slow)/100.0f;
8517 SetSpeed(mtype, speed, forced);
8520 float Unit::GetSpeed( UnitMoveType mtype ) const
8522 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
8525 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
8527 if (rate < 0)
8528 rate = 0.0f;
8530 // Update speed only on change
8531 if (m_speed_rate[mtype] == rate)
8532 return;
8534 m_speed_rate[mtype] = rate;
8536 propagateSpeedChange();
8538 WorldPacket data;
8539 if(!forced)
8541 switch(mtype)
8543 case MOVE_WALK:
8544 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8545 break;
8546 case MOVE_RUN:
8547 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
8548 break;
8549 case MOVE_RUN_BACK:
8550 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8551 break;
8552 case MOVE_SWIM:
8553 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
8554 break;
8555 case MOVE_SWIM_BACK:
8556 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8557 break;
8558 case MOVE_TURN_RATE:
8559 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
8560 break;
8561 case MOVE_FLIGHT:
8562 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
8563 break;
8564 case MOVE_FLIGHT_BACK:
8565 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8566 break;
8567 case MOVE_PITCH_RATE:
8568 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
8569 break;
8570 default:
8571 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
8572 return;
8575 data.append(GetPackGUID());
8576 data << uint32(0); // movement flags
8577 data << uint16(0); // unk flags
8578 data << uint32(getMSTime());
8579 data << float(GetPositionX());
8580 data << float(GetPositionY());
8581 data << float(GetPositionZ());
8582 data << float(GetOrientation());
8583 data << uint32(0); // fall time
8584 data << float(GetSpeed(mtype));
8585 SendMessageToSet( &data, true );
8587 else
8589 if(GetTypeId() == TYPEID_PLAYER)
8591 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
8592 // and do it only for real sent packets and use run for run/mounted as client expected
8593 ++((Player*)this)->m_forced_speed_changes[mtype];
8596 switch(mtype)
8598 case MOVE_WALK:
8599 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
8600 break;
8601 case MOVE_RUN:
8602 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
8603 break;
8604 case MOVE_RUN_BACK:
8605 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
8606 break;
8607 case MOVE_SWIM:
8608 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
8609 break;
8610 case MOVE_SWIM_BACK:
8611 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
8612 break;
8613 case MOVE_TURN_RATE:
8614 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
8615 break;
8616 case MOVE_FLIGHT:
8617 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
8618 break;
8619 case MOVE_FLIGHT_BACK:
8620 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
8621 break;
8622 case MOVE_PITCH_RATE:
8623 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
8624 break;
8625 default:
8626 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
8627 return;
8629 data.append(GetPackGUID());
8630 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
8631 if (mtype == MOVE_RUN)
8632 data << uint8(0); // new 2.1.0
8633 data << float(GetSpeed(mtype));
8634 SendMessageToSet( &data, true );
8636 if(Pet* pet = GetPet())
8637 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
8640 void Unit::SetHover(bool on)
8642 if(on)
8643 CastSpell(this,11010,true);
8644 else
8645 RemoveAurasDueToSpell(11010);
8648 void Unit::setDeathState(DeathState s)
8650 if (s != ALIVE && s!= JUST_ALIVED)
8652 CombatStop();
8653 DeleteThreatList();
8654 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
8656 if(IsNonMeleeSpellCasted(false))
8657 InterruptNonMeleeSpells(false);
8660 if (s == JUST_DIED)
8662 RemoveAllAurasOnDeath();
8663 UnsummonAllTotems();
8665 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
8666 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
8667 // remove aurastates allowing special moves
8668 ClearAllReactives();
8669 ClearDiminishings();
8671 else if(s == JUST_ALIVED)
8673 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
8676 if (m_deathState != ALIVE && s == ALIVE)
8678 //_ApplyAllAuraMods();
8680 m_deathState = s;
8683 /*########################################
8684 ######## ########
8685 ######## AGGRO SYSTEM ########
8686 ######## ########
8687 ########################################*/
8688 bool Unit::CanHaveThreatList() const
8690 // only creatures can have threat list
8691 if( GetTypeId() != TYPEID_UNIT )
8692 return false;
8694 // only alive units can have threat list
8695 if( !isAlive() )
8696 return false;
8698 // totems can not have threat list
8699 if( ((Creature*)this)->isTotem() )
8700 return false;
8702 // vehicles can not have threat list
8703 if( ((Creature*)this)->isVehicle() )
8704 return false;
8706 // pets can not have a threat list, unless they are controlled by a creature
8707 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
8708 return false;
8710 return true;
8713 //======================================================================
8715 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
8717 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
8718 return threat;
8720 SpellSchools school = GetFirstSchoolInMask(schoolMask);
8722 return threat * m_threatModifier[school];
8725 //======================================================================
8727 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
8729 // Only mobs can manage threat lists
8730 if(CanHaveThreatList())
8731 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
8734 //======================================================================
8736 void Unit::DeleteThreatList()
8738 m_ThreatManager.clearReferences();
8741 //======================================================================
8743 void Unit::TauntApply(Unit* taunter)
8745 assert(GetTypeId()== TYPEID_UNIT);
8747 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
8748 return;
8750 if(!CanHaveThreatList())
8751 return;
8753 Unit *target = getVictim();
8754 if(target && target == taunter)
8755 return;
8757 SetInFront(taunter);
8758 if (((Creature*)this)->AI())
8759 ((Creature*)this)->AI()->AttackStart(taunter);
8761 m_ThreatManager.tauntApply(taunter);
8764 //======================================================================
8766 void Unit::TauntFadeOut(Unit *taunter)
8768 assert(GetTypeId()== TYPEID_UNIT);
8770 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
8771 return;
8773 if(!CanHaveThreatList())
8774 return;
8776 Unit *target = getVictim();
8777 if(!target || target != taunter)
8778 return;
8780 if(m_ThreatManager.isThreatListEmpty())
8782 if(((Creature*)this)->AI())
8783 ((Creature*)this)->AI()->EnterEvadeMode();
8784 return;
8787 m_ThreatManager.tauntFadeOut(taunter);
8788 target = m_ThreatManager.getHostilTarget();
8790 if (target && target != taunter)
8792 SetInFront(target);
8793 if (((Creature*)this)->AI())
8794 ((Creature*)this)->AI()->AttackStart(target);
8798 //======================================================================
8800 bool Unit::SelectHostilTarget()
8802 //function provides main threat functionality
8803 //next-victim-selection algorithm and evade mode are called
8804 //threat list sorting etc.
8806 assert(GetTypeId()== TYPEID_UNIT);
8807 Unit* target = NULL;
8809 //This function only useful once AI has been initialized
8810 if (!((Creature*)this)->AI())
8811 return false;
8813 if(!m_ThreatManager.isThreatListEmpty())
8815 if(!HasAuraType(SPELL_AURA_MOD_TAUNT))
8817 target = m_ThreatManager.getHostilTarget();
8821 if(target)
8823 if(!hasUnitState(UNIT_STAT_STUNNED))
8824 SetInFront(target);
8825 ((Creature*)this)->AI()->AttackStart(target);
8826 return true;
8829 // no target but something prevent go to evade mode
8830 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
8831 return false;
8833 // last case when creature don't must go to evade mode:
8834 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
8835 // for example at owner command to pet attack some far away creature
8836 // Note: creature not have targeted movement generator but have attacker in this case
8837 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
8839 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
8841 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
8842 return false;
8846 // enter in evade mode in other case
8847 ((Creature*)this)->AI()->EnterEvadeMode();
8849 return false;
8852 //======================================================================
8853 //======================================================================
8854 //======================================================================
8856 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
8858 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
8860 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
8862 int32 level = int32(getLevel());
8863 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
8864 level = (int32)spellProto->maxLevel;
8865 else if (level < (int32)spellProto->baseLevel)
8866 level = (int32)spellProto->baseLevel;
8867 level-= (int32)spellProto->spellLevel;
8869 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
8870 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
8871 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
8872 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
8873 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
8875 // range can have possitive and negative values, so order its for irand
8876 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
8877 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
8878 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
8880 int32 value = basePoints + randvalue;
8881 //random damage
8882 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
8883 value += (int32)(comboDamage * comboPoints);
8885 if(Player* modOwner = GetSpellModOwner())
8887 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
8888 switch(effect_index)
8890 case 0:
8891 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
8892 break;
8893 case 1:
8894 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
8895 break;
8896 case 2:
8897 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
8898 break;
8902 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
8903 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
8904 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
8905 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
8907 return value;
8910 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
8912 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
8914 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
8916 int32 minduration = GetSpellDuration(spellProto);
8917 int32 maxduration = GetSpellMaxDuration(spellProto);
8919 int32 duration;
8921 if( minduration != -1 && minduration != maxduration )
8922 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
8923 else
8924 duration = minduration;
8926 if (duration > 0)
8928 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
8929 // Find total mod value (negative bonus)
8930 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
8931 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
8932 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
8933 // Find max mod (negative bonus)
8934 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
8936 int32 durationMod = 0;
8937 // Select strongest negative mod
8938 if (durationMod_always > durationMod_not_stack)
8939 durationMod = durationMod_not_stack;
8940 else
8941 durationMod = durationMod_always;
8943 if (durationMod != 0)
8944 duration = int32(int64(duration) * (100+durationMod) /100);
8946 if (duration < 0) duration = 0;
8949 return duration;
8952 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
8954 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
8956 if(i->DRGroup != group)
8957 continue;
8959 if(!i->hitCount)
8960 return DIMINISHING_LEVEL_1;
8962 if(!i->hitTime)
8963 return DIMINISHING_LEVEL_1;
8965 // If last spell was casted more than 15 seconds ago - reset the count.
8966 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
8968 i->hitCount = DIMINISHING_LEVEL_1;
8969 return DIMINISHING_LEVEL_1;
8971 // or else increase the count.
8972 else
8974 return DiminishingLevels(i->hitCount);
8977 return DIMINISHING_LEVEL_1;
8980 void Unit::IncrDiminishing(DiminishingGroup group)
8982 // Checking for existing in the table
8983 bool IsExist = false;
8984 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
8986 if(i->DRGroup != group)
8987 continue;
8989 IsExist = true;
8990 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
8991 i->hitCount += 1;
8993 break;
8996 if(!IsExist)
8997 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9000 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9002 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9003 return;
9005 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9006 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9008 // test pet/charm masters instead pets/charmeds
9009 Unit const* targetOwner = GetCharmerOrOwner();
9010 Unit const* casterOwner = caster->GetCharmerOrOwner();
9012 Unit const* target = targetOwner ? targetOwner : this;
9013 Unit const* source = casterOwner ? casterOwner : caster;
9015 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9016 duration = 10000;
9019 float mod = 1.0f;
9021 // Some diminishings applies to mobs too (for example, Stun)
9022 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9024 DiminishingLevels diminish = Level;
9025 switch(diminish)
9027 case DIMINISHING_LEVEL_1: break;
9028 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9029 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9030 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9031 default: break;
9035 duration = int32(duration * mod);
9038 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9040 // Checking for existing in the table
9041 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9043 if(i->DRGroup != group)
9044 continue;
9046 i->hitTime = getMSTime();
9048 if(apply)
9049 i->stack += 1;
9050 else if(i->stack)
9051 i->stack -= 1;
9053 break;
9057 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9059 return ObjectAccessor::GetUnit(object,guid);
9062 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9064 return isVisibleForOrDetect(u, false, inVisibleList, false);
9067 uint32 Unit::GetCreatureType() const
9069 if(GetTypeId() == TYPEID_PLAYER)
9071 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(((Player*)this)->m_form);
9072 if(ssEntry && ssEntry->creatureType > 0)
9073 return ssEntry->creatureType;
9074 else
9075 return CREATURE_TYPE_HUMANOID;
9077 else
9078 return ((Creature*)this)->GetCreatureInfo()->type;
9081 /*#######################################
9082 ######## ########
9083 ######## STAT SYSTEM ########
9084 ######## ########
9085 #######################################*/
9087 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9089 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9091 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9092 return false;
9095 float val = 1.0f;
9097 switch(modifierType)
9099 case BASE_VALUE:
9100 case TOTAL_VALUE:
9101 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9102 break;
9103 case BASE_PCT:
9104 case TOTAL_PCT:
9105 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9106 amount = -200.0f;
9108 val = (100.0f + amount) / 100.0f;
9109 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9110 break;
9112 default:
9113 break;
9116 if(!CanModifyStats())
9117 return false;
9119 switch(unitMod)
9121 case UNIT_MOD_STAT_STRENGTH:
9122 case UNIT_MOD_STAT_AGILITY:
9123 case UNIT_MOD_STAT_STAMINA:
9124 case UNIT_MOD_STAT_INTELLECT:
9125 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9127 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9128 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9130 case UNIT_MOD_MANA:
9131 case UNIT_MOD_RAGE:
9132 case UNIT_MOD_FOCUS:
9133 case UNIT_MOD_ENERGY:
9134 case UNIT_MOD_HAPPINESS:
9135 case UNIT_MOD_RUNE:
9136 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9138 case UNIT_MOD_RESISTANCE_HOLY:
9139 case UNIT_MOD_RESISTANCE_FIRE:
9140 case UNIT_MOD_RESISTANCE_NATURE:
9141 case UNIT_MOD_RESISTANCE_FROST:
9142 case UNIT_MOD_RESISTANCE_SHADOW:
9143 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9145 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9146 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9148 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9149 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9150 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9152 default:
9153 break;
9156 return true;
9159 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9161 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9163 sLog.outError("ERROR: trial to access non existed modifier value from UnitMods!");
9164 return 0.0f;
9167 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9168 return 0.0f;
9170 return m_auraModifiersGroup[unitMod][modifierType];
9173 float Unit::GetTotalStatValue(Stats stat) const
9175 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9177 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9178 return 0.0f;
9180 // value = ((base_value * base_pct) + total_value) * total_pct
9181 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9182 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9183 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9184 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9186 return value;
9189 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9191 if(unitMod >= UNIT_MOD_END)
9193 sLog.outError("ERROR: trial to access non existed UnitMods in GetTotalAuraModValue()!");
9194 return 0.0f;
9197 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9198 return 0.0f;
9200 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9201 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9202 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9203 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9205 return value;
9208 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9210 SpellSchools school = SPELL_SCHOOL_NORMAL;
9212 switch(unitMod)
9214 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9215 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9216 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9217 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9218 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9219 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9221 default:
9222 break;
9225 return school;
9228 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9230 Stats stat = STAT_STRENGTH;
9232 switch(unitMod)
9234 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9235 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9236 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9237 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9238 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9240 default:
9241 break;
9244 return stat;
9247 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9249 switch(unitMod)
9251 case UNIT_MOD_MANA: return POWER_MANA;
9252 case UNIT_MOD_RAGE: return POWER_RAGE;
9253 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9254 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9255 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9256 case UNIT_MOD_RUNE: return POWER_RUNE;
9257 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9260 return POWER_MANA;
9263 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9265 UnitMods unitMod = (attType == RANGED_ATTACK) ? UNIT_MOD_ATTACK_POWER_RANGED : UNIT_MOD_ATTACK_POWER;
9267 float val = GetTotalAuraModValue(unitMod);
9268 if(val < 0.0f)
9269 val = 0.0f;
9271 return val;
9274 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9276 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9277 return 0.0f;
9279 return m_weaponDamage[attType][type];
9282 void Unit::SetLevel(uint32 lvl)
9284 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9286 // group update
9287 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9288 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9291 void Unit::SetHealth(uint32 val)
9293 uint32 maxHealth = GetMaxHealth();
9294 if(maxHealth < val)
9295 val = maxHealth;
9297 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9299 // group update
9300 if(GetTypeId() == TYPEID_PLAYER)
9302 if(((Player*)this)->GetGroup())
9303 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9305 else if(((Creature*)this)->isPet())
9307 Pet *pet = ((Pet*)this);
9308 if(pet->isControlled())
9310 Unit *owner = GetOwner();
9311 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9312 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
9317 void Unit::SetMaxHealth(uint32 val)
9319 uint32 health = GetHealth();
9320 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
9322 // group update
9323 if(GetTypeId() == TYPEID_PLAYER)
9325 if(((Player*)this)->GetGroup())
9326 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
9328 else if(((Creature*)this)->isPet())
9330 Pet *pet = ((Pet*)this);
9331 if(pet->isControlled())
9333 Unit *owner = GetOwner();
9334 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9335 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
9339 if(val < health)
9340 SetHealth(val);
9343 void Unit::SetPower(Powers power, uint32 val)
9345 if(GetPower(power) == val)
9346 return;
9348 uint32 maxPower = GetMaxPower(power);
9349 if(maxPower < val)
9350 val = maxPower;
9352 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
9354 WorldPacket data(SMSG_POWER_UPDATE);
9355 data.append(GetPackGUID());
9356 data << uint8(power);
9357 data << uint32(val);
9358 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
9360 // group update
9361 if(GetTypeId() == TYPEID_PLAYER)
9363 if(((Player*)this)->GetGroup())
9364 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9366 else if(((Creature*)this)->isPet())
9368 Pet *pet = ((Pet*)this);
9369 if(pet->isControlled())
9371 Unit *owner = GetOwner();
9372 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9373 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9376 // Update the pet's character sheet with happiness damage bonus
9377 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
9379 pet->UpdateDamagePhysical(BASE_ATTACK);
9384 void Unit::SetMaxPower(Powers power, uint32 val)
9386 uint32 cur_power = GetPower(power);
9387 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
9389 // group update
9390 if(GetTypeId() == TYPEID_PLAYER)
9392 if(((Player*)this)->GetGroup())
9393 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9395 else if(((Creature*)this)->isPet())
9397 Pet *pet = ((Pet*)this);
9398 if(pet->isControlled())
9400 Unit *owner = GetOwner();
9401 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9402 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
9406 if(val < cur_power)
9407 SetPower(power, val);
9410 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
9412 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
9414 // group update
9415 if(GetTypeId() == TYPEID_PLAYER)
9417 if(((Player*)this)->GetGroup())
9418 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9420 else if(((Creature*)this)->isPet())
9422 Pet *pet = ((Pet*)this);
9423 if(pet->isControlled())
9425 Unit *owner = GetOwner();
9426 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9427 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9432 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
9434 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
9436 // group update
9437 if(GetTypeId() == TYPEID_PLAYER)
9439 if(((Player*)this)->GetGroup())
9440 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9442 else if(((Creature*)this)->isPet())
9444 Pet *pet = ((Pet*)this);
9445 if(pet->isControlled())
9447 Unit *owner = GetOwner();
9448 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9449 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
9454 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
9456 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
9457 if(apply)
9458 tAuraProcTriggerDamage.push_back(aura);
9459 else
9460 tAuraProcTriggerDamage.remove(aura);
9463 uint32 Unit::GetCreatePowers( Powers power ) const
9465 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
9466 switch(power)
9468 case POWER_MANA: return GetCreateMana();
9469 case POWER_RAGE: return 1000;
9470 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
9471 case POWER_ENERGY: return 100;
9472 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
9473 case POWER_RUNIC_POWER: return 1000;
9476 return 0;
9479 void Unit::AddToWorld()
9481 Object::AddToWorld();
9484 void Unit::RemoveFromWorld()
9486 // cleanup
9487 if(IsInWorld())
9489 RemoveNotOwnSingleTargetAuras();
9492 Object::RemoveFromWorld();
9495 void Unit::CleanupsBeforeDelete()
9497 if(m_uint32Values) // only for fully created object
9499 InterruptNonMeleeSpells(true);
9500 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
9501 CombatStop();
9502 ClearComboPointHolders();
9503 DeleteThreatList();
9504 getHostilRefManager().setOnlineOfflineState(false);
9505 RemoveAllAuras();
9506 RemoveAllGameObjects();
9507 RemoveAllDynObjects();
9508 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
9510 RemoveFromWorld();
9513 CharmInfo* Unit::InitCharmInfo(Unit *charm)
9515 if(!m_charmInfo)
9516 m_charmInfo = new CharmInfo(charm);
9517 return m_charmInfo;
9520 CharmInfo::CharmInfo(Unit* unit)
9521 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
9523 for(int i =0; i<4; ++i)
9525 m_charmspells[i].spellId = 0;
9526 m_charmspells[i].active = ACT_DISABLED;
9530 void CharmInfo::InitPetActionBar()
9532 // the first 3 SpellOrActions are attack, follow and stay
9533 for(uint32 i = 0; i < 3; i++)
9535 PetActionBar[i].Type = ACT_COMMAND;
9536 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
9538 PetActionBar[i + 7].Type = ACT_REACTION;
9539 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
9541 for(uint32 i=0; i < 4; i++)
9543 PetActionBar[i + 3].Type = ACT_DISABLED;
9544 PetActionBar[i + 3].SpellOrAction = 0;
9548 void CharmInfo::InitEmptyActionBar()
9550 for(uint32 x = 1; x < 10; ++x)
9552 PetActionBar[x].Type = ACT_PASSIVE;
9553 PetActionBar[x].SpellOrAction = 0;
9555 PetActionBar[0].Type = ACT_COMMAND;
9556 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
9559 void CharmInfo::InitPossessCreateSpells()
9561 if(m_unit->GetTypeId() == TYPEID_PLAYER)
9562 return;
9564 InitEmptyActionBar(); //charm action bar
9566 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
9568 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
9569 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
9570 else
9571 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
9575 void CharmInfo::InitCharmCreateSpells()
9577 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
9579 InitEmptyActionBar();
9580 return;
9583 InitPetActionBar();
9585 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
9587 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
9588 m_charmspells[x].spellId = spellId;
9590 if(!spellId)
9591 continue;
9593 if (IsPassiveSpell(spellId))
9595 m_unit->CastSpell(m_unit, spellId, true);
9596 m_charmspells[x].active = ACT_PASSIVE;
9598 else
9600 ActiveStates newstate;
9601 bool onlyselfcast = true;
9602 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
9604 if(!spellInfo) onlyselfcast = false;
9605 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
9607 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
9608 onlyselfcast = false;
9611 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
9612 newstate = ACT_DISABLED;
9613 else
9614 newstate = ACT_PASSIVE;
9616 AddSpellToAB(0, spellId, newstate);
9621 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
9623 for(uint8 i = 0; i < 10; i++)
9625 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
9627 PetActionBar[i].SpellOrAction = newid;
9628 if(!oldid)
9630 if(newstate == ACT_DECIDE)
9631 PetActionBar[i].Type = ACT_DISABLED;
9632 else
9633 PetActionBar[i].Type = newstate;
9636 return true;
9639 return false;
9642 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
9644 if(IsPassiveSpell(spellid))
9645 return;
9647 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
9649 if(spellid == m_charmspells[x].spellId)
9651 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
9656 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
9658 m_petnumber = petnumber;
9659 if(statwindow)
9660 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
9661 else
9662 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
9665 bool Unit::isFrozen() const
9667 AuraList const& mRoot = GetAurasByType(SPELL_AURA_MOD_ROOT);
9668 for(AuraList::const_iterator i = mRoot.begin(); i != mRoot.end(); ++i)
9669 if( GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
9670 return true;
9671 return false;
9674 struct ProcTriggeredData
9676 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
9677 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
9678 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
9680 SpellProcEventEntry const *spellProcEvent;
9681 Aura* triggeredByAura;
9682 Unit::spellEffectPair triggeredByAura_SpellPair;
9685 typedef std::list< ProcTriggeredData > ProcTriggeredList;
9686 typedef std::list< uint32> RemoveSpellList;
9688 // List of auras that CAN be trigger but may not exist in spell_proc_event
9689 // in most case need for drop charges
9690 // in some types of aura need do additional check
9691 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
9692 bool InitTriggerAuraData()
9694 for (int i=0;i<TOTAL_AURAS;i++)
9696 isTriggerAura[i]=false;
9697 isNonTriggerAura[i] = false;
9699 isTriggerAura[SPELL_AURA_PERIODIC_DAMAGE] = true;
9700 isTriggerAura[SPELL_AURA_DUMMY] = true;
9701 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
9702 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
9703 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
9704 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
9705 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
9706 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
9707 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
9708 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
9709 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
9710 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
9711 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
9712 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED] = true;
9713 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
9714 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
9715 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
9716 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
9717 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
9718 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
9719 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
9720 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
9721 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
9722 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
9723 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
9724 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
9725 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
9726 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
9727 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
9729 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
9730 isNonTriggerAura[SPELL_AURA_RESIST_PUSHBACK]=true;
9732 return true;
9735 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
9737 uint32 procEx = PROC_EX_NONE;
9738 // Check victim state
9739 if (missCondition!=SPELL_MISS_NONE)
9740 switch (missCondition)
9742 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
9743 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
9744 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
9745 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
9746 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
9747 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
9748 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
9749 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
9750 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
9751 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
9752 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
9753 default:
9754 break;
9756 else
9758 // On block
9759 if (damageInfo->blocked)
9760 procEx|=PROC_EX_BLOCK;
9761 // On absorb
9762 if (damageInfo->absorb)
9763 procEx|=PROC_EX_ABSORB;
9764 // On crit
9765 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
9766 procEx|=PROC_EX_CRITICAL_HIT;
9767 else
9768 procEx|=PROC_EX_NORMAL_HIT;
9770 return procEx;
9773 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
9775 // For melee/ranged based attack need update skills and set some Aura states
9776 if (procFlag & MELEE_BASED_TRIGGER_MASK)
9778 // Update skills here for players
9779 if (GetTypeId() == TYPEID_PLAYER)
9781 // On melee based hit/miss/resist need update skill (for victim and attacker)
9782 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
9784 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
9785 ((Player*)this)->UpdateCombatSkills(pTarget, attType, MELEE_HIT_MISS, isVictim);
9787 // Update defence if player is victim and parry/dodge/block
9788 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
9789 ((Player*)this)->UpdateDefense();
9791 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
9792 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
9794 // for victim
9795 if (isVictim)
9797 // if victim and dodge attack
9798 if (procExtra&PROC_EX_DODGE)
9800 //Update AURA_STATE on dodge
9801 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
9803 ModifyAuraState(AURA_STATE_DEFENSE, true);
9804 StartReactiveTimer( REACTIVE_DEFENSE );
9807 // if victim and parry attack
9808 if (procExtra & PROC_EX_PARRY)
9810 // For Hunters only Counterattack (skip Mongoose bite)
9811 if (getClass() == CLASS_HUNTER)
9813 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
9814 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
9816 else
9818 ModifyAuraState(AURA_STATE_DEFENSE, true);
9819 StartReactiveTimer( REACTIVE_DEFENSE );
9822 // if and victim block attack
9823 if (procExtra & PROC_EX_BLOCK)
9825 ModifyAuraState(AURA_STATE_DEFENSE,true);
9826 StartReactiveTimer( REACTIVE_DEFENSE );
9829 else //For attacker
9831 // Overpower on victim dodge
9832 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
9834 ((Player*)this)->AddComboPoints(pTarget, 1);
9835 StartReactiveTimer( REACTIVE_OVERPOWER );
9841 RemoveSpellList removedSpells;
9842 ProcTriggeredList procTriggered;
9843 // Fill procTriggered list
9844 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
9846 SpellProcEventEntry const* spellProcEvent = NULL;
9847 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
9848 continue;
9850 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
9853 // Nothing found
9854 if (procTriggered.empty())
9855 return;
9857 // Handle effects proceed this time
9858 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
9860 // Some auras can be deleted in function called in this loop (except first, ofc)
9861 // Until storing auars in std::multimap to hard check deleting by another way
9862 if(i != procTriggered.begin())
9864 bool found = false;
9865 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
9866 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
9867 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
9869 if(itr->second==i->triggeredByAura)
9871 found = true;
9872 break;
9875 if(!found)
9877 // 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);
9878 // sLog.outDebug("It can be deleted one from early proccesed auras:");
9879 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
9880 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
9881 // sLog.outDebug(" <end of list>");
9882 continue;
9886 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
9887 Aura *triggeredByAura = i->triggeredByAura;
9888 Modifier *auraModifier = triggeredByAura->GetModifier();
9889 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
9890 uint32 effIndex = triggeredByAura->GetEffIndex();
9891 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
9892 // For players set spell cooldown if need
9893 uint32 cooldown = 0;
9894 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
9895 cooldown = spellProcEvent->cooldown;
9897 switch(auraModifier->m_auraname)
9899 case SPELL_AURA_PROC_TRIGGER_SPELL:
9901 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
9902 // Don`t drop charge or add cooldown for not started trigger
9903 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9904 continue;
9905 break;
9907 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
9909 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());
9910 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
9911 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
9912 SendSpellNonMeleeDamageLog(&damageInfo);
9913 DealSpellDamage(&damageInfo, true);
9914 break;
9916 case SPELL_AURA_MANA_SHIELD:
9917 case SPELL_AURA_DUMMY:
9919 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());
9920 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9921 continue;
9922 break;
9924 case SPELL_AURA_MOD_HASTE:
9926 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());
9927 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9928 continue;
9929 break;
9931 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
9933 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());
9934 if (!HandleOverrideClassScriptAuraProc(pTarget, triggeredByAura, procSpell, cooldown))
9935 continue;
9936 break;
9938 case SPELL_AURA_PRAYER_OF_MENDING:
9940 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
9941 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
9943 HandleMeandingAuraProc(triggeredByAura);
9944 break;
9946 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
9948 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());
9950 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9951 continue;
9952 break;
9954 case SPELL_AURA_MOD_CASTING_SPEED:
9955 // Skip melee hits or instant cast spells
9956 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
9957 continue;
9958 break;
9959 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
9960 // Skip Melee hits and spells ws wrong school
9961 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
9962 continue;
9963 break;
9964 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
9965 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
9966 // Skip melee hits and spells ws wrong school or zero cost
9967 if (procSpell == NULL ||
9968 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
9969 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
9970 continue;
9971 break;
9972 case SPELL_AURA_MECHANIC_IMMUNITY:
9973 // Compare mechanic
9974 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
9975 continue;
9976 break;
9977 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
9978 // Compare mechanic
9979 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
9980 continue;
9981 break;
9982 default:
9983 // nothing do, just charges counter
9984 break;
9986 // Remove charge (aura can be removed by triggers)
9987 if(useCharges)
9989 // need found aura on drop (can be dropped by triggers)
9990 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
9991 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
9992 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
9994 // If last charge dropped add spell to remove list
9995 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
9997 removedSpells.push_back(triggeredByAura->GetId());
9998 break;
10003 if (!removedSpells.empty())
10005 // Sort spells and remove dublicates
10006 removedSpells.sort();
10007 removedSpells.unique();
10008 // Remove auras from removedAuras
10009 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
10010 RemoveAurasDueToSpell(*i);
10014 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10016 return SPELL_SCHOOL_MASK_NORMAL;
10019 Player* Unit::GetSpellModOwner()
10021 if(GetTypeId()==TYPEID_PLAYER)
10022 return (Player*)this;
10023 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10025 Unit* owner = GetOwner();
10026 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10027 return (Player*)owner;
10029 return NULL;
10032 ///----------Pet responses methods-----------------
10033 void Unit::SendPetCastFail(uint32 spellid, uint8 msg)
10035 Unit *owner = GetCharmerOrOwner();
10036 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10037 return;
10039 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
10040 data << uint8(0); // cast count?
10041 data << uint32(spellid);
10042 data << uint8(msg);
10043 // uint32 for some reason
10044 // uint32 for some reason
10045 ((Player*)owner)->GetSession()->SendPacket(&data);
10048 void Unit::SendPetActionFeedback (uint8 msg)
10050 Unit* owner = GetOwner();
10051 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10052 return;
10054 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10055 data << uint8(msg);
10056 ((Player*)owner)->GetSession()->SendPacket(&data);
10059 void Unit::SendPetTalk (uint32 pettalk)
10061 Unit* owner = GetOwner();
10062 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10063 return;
10065 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
10066 data << uint64(GetGUID());
10067 data << uint32(pettalk);
10068 ((Player*)owner)->GetSession()->SendPacket(&data);
10071 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10073 Unit* owner = GetOwner();
10074 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10075 return;
10077 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10078 data << uint64(GetGUID());
10079 data << uint8(0x0); // flags (0x1, 0x2)
10080 data << uint32(spellid);
10081 data << uint32(cooltime);
10083 ((Player*)owner)->GetSession()->SendPacket(&data);
10086 void Unit::SendPetClearCooldown (uint32 spellid)
10088 Unit* owner = GetOwner();
10089 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10090 return;
10092 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10093 data << uint32(spellid);
10094 data << uint64(GetGUID());
10095 ((Player*)owner)->GetSession()->SendPacket(&data);
10098 void Unit::SendPetAIReaction(uint64 guid)
10100 Unit* owner = GetOwner();
10101 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10102 return;
10104 WorldPacket data(SMSG_AI_REACTION, 12);
10105 data << uint64(guid) << uint32(00000002);
10106 ((Player*)owner)->GetSession()->SendPacket(&data);
10109 ///----------End of Pet responses methods----------
10111 void Unit::StopMoving()
10113 clearUnitState(UNIT_STAT_MOVING);
10115 // send explicit stop packet
10116 // rely on vmaps here because for example stormwind is in air
10117 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10118 //if (fabs(GetPositionZ() - z) < 2.0f)
10119 // Relocate(GetPositionX(), GetPositionY(), z);
10120 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10122 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10124 // update position and orientation;
10125 WorldPacket data;
10126 BuildHeartBeatMsg(&data);
10127 SendMessageToSet(&data,false);
10130 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10132 if( apply )
10134 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10135 return;
10137 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10139 GetMotionMaster()->MovementExpired(false);
10140 CastStop(GetGUID()==casterGUID ? spellID : 0);
10142 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10144 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10146 else
10148 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10150 GetMotionMaster()->MovementExpired(false);
10152 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10154 // restore appropriate movement generator
10155 if(getVictim())
10156 GetMotionMaster()->MoveChase(getVictim());
10157 else
10158 GetMotionMaster()->Initialize();
10160 // attack caster if can
10161 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10162 if(caster && caster != getVictim() && ((Creature*)this)->AI())
10163 ((Creature*)this)->AI()->AttackStart(caster);
10167 if (GetTypeId() == TYPEID_PLAYER)
10168 ((Player*)this)->SetClientControl(this, !apply);
10171 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10173 if( apply )
10175 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10177 CastStop(GetGUID()==casterGUID ? spellID : 0);
10179 GetMotionMaster()->MoveConfused();
10181 else
10183 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10185 GetMotionMaster()->MovementExpired(false);
10187 if (GetTypeId() == TYPEID_UNIT)
10189 // if in combat restore movement generator
10190 if(getVictim())
10191 GetMotionMaster()->MoveChase(getVictim());
10195 if(GetTypeId() == TYPEID_PLAYER)
10196 ((Player*)this)->SetClientControl(this, !apply);
10199 bool Unit::IsSitState() const
10201 uint8 s = getStandState();
10202 return s == PLAYER_STATE_SIT_CHAIR || s == PLAYER_STATE_SIT_LOW_CHAIR ||
10203 s == PLAYER_STATE_SIT_MEDIUM_CHAIR || s == PLAYER_STATE_SIT_HIGH_CHAIR ||
10204 s == PLAYER_STATE_SIT;
10207 bool Unit::IsStandState() const
10209 uint8 s = getStandState();
10210 return !IsSitState() && s != PLAYER_STATE_SLEEP && s != PLAYER_STATE_KNEEL;
10213 void Unit::SetStandState(uint8 state)
10215 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10217 if (IsStandState())
10218 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10220 if(GetTypeId()==TYPEID_PLAYER)
10222 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10223 data << (uint8)state;
10224 ((Player*)this)->GetSession()->SendPacket(&data);
10228 bool Unit::IsPolymorphed() const
10230 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10233 void Unit::SetDisplayId(uint32 modelId)
10235 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10237 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10239 Pet *pet = ((Pet*)this);
10240 if(!pet->isControlled())
10241 return;
10242 Unit *owner = GetOwner();
10243 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10244 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10248 void Unit::ClearComboPointHolders()
10250 while(!m_ComboPointHolders.empty())
10252 uint32 lowguid = *m_ComboPointHolders.begin();
10254 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10255 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10256 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10257 else
10258 m_ComboPointHolders.erase(lowguid); // or remove manually
10262 void Unit::ClearAllReactives()
10264 for(int i=0; i < MAX_REACTIVE; ++i)
10265 m_reactiveTimer[i] = 0;
10267 if (HasAuraState( AURA_STATE_DEFENSE))
10268 ModifyAuraState(AURA_STATE_DEFENSE, false);
10269 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10270 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10271 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10272 ((Player*)this)->ClearComboPoints();
10275 void Unit::UpdateReactives( uint32 p_time )
10277 for(int i = 0; i < MAX_REACTIVE; ++i)
10279 ReactiveType reactive = ReactiveType(i);
10281 if(!m_reactiveTimer[reactive])
10282 continue;
10284 if ( m_reactiveTimer[reactive] <= p_time)
10286 m_reactiveTimer[reactive] = 0;
10288 switch ( reactive )
10290 case REACTIVE_DEFENSE:
10291 if (HasAuraState(AURA_STATE_DEFENSE))
10292 ModifyAuraState(AURA_STATE_DEFENSE, false);
10293 break;
10294 case REACTIVE_HUNTER_PARRY:
10295 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10296 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10297 break;
10298 case REACTIVE_OVERPOWER:
10299 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10300 ((Player*)this)->ClearComboPoints();
10301 break;
10302 default:
10303 break;
10306 else
10308 m_reactiveTimer[reactive] -= p_time;
10313 Unit* Unit::SelectNearbyTarget() const
10315 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
10316 Cell cell(p);
10317 cell.data.Part.reserved = ALL_DISTRICT;
10318 cell.SetNoCreate();
10320 std::list<Unit *> targets;
10323 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
10324 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(targets, u_check);
10326 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
10327 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
10329 CellLock<GridReadGuard> cell_lock(cell, p);
10330 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
10331 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
10334 // remove current target
10335 if(getVictim())
10336 targets.remove(getVictim());
10338 // remove not LoS targets
10339 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
10341 if(!IsWithinLOSInMap(*tIter))
10343 std::list<Unit *>::iterator tIter2 = tIter;
10344 ++tIter;
10345 targets.erase(tIter2);
10347 else
10348 ++tIter;
10351 // no appropriate targets
10352 if(targets.empty())
10353 return NULL;
10355 // select random
10356 uint32 rIdx = urand(0,targets.size()-1);
10357 std::list<Unit *>::const_iterator tcIter = targets.begin();
10358 for(uint32 i = 0; i < rIdx; ++i)
10359 ++tcIter;
10361 return *tcIter;
10364 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
10366 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
10368 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
10369 return true;
10371 return false;
10374 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
10376 if(val > 0)
10378 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
10379 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
10381 else
10383 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
10384 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
10388 void Unit::ApplyCastTimePercentMod(float val, bool apply )
10390 if(val > 0)
10391 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
10392 else
10393 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
10396 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
10398 // Not apply this to creature casted spells with casttime==0
10399 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
10400 return 3500;
10402 if (CastingTime > 7000) CastingTime = 7000;
10403 if (CastingTime < 1500) CastingTime = 1500;
10405 if(damagetype == DOT && !IsChanneledSpell(spellProto))
10406 CastingTime = 3500;
10408 int32 overTime = 0;
10409 uint8 effects = 0;
10410 bool DirectDamage = false;
10411 bool AreaEffect = false;
10413 for ( uint32 i=0; i<3;i++)
10415 switch ( spellProto->Effect[i] )
10417 case SPELL_EFFECT_SCHOOL_DAMAGE:
10418 case SPELL_EFFECT_POWER_DRAIN:
10419 case SPELL_EFFECT_HEALTH_LEECH:
10420 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
10421 case SPELL_EFFECT_POWER_BURN:
10422 case SPELL_EFFECT_HEAL:
10423 DirectDamage = true;
10424 break;
10425 case SPELL_EFFECT_APPLY_AURA:
10426 switch ( spellProto->EffectApplyAuraName[i] )
10428 case SPELL_AURA_PERIODIC_DAMAGE:
10429 case SPELL_AURA_PERIODIC_HEAL:
10430 case SPELL_AURA_PERIODIC_LEECH:
10431 if ( GetSpellDuration(spellProto) )
10432 overTime = GetSpellDuration(spellProto);
10433 break;
10434 default:
10435 // -5% per additional effect
10436 ++effects;
10437 break;
10439 default:
10440 break;
10443 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
10444 AreaEffect = true;
10447 // Combined Spells with Both Over Time and Direct Damage
10448 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
10450 // mainly for DoTs which are 3500 here otherwise
10451 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
10452 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
10453 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
10454 // Portion to Over Time
10455 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
10457 if ( damagetype == DOT )
10458 CastingTime = uint32(CastingTime * PtOT);
10459 else if ( PtOT < 1.0f )
10460 CastingTime = uint32(CastingTime * (1 - PtOT));
10461 else
10462 CastingTime = 0;
10465 // Area Effect Spells receive only half of bonus
10466 if ( AreaEffect )
10467 CastingTime /= 2;
10469 // -5% of total per any additional effect
10470 for ( uint8 i=0; i<effects; ++i)
10472 if ( CastingTime > 175 )
10474 CastingTime -= 175;
10476 else
10478 CastingTime = 0;
10479 break;
10483 return CastingTime;
10486 void Unit::UpdateAuraForGroup(uint8 slot)
10488 if(GetTypeId() == TYPEID_PLAYER)
10490 Player* player = (Player*)this;
10491 if(player->GetGroup())
10493 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
10494 player->SetAuraUpdateMask(slot);
10497 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10499 Pet *pet = ((Pet*)this);
10500 if(pet->isControlled())
10502 Unit *owner = GetOwner();
10503 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10505 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
10506 pet->SetAuraUpdateMask(slot);
10512 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
10514 if (!normalized || GetTypeId() != TYPEID_PLAYER)
10515 return float(GetAttackTime(attType))/1000.0f;
10517 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
10518 if (!Weapon)
10519 return 2.4; // fist attack
10521 switch (Weapon->GetProto()->InventoryType)
10523 case INVTYPE_2HWEAPON:
10524 return 3.3;
10525 case INVTYPE_RANGED:
10526 case INVTYPE_RANGEDRIGHT:
10527 case INVTYPE_THROWN:
10528 return 2.8;
10529 case INVTYPE_WEAPON:
10530 case INVTYPE_WEAPONMAINHAND:
10531 case INVTYPE_WEAPONOFFHAND:
10532 default:
10533 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
10537 Aura* Unit::GetDummyAura( uint32 spell_id ) const
10539 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
10540 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
10541 if ((*itr)->GetId() == spell_id)
10542 return *itr;
10544 return NULL;
10547 bool Unit::IsUnderLastManaUseEffect() const
10549 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
10552 void Unit::SetContestedPvP(Player *attackedPlayer)
10554 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
10556 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
10557 return;
10559 player->SetContestedPvPTimer(30000);
10560 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
10562 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
10563 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
10564 // call MoveInLineOfSight for nearby contested guards
10565 SetVisibility(GetVisibility());
10567 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
10569 addUnitState(UNIT_STAT_ATTACK_PLAYER);
10570 // call MoveInLineOfSight for nearby contested guards
10571 SetVisibility(GetVisibility());
10575 void Unit::AddPetAura(PetAura const* petSpell)
10577 m_petAuras.insert(petSpell);
10578 if(Pet* pet = GetPet())
10579 pet->CastPetAura(petSpell);
10582 void Unit::RemovePetAura(PetAura const* petSpell)
10584 m_petAuras.erase(petSpell);
10585 if(Pet* pet = GetPet())
10586 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
10589 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
10591 Pet* pet = new Pet(HUNTER_PET);
10593 if(!pet->CreateBaseAtCreature(creatureTarget))
10595 delete pet;
10596 return NULL;
10599 pet->SetOwnerGUID(GetGUID());
10600 pet->SetCreatorGUID(GetGUID());
10601 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
10602 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
10604 if(GetTypeId()==TYPEID_PLAYER)
10605 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
10607 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
10608 pet->SetFreeTalentPoints(pet->GetMaxTalentPointsForLevel(level));
10610 if(!pet->InitStatsForLevel(level))
10612 sLog.outError("ERROR: Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
10613 delete pet;
10614 return NULL;
10617 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
10618 // this enables pet details window (Shift+P)
10619 pet->AIM_Initialize();
10620 pet->InitPetCreateSpells();
10621 pet->SetHealth(pet->GetMaxHealth());
10623 return pet;
10626 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
10628 SpellEntry const* spellProto = aura->GetSpellProto ();
10630 // Get proc Event Entry
10631 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
10633 // Aura info stored here
10634 Modifier *mod = aura->GetModifier();
10635 // Skip this auras
10636 if (isNonTriggerAura[mod->m_auraname])
10637 return false;
10638 // If not trigger by default and spellProcEvent==NULL - skip
10639 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
10640 return false;
10642 // Get EventProcFlag
10643 uint32 EventProcFlag;
10644 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
10645 EventProcFlag = spellProcEvent->procFlags;
10646 else
10647 EventProcFlag = spellProto->procFlags; // else get from spell proto
10648 // Continue if no trigger exist
10649 if (!EventProcFlag)
10650 return false;
10652 // Check spellProcEvent data requirements
10653 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
10654 return false;
10656 // In most cases req get honor or XP from kill
10657 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
10659 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
10660 // Shadow Word: Death - can trigger from every kill
10661 if (aura->GetId() == 32409)
10662 allow = true;
10663 if (!allow)
10664 return false;
10666 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
10667 // But except periodic triggers (can triggered from self)
10668 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
10669 return false;
10671 // Check if current equipment allows aura to proc
10672 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
10674 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
10676 Item *item = NULL;
10677 if(attType == BASE_ATTACK)
10678 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
10679 else if (attType == OFF_ATTACK)
10680 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
10681 else
10682 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
10684 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
10685 return false;
10687 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
10688 return false;
10690 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
10692 // Check if player is wearing shield
10693 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
10694 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
10695 return false;
10698 // Get chance from spell
10699 float chance = (float)spellProto->procChance;
10700 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
10701 if(spellProcEvent && spellProcEvent->customChance)
10702 chance = spellProcEvent->customChance;
10703 // If PPM exist calculate chance from PPM
10704 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
10706 uint32 WeaponSpeed = GetAttackTime(attType);
10707 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
10709 // Apply chance modifer aura
10710 if(Player* modOwner = GetSpellModOwner())
10711 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
10713 return roll_chance_f(chance);
10716 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
10718 // aura can be deleted at casts
10719 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
10720 uint32 effIdx = triggeredByAura->GetEffIndex();
10721 int32 heal = triggeredByAura->GetModifier()->m_amount;
10722 uint64 caster_guid = triggeredByAura->GetCasterGUID();
10724 // jumps
10725 int32 jumps = triggeredByAura->GetAuraCharges()-1;
10727 // current aura expire
10728 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
10730 // next target selection
10731 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
10733 float radius;
10734 if (spellProto->EffectRadiusIndex[effIdx])
10735 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
10736 else
10737 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
10739 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
10741 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
10743 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
10745 // aura will applied from caster, but spell casted from current aura holder
10746 SpellModifier *mod = new SpellModifier;
10747 mod->op = SPELLMOD_CHARGES;
10748 mod->value = jumps-5; // negative
10749 mod->type = SPELLMOD_FLAT;
10750 mod->spellId = spellProto->Id;
10751 mod->mask = spellProto->SpellFamilyFlags;
10752 mod->mask2 = spellProto->SpellFamilyFlags2;
10754 caster->AddSpellMod(mod, true);
10755 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
10756 caster->AddSpellMod(mod, false);
10761 // heal
10762 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
10763 return true;
10766 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
10768 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
10770 if(!IS_UNIT_GUID(target_guid))
10771 return;
10773 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
10774 if(!target)
10775 return;
10777 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
10779 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
10780 target->RemoveAura(iter);
10781 else
10782 ++iter;