[7297] Fixed profession spells sorting in trainer spell list at client.
[getmangos.git] / src / game / Unit.cpp
blobc572ec9a4f923608b99bb23098b1fa175d69f79f
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;
106 m_Visibility = VISIBILITY_ON;
108 m_detectInvisibilityMask = 0;
109 m_invisibilityMask = 0;
110 m_transform = 0;
111 m_ShapeShiftFormSpellId = 0;
112 m_canModifyStats = false;
114 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
115 m_spellImmune[i].clear();
116 for (int i = 0; i < UNIT_MOD_END; ++i)
118 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
119 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
120 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
121 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
123 // implement 50% base damage from offhand
124 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
126 for (int i = 0; i < MAX_ATTACK; ++i)
128 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
129 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
131 for (int i = 0; i < MAX_STATS; ++i)
132 m_createStats[i] = 0.0f;
134 m_attacking = NULL;
135 m_modMeleeHitChance = 0.0f;
136 m_modRangedHitChance = 0.0f;
137 m_modSpellHitChance = 0.0f;
138 m_baseSpellCritChance = 5;
140 m_CombatTimer = 0;
141 m_lastManaUse = 0;
143 //m_victimThreat = 0.0f;
144 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
145 m_threatModifier[i] = 1.0f;
146 m_isSorted = true;
147 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
148 m_speed_rate[i] = 1.0f;
150 m_removedAuras = 0;
151 m_charmInfo = NULL;
152 m_unit_movement_flags = 0;
154 // remove aurastates allowing special moves
155 for(int i=0; i < MAX_REACTIVE; ++i)
156 m_reactiveTimer[i] = 0;
159 Unit::~Unit()
161 // set current spells as deletable
162 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
164 if (m_currentSpells[i])
166 m_currentSpells[i]->SetReferencedFromCurrent(false);
167 m_currentSpells[i] = NULL;
171 RemoveAllGameObjects();
172 RemoveAllDynObjects();
174 if(m_charmInfo) delete m_charmInfo;
177 void Unit::Update( uint32 p_time )
179 /*if(p_time > m_AurasCheck)
181 m_AurasCheck = 2000;
182 _UpdateAura();
183 }else
184 m_AurasCheck -= p_time;*/
186 // WARNING! Order of execution here is important, do not change.
187 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
188 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
189 m_Events.Update( p_time );
190 _UpdateSpells( p_time );
192 // update combat timer only for players and pets
193 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
195 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
196 // targets without stopping half way there and running off.
197 // These flags are reset after target dies or another command is given.
198 if( m_HostilRefManager.isEmpty() )
200 // m_CombatTimer set at aura start and it will be freeze until aura removing
201 if ( m_CombatTimer <= p_time )
202 ClearInCombat();
203 else
204 m_CombatTimer -= p_time;
208 if(uint32 base_att = getAttackTimer(BASE_ATTACK))
210 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
213 // update abilities available only for fraction of time
214 UpdateReactives( p_time );
216 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
217 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
218 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
220 i_motionMaster.UpdateMotion(p_time);
223 bool Unit::haveOffhandWeapon() const
225 if(GetTypeId() == TYPEID_PLAYER)
226 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
227 else
228 return false;
231 void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
233 float x, y, z;
234 if(GetMotionMaster()->GetDestination(x, y, z))
235 SendMonsterMoveWithSpeed(x, y, z, GetUnitMovementFlags(), 0, player);
238 void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 MovementFlags, uint32 transitTime, Player* player)
240 if (!transitTime)
242 float dx = x - GetPositionX();
243 float dy = y - GetPositionY();
244 float dz = z - GetPositionZ();
246 float dist = ((dx*dx) + (dy*dy) + (dz*dz));
247 if(dist<0)
248 dist = 0;
249 else
250 dist = sqrt(dist);
252 double speed = GetSpeed((MovementFlags & MOVEMENTFLAG_WALK_MODE) ? MOVE_WALK : MOVE_RUN);
253 if(speed<=0)
254 speed = 2.5f;
255 speed *= 0.001f;
256 transitTime = static_cast<uint32>(dist / speed + 0.5);
258 //float orientation = (float)atan2((double)dy, (double)dx);
259 SendMonsterMove(x, y, z, 0, MovementFlags, transitTime, player);
262 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player)
264 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
265 data.append(GetPackGUID());
267 // Point A, starting location
268 data << GetPositionX() << GetPositionY() << GetPositionZ();
269 // unknown field - unrelated to orientation
270 // seems to increment about 1000 for every 1.7 seconds
271 // for now, we'll just use mstime
272 data << getMSTime();
274 data << uint8(type); // unknown
275 switch(type)
277 case 0: // normal packet
278 break;
279 case 1: // stop packet
280 SendMessageToSet( &data, true );
281 return;
282 case 2: // not used currently
283 data << float(0);
284 data << float(0);
285 data << float(0);
286 break;
287 case 3: // not used currently
288 data << uint64(0); // probably target guid
289 break;
290 case 4: // not used currently
291 data << float(0); // probably orientation
292 break;
295 //Movement Flags (0x0 = walk, 0x100 = run, 0x200 = fly/swim)
296 data << uint32(MovementFlags);
298 data << Time; // Time in between points
299 data << uint32(1); // 1 single waypoint
300 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
302 if(player)
303 player->GetSession()->SendPacket(&data);
304 else
305 SendMessageToSet( &data, true );
308 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, uint32 MovementFlags)
310 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
312 uint32 pathSize = end-start;
314 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+4+4+4+4+1+4+4+4+pathSize*4*3) );
315 data.append(GetPackGUID());
316 data << GetPositionX();
317 data << GetPositionY();
318 data << GetPositionZ();
320 // unknown field - unrelated to orientation
321 // seems to increment about 1000 for every 1.7 seconds
322 // for now, we'll just use mstime
323 data << getMSTime();
325 data << uint8( 0 );
326 data << uint32( MovementFlags );
327 data << uint32( traveltime );
328 data << uint32( pathSize );
329 data.append( (char*)path.GetNodes(start), pathSize * 4 * 3 );
331 //WPAssert( data.size() == 37 + pathnodes.Size( ) * 4 * 3 );
332 SendMessageToSet(&data, true);
335 void Unit::resetAttackTimer(WeaponAttackType type)
337 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
340 bool Unit::canReachWithAttack(Unit *pVictim) const
342 assert(pVictim);
343 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
344 if( reach <= 0.0f )
345 reach = 1.0f;
346 return IsWithinDistInMap(pVictim, reach);
349 void Unit::RemoveSpellsCausingAura(AuraType auraType)
351 if (auraType >= TOTAL_AURAS) return;
352 AuraList::iterator iter, next;
353 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
355 next = iter;
356 ++next;
358 if (*iter)
360 RemoveAurasDueToSpell((*iter)->GetId());
361 if (!m_modAuras[auraType].empty())
362 next = m_modAuras[auraType].begin();
363 else
364 return;
369 bool Unit::HasAuraType(AuraType auraType) const
371 return (!m_modAuras[auraType].empty());
374 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
375 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
377 if(!HasAuraType(auraType))
378 return;
380 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
381 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
382 float chance = float(damage) / max_dmg * 100.0f;
383 if (roll_chance_f(chance))
384 RemoveSpellsCausingAura(auraType);
387 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
389 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
390 return 0;
392 //You don't lose health from damage taken from another player while in a sanctuary
393 //You still see it in the combat log though
394 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
396 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
397 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
398 return 0;
401 // remove affects from victim (including from 0 damage and DoTs)
402 if(pVictim != this)
403 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
405 // remove affects from attacker at any non-DoT damage (including 0 damage)
406 if( damagetype != DOT)
408 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
409 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
411 if(pVictim != this)
412 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
414 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
415 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
418 //Script Event damage Deal
419 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
420 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
421 //Script Event damage taken
422 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
423 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
425 if(!damage)
427 // Rage from physical damage received .
428 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
429 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
431 return 0;
433 if (!spellProto || !IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR, spellProto->Id))
434 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
435 // root type spells do not dispel the root effect
436 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT, spellProto->Id)))
437 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
439 if(pVictim->GetTypeId() != TYPEID_PLAYER)
441 // no xp,health if type 8 /critters/
442 if ( pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
444 pVictim->setDeathState(JUST_DIED);
445 pVictim->SetHealth(0);
447 // allow loot only if has loot_id in creature_template
448 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
449 if(cInfo && cInfo->lootid)
450 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
452 // some critters required for quests
453 if(GetTypeId() == TYPEID_PLAYER)
454 ((Player*)this)->KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
456 return damage;
459 if(!pVictim->isInCombat() && ((Creature*)pVictim)->AI())
460 ((Creature*)pVictim)->AI()->AttackStart(this);
463 DEBUG_LOG("DealDamageStart");
465 uint32 health = pVictim->GetHealth();
466 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
468 // duel ends when player has 1 or less hp
469 bool duel_hasEnded = false;
470 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
472 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
473 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
474 damage = health-1;
476 duel_hasEnded = true;
478 //Get in CombatState
479 if(pVictim != this && damagetype != DOT)
481 SetInCombatWith(pVictim);
482 pVictim->SetInCombatWith(this);
484 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
485 SetContestedPvP(attackedPlayer);
488 // Rage from Damage made (only from direct weapon damage)
489 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
491 uint32 weaponSpeedHitFactor;
493 switch(cleanDamage->attackType)
495 case BASE_ATTACK:
497 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
498 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
499 else
500 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
502 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
504 break;
506 case OFF_ATTACK:
508 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
509 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
510 else
511 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
513 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
515 break;
517 case RANGED_ATTACK:
518 break;
522 if(pVictim->GetTypeId() == TYPEID_PLAYER && GetTypeId() == TYPEID_PLAYER)
524 if(((Player*)pVictim)->InBattleGround())
526 Player *killer = ((Player*)this);
527 if(killer != ((Player*)pVictim))
528 if(BattleGround *bg = killer->GetBattleGround())
529 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
533 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
534 ((Creature*)pVictim)->SetLootRecipient(this);
535 if (health <= damage)
537 DEBUG_LOG("DealDamage: victim just died");
539 // find player: owner of controlled `this` or `this` itself maybe
540 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
542 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
543 player = ((Creature*)pVictim)->GetLootRecipient();
544 // Reward player, his pets, and group/raid members
545 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
546 if(player && player!=pVictim)
548 player->RewardPlayerAndGroupAtKill(pVictim);
549 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
552 DEBUG_LOG("DealDamageAttackStop");
554 // stop combat
555 pVictim->CombatStop();
556 pVictim->getHostilRefManager().deleteReferences();
558 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
560 // if talent known but not triggered (check priest class for speedup check)
561 Aura* spiritOfRedemtionTalentReady = NULL;
562 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
563 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
565 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
566 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
568 if((*itr)->GetSpellProto()->SpellIconID==1654)
570 spiritOfRedemtionTalentReady = *itr;
571 break;
576 DEBUG_LOG("SET JUST_DIED");
577 if(!spiritOfRedemtionTalentReady)
578 pVictim->setDeathState(JUST_DIED);
580 DEBUG_LOG("DealDamageHealth1");
582 if(spiritOfRedemtionTalentReady)
584 // save value before aura remove
585 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
586 if(!ressSpellId)
587 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
589 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
590 pVictim->RemoveAllAurasOnDeath();
592 // restore for use at real death
593 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
595 // FORM_SPIRITOFREDEMPTION and related auras
596 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
598 else
599 pVictim->SetHealth(0);
601 // remember victim PvP death for corpse type and corpse reclaim delay
602 // at original death (not at SpiritOfRedemtionTalent timeout)
603 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
604 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
606 // Call KilledUnit for creatures
607 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
608 ((Creature*)this)->AI()->KilledUnit(pVictim);
610 // achievement stuff
611 if ( pVictim->GetTypeId() == TYPEID_PLAYER)
613 if(GetTypeId() == TYPEID_UNIT)
614 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
615 else if(GetTypeId() == TYPEID_PLAYER)
616 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1);
619 // 10% durability loss on death
620 // clean InHateListOf
621 if (pVictim->GetTypeId() == TYPEID_PLAYER)
623 // only if not player and not controlled by player pet. And not at BG
624 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
626 DEBUG_LOG("We are dead, loosing 10 percents durability");
627 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
628 // durability lost message
629 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
630 ((Player*)pVictim)->GetSession()->SendPacket(&data);
633 else // creature died
635 DEBUG_LOG("DealDamageNotPlayer");
636 Creature *cVictim = (Creature*)pVictim;
638 if(!cVictim->isPet())
640 cVictim->DeleteThreatList();
641 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
643 // Call creature just died function
644 if (cVictim->AI())
645 cVictim->AI()->JustDied(this);
647 // Dungeon specific stuff, only applies to players killing creatures
648 if(cVictim->GetInstanceId())
650 Map *m = cVictim->GetMap();
651 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
652 // TODO: do instance binding anyway if the charmer/owner is offline
654 if(m->IsDungeon() && creditedPlayer)
656 if(m->IsRaid() || m->IsHeroic())
658 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
659 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
661 else
663 // the reset time is set but not added to the scheduler
664 // until the players leave the instance
665 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
666 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
667 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
673 // last damage from non duel opponent or opponent controlled creature
674 if(duel_hasEnded)
676 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
677 Player *he = (Player*)pVictim;
679 assert(he->duel);
681 he->duel->opponent->CombatStopWithPets(true);
682 he->CombatStopWithPets(true);
684 he->DuelComplete(DUEL_INTERUPTED);
687 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
688 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
690 Player *killed = ((Player*)pVictim);
691 if(BattleGround *bg = killed->GetBattleGround())
692 if(player)
693 bg->HandleKillPlayer(killed, player);
694 //later we can add support for creature->player kills here i'm
695 //not sure, but i guess those kills also get counted in av
696 //else if(GetTypeId() == TYPEID_UNIT)
697 // bg->HandleKillPlayer(killed,(Creature*)this);
700 else // if (health <= damage)
702 DEBUG_LOG("DealDamageAlive");
704 pVictim->ModifyHealth(- (int32)damage);
706 if(damagetype != DOT)
708 if(getVictim())
710 // if have target and damage pVictim just call AI reaction
711 if(pVictim != getVictim() && pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
712 ((Creature*)pVictim)->AI()->AttackedBy(this);
714 else
716 // if not have main target then attack state with target (including AI call)
717 //start melee attacks only after melee hit
718 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
722 // polymorphed and other negative transformed cases
723 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
724 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
726 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
728 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
729 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
731 if (pVictim->GetTypeId() != TYPEID_PLAYER)
733 if(spellProto && IsDamageToThreatSpell(spellProto))
734 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
735 else
736 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
738 else // victim is a player
740 // Rage from damage received
741 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
743 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
744 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
747 // random durability for items (HIT TAKEN)
748 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
750 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
751 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
755 if(GetTypeId()==TYPEID_PLAYER)
757 // random durability for items (HIT DONE)
758 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
760 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
761 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
765 // TODO: Store auras by interrupt flag to speed this up.
766 AuraMap& vAuras = pVictim->GetAuras();
767 for (AuraMap::iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
769 const SpellEntry *se = i->second->GetSpellProto();
770 next = i; ++next;
771 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
772 continue;
773 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
775 bool remove = true;
776 if (se->procFlags & (1<<3))
778 if (!roll_chance_i(se->procChance))
779 remove = false;
781 if (remove)
783 pVictim->RemoveAurasDueToSpell(i->second->GetId());
784 // FIXME: this may cause the auras with proc chance to be rerolled several times
785 next = vAuras.begin();
790 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
792 if( damagetype != DOT )
794 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
796 // skip channeled spell (processed differently below)
797 if (i == CURRENT_CHANNELED_SPELL)
798 continue;
800 if(Spell* spell = pVictim->m_currentSpells[i])
801 if(spell->getState() == SPELL_STATE_PREPARING)
803 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
804 pVictim->InterruptSpell(i);
805 else
806 spell->Delayed();
811 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
813 if (spell->getState() == SPELL_STATE_CASTING)
815 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
816 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
818 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
819 spell->DelayedChannel();
821 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
823 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
824 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
827 else if (spell->getState() == SPELL_STATE_DELAYED)
828 // break channeled spell in delayed state on damage
830 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
831 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
836 // last damage from duel opponent
837 if(duel_hasEnded)
839 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
840 Player *he = (Player*)pVictim;
842 assert(he->duel);
844 he->SetHealth(1);
846 he->duel->opponent->CombatStopWithPets(true);
847 he->CombatStopWithPets(true);
849 he->CastSpell(he, 7267, true); // beg
850 he->DuelComplete(DUEL_WON);
854 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
856 return damage;
859 void Unit::CastStop(uint32 except_spellid)
861 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
862 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
863 InterruptSpell(i,false);
866 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
868 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
870 if(!spellInfo)
872 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
873 return;
876 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
879 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
881 if(!spellInfo)
883 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
884 return;
887 if (castItem)
888 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
890 if(!originalCaster && triggeredByAura)
891 originalCaster = triggeredByAura->GetCasterGUID();
893 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
895 SpellCastTargets targets;
896 targets.setUnitTarget( Victim );
897 spell->m_CastItem = castItem;
898 spell->prepare(&targets, triggeredByAura);
901 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
903 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
905 if(!spellInfo)
907 sLog.outError("CastCustomSpell: unknown spell id %i\n", spellId);
908 return;
911 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
914 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)
916 if(!spellInfo)
918 sLog.outError("CastCustomSpell: unknown spell");
919 return;
922 if (castItem)
923 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
925 if(!originalCaster && triggeredByAura)
926 originalCaster = triggeredByAura->GetCasterGUID();
928 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
930 if(bp0)
931 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
933 if(bp1)
934 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
936 if(bp2)
937 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
939 SpellCastTargets targets;
940 targets.setUnitTarget( Victim );
941 spell->m_CastItem = castItem;
942 spell->prepare(&targets, triggeredByAura);
945 // used for scripting
946 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
948 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
950 if(!spellInfo)
952 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()));
953 return;
956 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
959 // used for scripting
960 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
962 if(!spellInfo)
964 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
965 return;
968 if (castItem)
969 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
971 if(!originalCaster && triggeredByAura)
972 originalCaster = triggeredByAura->GetCasterGUID();
974 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
976 SpellCastTargets targets;
977 targets.setDestination(x, y, z);
978 spell->m_CastItem = castItem;
979 spell->prepare(&targets, triggeredByAura);
982 // Obsolete func need remove, here only for comotability vs another patches
983 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
985 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
986 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
987 CalculateSpellDamage(&damageInfo, damage, spellInfo);
988 SendSpellNonMeleeDamageLog(&damageInfo);
989 DealSpellDamage(&damageInfo, true);
990 return damageInfo.damage;
993 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
995 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
996 Unit *pVictim = damageInfo->target;
998 if (damage < 0)
999 return;
1001 if(!this || !pVictim)
1002 return;
1003 if(!this->isAlive() || !pVictim->isAlive())
1004 return;
1006 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1007 // Check spell crit chance
1008 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1009 bool blocked = false;
1010 // Per-school calc
1011 switch (spellInfo->DmgClass)
1013 // Melee and Ranged Spells
1014 case SPELL_DAMAGE_CLASS_RANGED:
1015 case SPELL_DAMAGE_CLASS_MELEE:
1017 // Physical Damage
1018 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1020 //Calculate armor mitigation
1021 damage = CalcArmorReducedDamage(pVictim, damage);
1022 // Get blocked status
1023 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1025 // Magical Damage
1026 else
1028 // Calculate damage bonus
1029 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1031 if (crit)
1033 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1035 // Calculate crit bonus
1036 uint32 crit_bonus = damage;
1037 // Apply crit_damage bonus for melee spells
1038 if(Player* modOwner = GetSpellModOwner())
1039 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1040 damage += crit_bonus;
1042 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1043 int32 critPctDamageMod=0;
1044 if(attackType == RANGED_ATTACK)
1045 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1046 else
1048 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1049 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1051 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1052 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1054 if (critPctDamageMod!=0)
1055 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1057 // Resilience - reduce crit damage
1058 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1059 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1061 // Spell weapon based damage CAN BE crit & blocked at same time
1062 if (blocked)
1064 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1065 if (damage < damageInfo->blocked)
1066 damageInfo->blocked = damage;
1067 damage-=damageInfo->blocked;
1070 break;
1071 // Magical Attacks
1072 case SPELL_DAMAGE_CLASS_NONE:
1073 case SPELL_DAMAGE_CLASS_MAGIC:
1075 // Calculate damage bonus
1076 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1077 // If crit add critical bonus
1078 if (crit)
1080 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1081 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1082 // Resilience - reduce crit damage
1083 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1084 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1087 break;
1090 // Calculate absorb resist
1091 if(damage > 0)
1093 // lookup absorb/resist ignore auras on caster for spell
1094 bool ignore = false;
1095 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1096 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1097 if ((*i)->isAffectedOnSpell(spellInfo))
1099 ignore = true;
1100 break;
1103 if (!ignore)
1105 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1106 damage-= damageInfo->absorb + damageInfo->resist;
1109 else
1110 damage = 0;
1111 damageInfo->damage = damage;
1114 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1116 if (damageInfo==0)
1117 return;
1119 Unit *pVictim = damageInfo->target;
1121 if(!this || !pVictim)
1122 return;
1124 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1125 return;
1127 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1128 if (spellProto == NULL)
1130 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1131 return;
1134 //You don't lose health from damage taken from another player while in a sanctuary
1135 //You still see it in the combat log though
1136 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1138 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1139 if(area && area->flags & 0x800) //sanctuary
1140 return;
1143 // Call default DealDamage
1144 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1145 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1148 //TODO for melee need create structure as in
1149 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1151 damageInfo->attacker = this;
1152 damageInfo->target = pVictim;
1153 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1154 damageInfo->attackType = attackType;
1155 damageInfo->damage = 0;
1156 damageInfo->cleanDamage = 0;
1157 damageInfo->absorb = 0;
1158 damageInfo->resist = 0;
1159 damageInfo->blocked_amount = 0;
1161 damageInfo->TargetState = 0;
1162 damageInfo->HitInfo = 0;
1163 damageInfo->procAttacker = PROC_FLAG_NONE;
1164 damageInfo->procVictim = PROC_FLAG_NONE;
1165 damageInfo->procEx = PROC_EX_NONE;
1166 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1168 if(!this || !pVictim)
1169 return;
1170 if(!this->isAlive() || !pVictim->isAlive())
1171 return;
1173 // Select HitInfo/procAttacker/procVictim flag based on attack type
1174 switch (attackType)
1176 case BASE_ATTACK:
1177 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1178 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1179 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1180 break;
1181 case OFF_ATTACK:
1182 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1183 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1184 damageInfo->HitInfo = HITINFO_LEFTSWING;
1185 break;
1186 case RANGED_ATTACK:
1187 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1188 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1189 damageInfo->HitInfo = 0x08;// test
1190 break;
1191 default:
1192 break;
1195 // Physical Immune check
1196 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1198 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1199 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1201 damageInfo->procEx |=PROC_EX_IMMUNE;
1202 damageInfo->damage = 0;
1203 damageInfo->cleanDamage = 0;
1204 return;
1206 damage += CalculateDamage (damageInfo->attackType, false);
1207 // Add melee damage bonus
1208 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1209 // Calculate armor reduction
1210 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1211 damageInfo->cleanDamage += damage - damageInfo->damage;
1213 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1215 // Disable parry or dodge for ranged attack
1216 if(damageInfo->attackType == RANGED_ATTACK)
1218 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1219 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1222 switch(damageInfo->hitOutCome)
1224 case MELEE_HIT_EVADE:
1226 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1227 damageInfo->TargetState = VICTIMSTATE_EVADES;
1229 damageInfo->procEx|=PROC_EX_EVADE;
1230 damageInfo->damage = 0;
1231 damageInfo->cleanDamage = 0;
1232 return;
1234 case MELEE_HIT_MISS:
1236 damageInfo->HitInfo |= HITINFO_MISS;
1237 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1239 damageInfo->procEx|=PROC_EX_MISS;
1240 damageInfo->damage = 0;
1241 damageInfo->cleanDamage = 0;
1242 break;
1244 case MELEE_HIT_NORMAL:
1245 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1246 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1247 break;
1248 case MELEE_HIT_CRIT:
1250 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1251 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1253 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1254 // Crit bonus calc
1255 damageInfo->damage += damageInfo->damage;
1256 int32 mod=0;
1257 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1258 if(damageInfo->attackType == RANGED_ATTACK)
1259 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1260 else
1262 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1263 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1266 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1268 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1269 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1270 if (mod!=0)
1271 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1273 // Resilience - reduce crit damage
1274 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1276 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1277 damageInfo->damage -= resilienceReduction;
1278 damageInfo->cleanDamage += resilienceReduction;
1280 break;
1282 case MELEE_HIT_PARRY:
1283 damageInfo->TargetState = VICTIMSTATE_PARRY;
1284 damageInfo->procEx|=PROC_EX_PARRY;
1285 damageInfo->cleanDamage += damageInfo->damage;
1286 damageInfo->damage = 0;
1287 break;
1289 case MELEE_HIT_DODGE:
1290 damageInfo->TargetState = VICTIMSTATE_DODGE;
1291 damageInfo->procEx|=PROC_EX_DODGE;
1292 damageInfo->cleanDamage += damageInfo->damage;
1293 damageInfo->damage = 0;
1294 break;
1295 case MELEE_HIT_BLOCK:
1297 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1298 damageInfo->HitInfo |= HITINFO_BLOCK;
1299 damageInfo->procEx|=PROC_EX_BLOCK;
1300 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1301 if (damageInfo->blocked_amount >= damageInfo->damage)
1303 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1304 damageInfo->blocked_amount = damageInfo->damage;
1306 damageInfo->damage -= damageInfo->blocked_amount;
1307 damageInfo->cleanDamage += damageInfo->blocked_amount;
1308 break;
1310 case MELEE_HIT_GLANCING:
1312 damageInfo->HitInfo |= HITINFO_GLANCING;
1313 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1314 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1315 float reducePercent = 1.0f; //damage factor
1316 // calculate base values and mods
1317 float baseLowEnd = 1.3;
1318 float baseHighEnd = 1.2;
1319 switch(getClass()) // lowering base values for casters
1321 case CLASS_SHAMAN:
1322 case CLASS_PRIEST:
1323 case CLASS_MAGE:
1324 case CLASS_WARLOCK:
1325 case CLASS_DRUID:
1326 baseLowEnd -= 0.7;
1327 baseHighEnd -= 0.3;
1328 break;
1331 float maxLowEnd = 0.6;
1332 switch(getClass()) // upper for melee classes
1334 case CLASS_WARRIOR:
1335 case CLASS_ROGUE:
1336 maxLowEnd = 0.91; //If the attacker is a melee class then instead the lower value of 0.91
1339 // calculate values
1340 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1341 float lowEnd = baseLowEnd - ( 0.05f * diff );
1342 float highEnd = baseHighEnd - ( 0.03f * diff );
1344 // apply max/min bounds
1345 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1346 lowEnd = 0.01f;
1347 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1348 lowEnd = maxLowEnd;
1350 if ( highEnd < 0.2f ) //high end limits
1351 highEnd = 0.2f;
1352 if ( highEnd > 0.99f )
1353 highEnd = 0.99f;
1355 if(lowEnd > highEnd) // prevent negative range size
1356 lowEnd = highEnd;
1358 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1360 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1361 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1362 break;
1364 case MELEE_HIT_CRUSHING:
1366 damageInfo->HitInfo |= HITINFO_CRUSHING;
1367 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1368 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1369 // 150% normal damage
1370 damageInfo->damage += (damageInfo->damage / 2);
1371 break;
1373 default:
1375 break;
1378 // Calculate absorb resist
1379 if(int32(damageInfo->damage) > 0)
1381 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1382 // Calculate absorb & resists
1383 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1384 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1385 if (damageInfo->absorb)
1387 damageInfo->HitInfo|=HITINFO_ABSORB;
1388 damageInfo->procEx|=PROC_EX_ABSORB;
1390 if (damageInfo->resist)
1391 damageInfo->HitInfo|=HITINFO_RESIST;
1394 else // Umpossible get negative result but....
1395 damageInfo->damage = 0;
1398 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1400 if (damageInfo==0) return;
1401 Unit *pVictim = damageInfo->target;
1403 if(!this || !pVictim)
1404 return;
1406 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1407 return;
1409 //You don't lose health from damage taken from another player while in a sanctuary
1410 //You still see it in the combat log though
1411 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1413 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1414 if(area && area->flags & 0x800) //sanctuary
1415 return;
1418 // Hmmmm dont like this emotes cloent must by self do all animations
1419 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1420 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1421 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1422 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1424 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1426 // Get attack timers
1427 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1428 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1429 // Reduce attack time
1430 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1432 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20;
1433 float percent60 = 3 * percent20;
1434 if(offtime > percent20 && offtime <= percent60)
1436 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1438 else if(offtime > percent60)
1440 offtime -= 2 * percent20;
1441 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1444 else
1446 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1447 float percent60 = 3 * percent20;
1448 if(basetime > percent20 && basetime <= percent60)
1450 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1452 else if(basetime > percent60)
1454 basetime -= 2 * percent20;
1455 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1460 // Call default DealDamage
1461 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1462 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1464 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1465 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1466 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1468 // -probability is between 0% and 40%
1469 // 20% base chance
1470 float Probability = 20;
1472 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1473 if( pVictim->getLevel() < 30 )
1474 Probability = 0.65f*pVictim->getLevel()+0.5;
1476 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1477 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1479 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1481 if(Probability > 40)
1482 Probability = 40;
1484 if(roll_chance_f(Probability))
1485 CastSpell(pVictim, 1604, true);
1488 // If not miss
1489 if (!(damageInfo->HitInfo & HITINFO_MISS))
1491 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1493 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1494 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1497 // victim's damage shield
1498 std::set<Aura*> alreadyDone;
1499 uint32 removedAuras = pVictim->m_removedAuras;
1500 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1501 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1503 next++;
1504 if (alreadyDone.find(*i) == alreadyDone.end())
1506 alreadyDone.insert(*i);
1507 uint32 damage=(*i)->GetModifier()->m_amount;
1508 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1509 if(!spellProto)
1510 continue;
1511 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1512 //uint32 absorb;
1513 //uint32 resist;
1514 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1515 //damage-=absorb + resist;
1517 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1518 data << uint64(pVictim->GetGUID());
1519 data << uint64(GetGUID());
1520 data << uint32(spellProto->Id);
1521 data << uint32(damage); // Damage
1522 data << uint32(0); // Overkill
1523 data << uint32(spellProto->SchoolMask);
1524 pVictim->SendMessageToSet(&data, true );
1526 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1528 if (pVictim->m_removedAuras > removedAuras)
1530 removedAuras = pVictim->m_removedAuras;
1531 next = vDamageShields.begin();
1539 void Unit::HandleEmoteCommand(uint32 anim_id)
1541 WorldPacket data( SMSG_EMOTE, 12 );
1542 data << uint32(anim_id);
1543 data << uint64(GetGUID());
1544 SendMessageToSet(&data, true);
1547 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1549 uint32 newdamage = 0;
1550 float armor = pVictim->GetArmor();
1551 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1552 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1554 // Apply Player CR_ARMOR_PENETRATION rating
1555 if (GetTypeId()==TYPEID_PLAYER)
1556 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1558 if (armor < 0.0f) armor=0.0f;
1560 float levelModifier = getLevel();
1561 if ( levelModifier > 59 )
1562 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1564 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1565 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1567 if(tmpvalue < 0.0f)
1568 tmpvalue = 0.0f;
1569 if(tmpvalue > 0.75f)
1570 tmpvalue = 0.75f;
1571 newdamage = uint32(damage - (damage * tmpvalue));
1573 return (newdamage > 1) ? newdamage : 1;
1576 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1578 if(!pVictim || !pVictim->isAlive() || !damage)
1579 return;
1581 // Magic damage, check for resists
1582 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1584 // Get base victim resistance for school
1585 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1586 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1587 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1589 tmpvalue2 *= (float)(0.15f / getLevel());
1590 if (tmpvalue2 < 0.0f)
1591 tmpvalue2 = 0.0f;
1592 if (tmpvalue2 > 0.75f)
1593 tmpvalue2 = 0.75f;
1594 uint32 ran = urand(0, 100);
1595 uint32 faq[4] = {24,6,4,6};
1596 uint8 m = 0;
1597 float Binom = 0.0f;
1598 for (uint8 i = 0; i < 4; i++)
1600 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1601 if (ran > Binom )
1602 ++m;
1603 else
1604 break;
1606 if (damagetype == DOT && m == 4)
1607 *resist += uint32(damage - 1);
1608 else
1609 *resist += uint32(damage * m / 4);
1610 if(*resist > damage)
1611 *resist = damage;
1613 else
1614 *resist = 0;
1616 int32 RemainingDamage = damage - *resist;
1618 // Get unit state (need for some absorb check)
1619 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1620 // Reflect damage spells (not cast any damage spell in aura lookup)
1621 uint32 reflectSpell = 0;
1622 int32 reflectDamage = 0;
1623 // Need remove expired auras after
1624 bool existExpired = false;
1625 // absorb without mana cost
1626 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1627 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1629 Modifier* mod = (*i)->GetModifier();
1630 if (!(mod->m_miscvalue & schoolMask))
1631 continue;
1633 SpellEntry const* spellProto = (*i)->GetSpellProto();
1635 // Max Amount can be absorbed by this aura
1636 int32 currentAbsorb = mod->m_amount;
1638 // Found empty aura (umpossible but..)
1639 if (currentAbsorb <=0)
1641 existExpired = true;
1642 continue;
1644 // Handle custom absorb auras
1645 // TODO: try find better way
1646 switch(spellProto->SpellFamilyName)
1648 case SPELLFAMILY_GENERIC:
1650 // Astral Shift
1651 if (spellProto->SpellIconID == 3066)
1653 //reduces all damage taken while stun, fear or silence
1654 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1655 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1656 continue;
1658 // Nerves of Steel
1659 if (spellProto->SpellIconID == 2115)
1661 // while affected by Stun and Fear
1662 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1663 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1664 continue;
1666 // Spell Deflection
1667 if (spellProto->SpellIconID == 3006)
1669 // You have a chance equal to your Parry chance
1670 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1671 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1672 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1673 continue;
1675 // Reflective Shield (Lady Malande boss)
1676 if (spellProto->Id == 41475)
1678 if(RemainingDamage < currentAbsorb)
1679 reflectDamage = RemainingDamage / 2;
1680 else
1681 reflectDamage = currentAbsorb / 2;
1682 reflectSpell = 33619;
1683 break;
1685 if (spellProto->Id == 39228 || // Argussian Compass
1686 spellProto->Id == 60218) // Essence of Gossamer
1688 // Max absorb stored in 1 dummy effect
1689 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1690 currentAbsorb = spellProto->EffectBasePoints[1];
1691 break;
1693 break;
1695 case SPELLFAMILY_DRUID:
1697 // Primal Tenacity
1698 if (spellProto->SpellIconID == 2253)
1700 //reduces all damage taken while Stunned
1701 if (unitflag & UNIT_FLAG_STUNNED)
1702 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1703 continue;
1705 break;
1707 case SPELLFAMILY_ROGUE:
1709 // Cheat Death
1710 if(spellProto->SpellIconID == 2109)
1712 if (pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1713 pVictim->GetHealth() <= RemainingDamage && // Only if damage kill
1714 !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
1715 roll_chance_i(currentAbsorb)) // Only if roll
1717 pVictim->CastSpell(pVictim,31231,true);
1718 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1719 // with health > 10% lost health until health==10%, in other case no losses
1720 uint32 health10 = pVictim->GetMaxHealth()/10;
1721 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1723 continue;
1725 break;
1727 case SPELLFAMILY_PRIEST:
1729 // Reflective Shield
1730 if (spellProto->SpellFamilyFlags == 0x1)
1732 if (pVictim == this)
1733 break;
1734 Unit* caster = (*i)->GetCaster();
1735 if (!caster)
1736 break;
1737 int32 reflectDamage = 0;
1738 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1739 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1741 switch((*k)->GetModifier()->m_miscvalue)
1743 case 5065: // Rank 1
1744 case 5064: // Rank 2
1745 case 5063: // Rank 3
1747 if(RemainingDamage >= currentAbsorb)
1748 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1749 else
1750 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1751 reflectSpell = 33619;
1752 } break;
1753 default: break;
1756 break;
1758 break;
1760 case SPELLFAMILY_SHAMAN:
1762 // Astral Shift
1763 if (spellProto->SpellIconID == 3066)
1765 //reduces all damage taken while stun, fear or silence
1766 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1767 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1768 continue;
1770 break;
1772 case SPELLFAMILY_DEATHKNIGHT:
1774 // Shadow of Death
1775 if (spellProto->SpellIconID == 1958)
1777 // TODO: absorb only while transform
1778 continue;
1780 // Anti-Magic Shell (on self)
1781 if (spellProto->Id == 48707)
1783 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1784 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1785 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1786 int32 regen = absorbed * 2 / 10;
1787 pVictim->CastCustomSpell(pVictim, 49088, &regen, 0, 0, true, 0, *i);
1788 RemainingDamage -= absorbed;
1789 continue;
1791 // Anti-Magic Shell (on single party/raid member)
1792 if (spellProto->Id == 50462)
1794 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1795 continue;
1797 // Anti-Magic Zone
1798 if (spellProto->Id == 50461)
1800 Unit* caster = (*i)->GetCaster();
1801 if (!caster)
1802 continue;
1803 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1804 int32 canabsorb = caster->GetHealth();
1805 if (canabsorb < absorbed)
1806 absorbed = canabsorb;
1807 DealDamage(caster, absorbed, NULL, damagetype, schoolMask, 0, false);
1808 RemainingDamage -= absorbed;
1809 continue;
1811 break;
1813 default:
1814 break;
1817 // currentAbsorb - damage can be absorbed by shield
1818 // If need absorb less damage
1819 if (RemainingDamage < currentAbsorb)
1820 currentAbsorb = RemainingDamage;
1822 RemainingDamage -= currentAbsorb;
1824 // Reduce shield amount
1825 mod->m_amount-=currentAbsorb;
1826 // Need remove it later
1827 if (mod->m_amount<=0)
1828 existExpired = true;
1831 // Remove all expired absorb auras
1832 if (existExpired)
1834 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1836 if ((*i)->GetModifier()->m_amount<=0)
1838 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1839 i = vSchoolAbsorb.begin();
1841 else
1842 ++i;
1845 // Cast back reflect damage spell
1846 if (reflectSpell)
1847 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true);
1849 // absorb by mana cost
1850 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1851 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1853 next = i; ++next;
1855 // check damage school mask
1856 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1857 continue;
1859 int32 currentAbsorb;
1860 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1861 currentAbsorb = (*i)->GetModifier()->m_amount;
1862 else
1863 currentAbsorb = RemainingDamage;
1865 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1866 if(Player *modOwner = pVictim->GetSpellModOwner())
1867 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1869 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1870 if (currentAbsorb > maxAbsorb)
1871 currentAbsorb = maxAbsorb;
1873 (*i)->GetModifier()->m_amount -= currentAbsorb;
1874 if((*i)->GetModifier()->m_amount <= 0)
1876 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1877 next = vManaShield.begin();
1880 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1881 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1883 RemainingDamage -= currentAbsorb;
1886 // only split damage if not damaging yourself
1887 if(pVictim != this)
1889 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1890 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1892 next = i; ++next;
1894 // check damage school mask
1895 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1896 continue;
1898 // Damage can be splitted only if aura has an alive caster
1899 Unit *caster = (*i)->GetCaster();
1900 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1901 continue;
1903 int32 currentAbsorb;
1904 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1905 currentAbsorb = (*i)->GetModifier()->m_amount;
1906 else
1907 currentAbsorb = RemainingDamage;
1909 RemainingDamage -= currentAbsorb;
1911 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1913 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1914 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1917 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1918 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1920 next = i; ++next;
1922 // check damage school mask
1923 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1924 continue;
1926 // Damage can be splitted only if aura has an alive caster
1927 Unit *caster = (*i)->GetCaster();
1928 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1929 continue;
1931 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1933 RemainingDamage -= splitted;
1935 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1937 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1938 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1942 *absorb = damage - RemainingDamage - *resist;
1945 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1947 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1948 return;
1950 if (!pVictim->isAlive())
1951 return;
1953 if(IsNonMeleeSpellCasted(false))
1954 return;
1956 uint32 hitInfo;
1957 if (attType == BASE_ATTACK)
1958 hitInfo = HITINFO_NORMALSWING2;
1959 else if (attType == OFF_ATTACK)
1960 hitInfo = HITINFO_LEFTSWING;
1961 else
1962 return; // ignore ranged case
1964 uint32 extraAttacks = m_extraAttacks;
1966 // melee attack spell casted at main hand attack only
1967 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1969 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1971 // not recent extra attack only at any non extra attack (melee spell case)
1972 if(!extra && extraAttacks)
1974 while(m_extraAttacks)
1976 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1977 if(m_extraAttacks > 0)
1978 --m_extraAttacks;
1982 return;
1985 CalcDamageInfo damageInfo;
1986 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1987 // Send log damage message to client
1988 SendAttackStateUpdate(&damageInfo);
1989 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1990 DealMeleeDamage(&damageInfo,true);
1992 if (GetTypeId() == TYPEID_PLAYER)
1993 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1994 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1995 else
1996 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1997 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1999 // extra attack only at any non extra attack (normal case)
2000 if(!extra && extraAttacks)
2002 while(m_extraAttacks)
2004 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2005 if(m_extraAttacks > 0)
2006 --m_extraAttacks;
2011 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2013 // This is only wrapper
2015 // Miss chance based on melee
2016 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2018 // Critical hit chance
2019 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2021 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2022 float dodge_chance = pVictim->GetUnitDodgeChance();
2023 float block_chance = pVictim->GetUnitBlockChance();
2024 float parry_chance = pVictim->GetUnitParryChance();
2026 // Useful if want to specify crit & miss chances for melee, else it could be removed
2027 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2029 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2032 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2034 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2035 return MELEE_HIT_EVADE;
2037 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2038 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2040 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2041 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2043 // bonus from skills is 0.04%
2044 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2045 int32 sum = 0, tmp = 0;
2046 int32 roll = urand (0, 10000);
2048 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2049 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2050 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2052 tmp = miss_chance;
2054 if (tmp > 0 && roll < (sum += tmp ))
2056 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2057 return MELEE_HIT_MISS;
2060 // always crit against a sitting target (except 0 crit chance)
2061 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2063 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2064 return MELEE_HIT_CRIT;
2067 // Dodge chance
2069 // only players can't dodge if attacker is behind
2070 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2072 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2074 else
2076 // Reduce dodge chance by attacker expertise rating
2077 if (GetTypeId() == TYPEID_PLAYER)
2078 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2080 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2081 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2083 tmp = dodge_chance;
2084 if ( (tmp > 0) // check if unit _can_ dodge
2085 && ((tmp -= skillBonus) > 0)
2086 && roll < (sum += tmp))
2088 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2089 return MELEE_HIT_DODGE;
2093 // parry & block chances
2095 // check if attack comes from behind, nobody can parry or block if attacker is behind
2096 if (!pVictim->HasInArc(M_PI,this))
2098 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2100 else
2102 // Reduce parry chance by attacker expertise rating
2103 if (GetTypeId() == TYPEID_PLAYER)
2104 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2106 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2108 int32 tmp = int32(parry_chance);
2109 if ( (tmp > 0) // check if unit _can_ parry
2110 && ((tmp -= skillBonus) > 0)
2111 && (roll < (sum += tmp)))
2113 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
2114 return MELEE_HIT_PARRY;
2118 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2120 tmp = block_chance;
2121 if ( (tmp > 0) // check if unit _can_ block
2122 && ((tmp -= skillBonus) > 0)
2123 && (roll < (sum += tmp)))
2125 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2126 return MELEE_HIT_BLOCK;
2131 // Critical chance
2132 tmp = crit_chance;
2134 if (tmp > 0 && roll < (sum += tmp))
2136 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2137 return MELEE_HIT_CRIT;
2140 // 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)
2141 if( attType != RANGED_ATTACK &&
2142 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2143 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2144 getLevel() < pVictim->getLevelForTarget(this) )
2146 // cap possible value (with bonuses > max skill)
2147 int32 skill = attackerWeaponSkill;
2148 int32 maxskill = attackerMaxSkillValueForLevel;
2149 skill = (skill > maxskill) ? maxskill : skill;
2151 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2152 tmp = tmp > 4000 ? 4000 : tmp;
2153 if (roll < (sum += tmp))
2155 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2156 return MELEE_HIT_GLANCING;
2160 // mobs can score crushing blows if they're 4 or more levels above victim
2161 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2162 // can be from by creature (if can) or from controlled player that considered as creature
2163 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2164 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2165 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2167 // when their weapon skill is 15 or more above victim's defense skill
2168 tmp = victimDefenseSkill;
2169 int32 tmpmax = victimMaxSkillValueForLevel;
2170 // having defense above your maximum (from items, talents etc.) has no effect
2171 tmp = tmp > tmpmax ? tmpmax : tmp;
2172 // tmp = mob's level * 5 - player's current defense skill
2173 tmp = attackerMaxSkillValueForLevel - tmp;
2174 if(tmp >= 15)
2176 // add 2% chance per lacking skill point, min. is 15%
2177 tmp = tmp * 200 - 1500;
2178 if (roll < (sum += tmp))
2180 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2181 return MELEE_HIT_CRUSHING;
2186 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2187 return MELEE_HIT_NORMAL;
2190 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2192 float min_damage, max_damage;
2194 if (normalized && GetTypeId()==TYPEID_PLAYER)
2195 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2196 else
2198 switch (attType)
2200 case RANGED_ATTACK:
2201 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2202 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2203 break;
2204 case BASE_ATTACK:
2205 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2206 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2207 break;
2208 case OFF_ATTACK:
2209 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2210 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2211 break;
2212 // Just for good manner
2213 default:
2214 min_damage = 0.0f;
2215 max_damage = 0.0f;
2216 break;
2220 if (min_damage > max_damage)
2222 std::swap(min_damage,max_damage);
2225 if(max_damage == 0.0f)
2226 max_damage = 5.0f;
2228 return urand((uint32)min_damage, (uint32)max_damage);
2231 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2233 if(spellProto->spellLevel <= 0)
2234 return 1.0f;
2236 float LvlPenalty = 0.0f;
2238 if(spellProto->spellLevel < 20)
2239 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2240 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2241 if(LvlFactor > 1.0f)
2242 LvlFactor = 1.0f;
2244 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2247 void Unit::SendAttackStart(Unit* pVictim)
2249 WorldPacket data( SMSG_ATTACKSTART, 16 );
2250 data << uint64(GetGUID());
2251 data << uint64(pVictim->GetGUID());
2253 SendMessageToSet(&data, true);
2254 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2257 void Unit::SendAttackStop(Unit* victim)
2259 if(!victim)
2260 return;
2262 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2263 data.append(GetPackGUID());
2264 data.append(victim->GetPackGUID()); // can be 0x00...
2265 data << uint32(0); // can be 0x1
2266 SendMessageToSet(&data, true);
2267 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2269 /*if(victim->GetTypeId() == TYPEID_UNIT)
2270 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2273 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2275 if (pVictim->HasInArc(M_PI,this))
2277 /* Currently not exist spells with ignore block
2278 // Ignore combat result aura (parry/dodge check on prepare)
2279 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2280 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2282 if (!(*i)->isAffectedOnSpell(spellProto))
2283 continue;
2284 if ((*i)->GetModifier()->m_miscvalue == )
2285 return false;
2289 // Check creatures flags_extra for disable block
2290 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2291 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2292 return false;
2294 float blockChance = GetUnitBlockChance();
2295 blockChance += (GetWeaponSkillValue(attackType) - pVictim->GetMaxSkillValueForLevel() )*0.04;
2296 if (roll_chance_f(blockChance))
2297 return true;
2299 return false;
2302 // Melee based spells can be miss, parry or dodge on this step
2303 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2304 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2306 // Calculate hit chance (more correct for chance mod)
2307 int32 HitChance;
2309 // PvP - PvE melee chances
2310 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2311 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2312 if(leveldif < 3)
2313 HitChance = 95 - leveldif;
2314 else
2315 HitChance = 93 - (leveldif - 2) * lchance;
2317 // Hit chance depends from victim auras
2318 if(attType == RANGED_ATTACK)
2319 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2320 else
2321 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2323 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2324 if(Player *modOwner = GetSpellModOwner())
2325 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2327 // Miss = 100 - hit
2328 float miss_chance= 100.0f - HitChance;
2330 // Bonuses from attacker aura and ratings
2331 if (attType == RANGED_ATTACK)
2332 miss_chance -= m_modRangedHitChance;
2333 else
2334 miss_chance -= m_modMeleeHitChance;
2336 // bonus from skills is 0.04%
2337 miss_chance -= skillDiff * 0.04f;
2339 // Limit miss chance from 0 to 60%
2340 if (miss_chance < 0.0f)
2341 return 0.0f;
2342 if (miss_chance > 60.0f)
2343 return 60.0f;
2344 return miss_chance;
2347 // Melee based spells hit result calculations
2348 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2350 WeaponAttackType attType = BASE_ATTACK;
2352 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2353 attType = RANGED_ATTACK;
2355 // bonus from skills is 0.04% per skill Diff
2356 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2357 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2358 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2360 uint32 roll = urand (0, 10000);
2362 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2363 // Roll miss
2364 uint32 tmp = missChance;
2365 if (roll < tmp)
2366 return SPELL_MISS_MISS;
2368 // Chance resist mechanic (select max value from every mechanic spell effect)
2369 int32 resist_mech = 0;
2370 // Get effects mechanic and chance
2371 for(int eff = 0; eff < 3; ++eff)
2373 int32 effect_mech = GetEffectMechanic(spell, eff);
2374 if (effect_mech)
2376 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2377 if (resist_mech < temp*100)
2378 resist_mech = temp*100;
2381 // Roll chance
2382 tmp += resist_mech;
2383 if (roll < tmp)
2384 return SPELL_MISS_RESIST;
2386 bool canDodge = true;
2387 bool canParry = true;
2389 // Same spells cannot be parry/dodge
2390 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2391 return SPELL_MISS_NONE;
2393 // Ranged attack cannot be parry/dodge only deflect
2394 if (attType == RANGED_ATTACK)
2396 // only if in front
2397 if (pVictim->HasInArc(M_PI,this))
2399 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2400 tmp+=deflect_chance;
2401 if (roll < tmp)
2402 return SPELL_MISS_DEFLECT;
2404 return SPELL_MISS_NONE;
2407 // Check for attack from behind
2408 if (!pVictim->HasInArc(M_PI,this))
2410 // Can`t dodge from behind in PvP (but its possible in PvE)
2411 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2412 canDodge = false;
2413 // Can`t parry
2414 canParry = false;
2416 // Check creatures flags_extra for disable parry
2417 if(pVictim->GetTypeId()==TYPEID_UNIT)
2419 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2420 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2421 canParry = false;
2423 // Ignore combat result aura
2424 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2425 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2427 if (!(*i)->isAffectedOnSpell(spell))
2428 continue;
2429 switch((*i)->GetModifier()->m_miscvalue)
2431 case MELEE_HIT_DODGE: canDodge = false; break;
2432 case MELEE_HIT_BLOCK: break; // Block check in hit step
2433 case MELEE_HIT_PARRY: canParry = false; break;
2434 default:
2435 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2436 break;
2440 if (canDodge)
2442 // Roll dodge
2443 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2444 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2445 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2446 // Reduce dodge chance by attacker expertise rating
2447 if (GetTypeId() == TYPEID_PLAYER)
2448 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2449 if (dodgeChance < 0)
2450 dodgeChance = 0;
2452 tmp += dodgeChance;
2453 if (roll < tmp)
2454 return SPELL_MISS_DODGE;
2457 if (canParry)
2459 // Roll parry
2460 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2461 // Reduce parry chance by attacker expertise rating
2462 if (GetTypeId() == TYPEID_PLAYER)
2463 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2464 if (parryChance < 0)
2465 parryChance = 0;
2467 tmp += parryChance;
2468 if (roll < tmp)
2469 return SPELL_MISS_PARRY;
2472 return SPELL_MISS_NONE;
2475 // TODO need use unit spell resistances in calculations
2476 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2478 // Can`t miss on dead target (on skinning for example)
2479 if (!pVictim->isAlive())
2480 return SPELL_MISS_NONE;
2482 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2483 // PvP - PvE spell misschances per leveldif > 2
2484 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2485 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2487 // Base hit chance from attacker and victim levels
2488 int32 modHitChance;
2489 if(leveldif < 3)
2490 modHitChance = 96 - leveldif;
2491 else
2492 modHitChance = 94 - (leveldif - 2) * lchance;
2494 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2495 if(Player *modOwner = GetSpellModOwner())
2496 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2497 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2498 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2499 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2500 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2501 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2502 if (IsAreaOfEffectSpell(spell))
2503 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2504 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2505 if (IsDispelSpell(spell))
2506 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2507 // Chance resist mechanic (select max value from every mechanic spell effect)
2508 int32 resist_mech = 0;
2509 // Get effects mechanic and chance
2510 for(int eff = 0; eff < 3; ++eff)
2512 int32 effect_mech = GetEffectMechanic(spell, eff);
2513 if (effect_mech)
2515 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2516 if (resist_mech < temp)
2517 resist_mech = temp;
2520 // Apply mod
2521 modHitChance-=resist_mech;
2523 // Chance resist debuff
2524 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2526 int32 HitChance = modHitChance * 100;
2527 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2528 HitChance += int32(m_modSpellHitChance*100.0f);
2530 // Decrease hit chance from victim rating bonus
2531 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2532 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2534 if (HitChance < 100) HitChance = 100;
2535 if (HitChance > 9900) HitChance = 9900;
2537 int32 tmp = 10000 - HitChance;
2539 uint32 rand = urand(0,10000);
2541 if (rand < tmp)
2542 return SPELL_MISS_RESIST;
2544 // cast by caster in front of victim
2545 if (pVictim->HasInArc(M_PI,this))
2547 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2548 tmp+=deflect_chance;
2549 if (rand < tmp)
2550 return SPELL_MISS_DEFLECT;
2553 return SPELL_MISS_NONE;
2556 // Calculate spell hit result can be:
2557 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2558 // For melee based spells:
2559 // Miss
2560 // Dodge
2561 // Parry
2562 // For spells
2563 // Resist
2564 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2566 // Return evade for units in evade mode
2567 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2568 return SPELL_MISS_EVADE;
2570 // Check for immune
2571 if (pVictim->IsImmunedToSpell(spell))
2572 return SPELL_MISS_IMMUNE;
2574 // All positive spells can`t miss
2575 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2576 if (IsPositiveSpell(spell->Id))
2577 return SPELL_MISS_NONE;
2579 // Check for immune
2580 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2581 return SPELL_MISS_IMMUNE;
2583 // Try victim reflect spell
2584 if (CanReflect)
2586 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2587 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2588 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2589 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2590 reflectchance += (*i)->GetModifier()->m_amount;
2591 if (reflectchance > 0 && roll_chance_i(reflectchance))
2593 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2594 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2595 return SPELL_MISS_REFLECT;
2599 switch (spell->DmgClass)
2601 case SPELL_DAMAGE_CLASS_RANGED:
2602 case SPELL_DAMAGE_CLASS_MELEE:
2603 return MeleeSpellHitResult(pVictim, spell);
2604 case SPELL_DAMAGE_CLASS_NONE:
2605 case SPELL_DAMAGE_CLASS_MAGIC:
2606 return MagicSpellHitResult(pVictim, spell);
2608 return SPELL_MISS_NONE;
2611 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2613 if(!pVictim)
2614 return 0.0f;
2616 // Base misschance 5%
2617 float misschance = 5.0f;
2619 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2620 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2622 bool isNormal = false;
2623 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2625 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2627 isNormal = true;
2628 break;
2631 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2633 misschance = 5.0f;
2635 else
2637 misschance = 24.0f;
2641 // PvP : PvE melee misschances per leveldif > 2
2642 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2644 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2645 if(leveldif < 0)
2646 leveldif = 0;
2648 // Hit chance from attacker based on ratings and auras
2649 float m_modHitChance;
2650 if (attType == RANGED_ATTACK)
2651 m_modHitChance = m_modRangedHitChance;
2652 else
2653 m_modHitChance = m_modMeleeHitChance;
2655 if(leveldif < 3)
2656 misschance += (leveldif - m_modHitChance);
2657 else
2658 misschance += ((leveldif - 2) * chance - m_modHitChance);
2660 // Hit chance for victim based on ratings
2661 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2663 if (attType == RANGED_ATTACK)
2664 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2665 else
2666 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2669 // Modify miss chance by victim auras
2670 if(attType == RANGED_ATTACK)
2671 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2672 else
2673 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2675 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2676 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2677 misschance -= skillBonus * 0.04f;
2679 // Limit miss chance from 0 to 60%
2680 if ( misschance < 0.0f)
2681 return 0.0f;
2682 if ( misschance > 60.0f)
2683 return 60.0f;
2685 return misschance;
2688 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2690 if(GetTypeId() == TYPEID_PLAYER)
2692 // in PvP use full skill instead current skill value
2693 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2694 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2695 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2696 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2697 return value;
2699 else
2700 return GetUnitMeleeSkill(target);
2703 float Unit::GetUnitDodgeChance() const
2705 if(hasUnitState(UNIT_STAT_STUNNED))
2706 return 0.0f;
2707 if( GetTypeId() == TYPEID_PLAYER )
2708 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2709 else
2711 if(((Creature const*)this)->isTotem())
2712 return 0.0f;
2713 else
2715 float dodge = 5.0f;
2716 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2717 return dodge > 0.0f ? dodge : 0.0f;
2722 float Unit::GetUnitParryChance() const
2724 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2725 return 0.0f;
2727 float chance = 0.0f;
2729 if(GetTypeId() == TYPEID_PLAYER)
2731 Player const* player = (Player const*)this;
2732 if(player->CanParry() )
2734 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2735 if(!tmpitem)
2736 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2738 if(tmpitem)
2739 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2742 else if(GetTypeId() == TYPEID_UNIT)
2744 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2746 chance = 5.0f;
2747 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2751 return chance > 0.0f ? chance : 0.0f;
2754 float Unit::GetUnitBlockChance() const
2756 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2757 return 0.0f;
2759 if(GetTypeId() == TYPEID_PLAYER)
2761 Player const* player = (Player const*)this;
2762 if(player->CanBlock() )
2764 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2765 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2766 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2768 // is player but has no block ability or no not broken shield equipped
2769 return 0.0f;
2771 else
2773 if(((Creature const*)this)->isTotem())
2774 return 0.0f;
2775 else
2777 float block = 5.0f;
2778 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2779 return block > 0.0f ? block : 0.0f;
2784 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2786 float crit;
2788 if(GetTypeId() == TYPEID_PLAYER)
2790 switch(attackType)
2792 case BASE_ATTACK:
2793 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2794 break;
2795 case OFF_ATTACK:
2796 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2797 break;
2798 case RANGED_ATTACK:
2799 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2800 break;
2801 // Just for good manner
2802 default:
2803 crit = 0.0f;
2804 break;
2807 else
2809 crit = 5.0f;
2810 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2813 // flat aura mods
2814 if(attackType == RANGED_ATTACK)
2815 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2816 else
2817 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2819 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2821 // reduce crit chance from Rating for players
2822 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2824 if (attackType==RANGED_ATTACK)
2825 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2826 else
2827 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2830 // Apply crit chance from defence skill
2831 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2833 if (crit < 0.0f)
2834 crit = 0.0f;
2835 return crit;
2838 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2840 uint32 value = 0;
2841 if(GetTypeId() == TYPEID_PLAYER)
2843 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2845 // feral or unarmed skill only for base attack
2846 if(attType != BASE_ATTACK && !item )
2847 return 0;
2849 if(((Player*)this)->IsInFeralForm())
2850 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2852 // weapon skill or (unarmed for base attack)
2853 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2855 // in PvP use full skill instead current skill value
2856 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2857 ? ((Player*)this)->GetMaxSkillValue(skill)
2858 : ((Player*)this)->GetSkillValue(skill);
2859 // Modify value from ratings
2860 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2861 switch (attType)
2863 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2864 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2865 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2868 else
2869 value = GetUnitMeleeSkill(target);
2870 return value;
2873 void Unit::_UpdateSpells( uint32 time )
2875 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2876 _UpdateAutoRepeatSpell();
2878 // remove finished spells from current pointers
2879 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2881 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2883 m_currentSpells[i]->SetReferencedFromCurrent(false);
2884 m_currentSpells[i] = NULL; // remove pointer
2888 // TODO: Find a better way to prevent crash when multiple auras are removed.
2889 m_removedAuras = 0;
2890 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2891 if ((*i).second)
2892 (*i).second->SetUpdated(false);
2894 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2896 next = i;
2897 ++next;
2898 if ((*i).second)
2900 // prevent double update
2901 if ((*i).second->IsUpdated())
2902 continue;
2903 (*i).second->SetUpdated(true);
2904 (*i).second->Update( time );
2905 // several auras can be deleted due to update
2906 if (m_removedAuras)
2908 if (m_Auras.empty()) break;
2909 next = m_Auras.begin();
2910 m_removedAuras = 0;
2915 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2917 if ((*i).second)
2919 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2921 RemoveAura(i);
2923 else
2925 ++i;
2928 else
2930 ++i;
2934 if(!m_gameObj.empty())
2936 std::list<GameObject*>::iterator ite1, dnext1;
2937 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2939 dnext1 = ite1;
2940 //(*i)->Update( difftime );
2941 if( !(*ite1)->isSpawned() )
2943 (*ite1)->SetOwnerGUID(0);
2944 (*ite1)->SetRespawnTime(0);
2945 (*ite1)->Delete();
2946 dnext1 = m_gameObj.erase(ite1);
2948 else
2949 ++dnext1;
2954 void Unit::_UpdateAutoRepeatSpell()
2956 //check "realtime" interrupts
2957 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2959 // cancel wand shoot
2960 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2961 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2962 m_AutoRepeatFirstCast = true;
2963 return;
2966 //apply delay
2967 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2968 setAttackTimer(RANGED_ATTACK,500);
2969 m_AutoRepeatFirstCast = false;
2971 //castroutine
2972 if (isAttackReady(RANGED_ATTACK))
2974 // Check if able to cast
2975 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CanCast(true))
2977 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2978 return;
2981 // we want to shoot
2982 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2983 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2985 // all went good, reset attack
2986 resetAttackTimer(RANGED_ATTACK);
2990 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2992 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2994 uint32 CSpellType = pSpell->GetCurrentContainer();
2996 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
2998 // break same type spell if it is not delayed
2999 InterruptSpell(CSpellType,false);
3001 // special breakage effects:
3002 switch (CSpellType)
3004 case CURRENT_GENERIC_SPELL:
3006 // generic spells always break channeled not delayed spells
3007 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3009 // autorepeat breaking
3010 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3012 // break autorepeat if not Auto Shot
3013 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3014 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3015 m_AutoRepeatFirstCast = true;
3017 } break;
3019 case CURRENT_CHANNELED_SPELL:
3021 // channel spells always break generic non-delayed and any channeled spells
3022 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3023 InterruptSpell(CURRENT_CHANNELED_SPELL);
3025 // it also does break autorepeat if not Auto Shot
3026 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3027 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3028 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3029 } break;
3031 case CURRENT_AUTOREPEAT_SPELL:
3033 // only Auto Shoot does not break anything
3034 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3036 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3037 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3038 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3040 // special action: set first cast flag
3041 m_AutoRepeatFirstCast = true;
3042 } break;
3044 default:
3046 // other spell types don't break anything now
3047 } break;
3050 // current spell (if it is still here) may be safely deleted now
3051 if (m_currentSpells[CSpellType])
3052 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3054 // set new current spell
3055 m_currentSpells[CSpellType] = pSpell;
3056 pSpell->SetReferencedFromCurrent(true);
3059 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
3061 assert(spellType < CURRENT_MAX_SPELL);
3063 if(m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3065 // send autorepeat cancel message for autorepeat spells
3066 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3068 if(GetTypeId()==TYPEID_PLAYER)
3069 ((Player*)this)->SendAutoRepeatCancel();
3072 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3073 m_currentSpells[spellType]->cancel();
3074 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3075 m_currentSpells[spellType] = NULL;
3079 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3081 // We don't do loop here to explicitly show that melee spell is excluded.
3082 // Maybe later some special spells will be excluded too.
3084 // generic spells are casted when they are not finished and not delayed
3085 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3086 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3087 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3088 return(true);
3090 // channeled spells may be delayed, but they are still considered casted
3091 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3092 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3093 return(true);
3095 // autorepeat spells may be finished or delayed, but they are still considered casted
3096 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3097 return(true);
3099 return(false);
3102 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3104 // generic spells are interrupted if they are not finished or delayed
3105 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3107 if ( (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3108 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3109 m_currentSpells[CURRENT_GENERIC_SPELL]->cancel();
3110 m_currentSpells[CURRENT_GENERIC_SPELL]->SetReferencedFromCurrent(false);
3111 m_currentSpells[CURRENT_GENERIC_SPELL] = NULL;
3114 // autorepeat spells are interrupted if they are not finished or delayed
3115 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3117 // send disable autorepeat packet in any case
3118 if(GetTypeId()==TYPEID_PLAYER)
3119 ((Player*)this)->SendAutoRepeatCancel();
3121 if ( (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3122 (withDelayed || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_DELAYED) )
3123 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->cancel();
3124 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->SetReferencedFromCurrent(false);
3125 m_currentSpells[CURRENT_AUTOREPEAT_SPELL] = NULL;
3128 // channeled spells are interrupted if they are not finished, even if they are delayed
3129 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3131 if (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)
3132 m_currentSpells[CURRENT_CHANNELED_SPELL]->cancel();
3133 m_currentSpells[CURRENT_CHANNELED_SPELL]->SetReferencedFromCurrent(false);
3134 m_currentSpells[CURRENT_CHANNELED_SPELL] = NULL;
3138 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3140 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
3141 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3142 return m_currentSpells[i];
3143 return NULL;
3146 bool Unit::isInFront(Unit const* target, float distance, float arc) const
3148 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
3151 void Unit::SetInFront(Unit const* target)
3153 SetOrientation(GetAngle(target));
3156 bool Unit::isInBack(Unit const* target, float distance, float arc) const
3158 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
3161 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3163 if(IsInWater())
3164 return c->canSwim();
3165 else
3166 return c->canWalk() || c->canFly();
3169 bool Unit::IsInWater() const
3171 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3174 bool Unit::IsUnderWater() const
3176 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3179 void Unit::DeMorph()
3181 SetDisplayId(GetNativeDisplayId());
3184 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3186 int32 modifier = 0;
3188 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3189 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3190 modifier += (*i)->GetModifier()->m_amount;
3192 return modifier;
3195 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3197 float multiplier = 1.0f;
3199 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3200 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3201 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3203 return multiplier;
3206 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3208 int32 modifier = 0;
3210 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3211 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3212 if ((*i)->GetModifier()->m_amount > modifier)
3213 modifier = (*i)->GetModifier()->m_amount;
3215 return modifier;
3218 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3220 int32 modifier = 0;
3222 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3223 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3224 if ((*i)->GetModifier()->m_amount < modifier)
3225 modifier = (*i)->GetModifier()->m_amount;
3227 return modifier;
3230 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3232 int32 modifier = 0;
3234 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3235 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3237 Modifier* mod = (*i)->GetModifier();
3238 if (mod->m_miscvalue & misc_mask)
3239 modifier += mod->m_amount;
3241 return modifier;
3244 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3246 float multiplier = 1.0f;
3248 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3249 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3251 Modifier* mod = (*i)->GetModifier();
3252 if (mod->m_miscvalue & misc_mask)
3253 multiplier *= (100.0f + mod->m_amount)/100.0f;
3255 return multiplier;
3258 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3260 int32 modifier = 0;
3262 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3263 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3265 Modifier* mod = (*i)->GetModifier();
3266 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3267 modifier = mod->m_amount;
3270 return modifier;
3273 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3275 int32 modifier = 0;
3277 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3278 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3280 Modifier* mod = (*i)->GetModifier();
3281 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3282 modifier = mod->m_amount;
3285 return modifier;
3288 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3290 int32 modifier = 0;
3292 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3293 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3295 Modifier* mod = (*i)->GetModifier();
3296 if (mod->m_miscvalue == misc_value)
3297 modifier += mod->m_amount;
3299 return modifier;
3302 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3304 float multiplier = 1.0f;
3306 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3307 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3309 Modifier* mod = (*i)->GetModifier();
3310 if (mod->m_miscvalue == misc_value)
3311 multiplier *= (100.0f + mod->m_amount)/100.0f;
3313 return multiplier;
3316 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3318 int32 modifier = 0;
3320 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3321 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3323 Modifier* mod = (*i)->GetModifier();
3324 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3325 modifier = mod->m_amount;
3328 return modifier;
3331 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3333 int32 modifier = 0;
3335 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3336 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3338 Modifier* mod = (*i)->GetModifier();
3339 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3340 modifier = mod->m_amount;
3343 return modifier;
3346 bool Unit::AddAura(Aura *Aur)
3348 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3349 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3350 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3352 delete Aur;
3353 return false;
3356 if(Aur->GetTarget() != this)
3358 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3359 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3360 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3361 delete Aur;
3362 return false;
3365 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3367 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3368 AuraMap::iterator i = m_Auras.find( spair );
3370 // take out same spell
3371 if (i != m_Auras.end())
3373 // passive and persistent auras can stack with themselves any number of times
3374 if (!Aur->IsPassive() && !Aur->IsPersistent())
3376 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3378 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3380 // Aura can stack on self -> Stack it;
3381 if(aurSpellInfo->StackAmount)
3383 i2->second->modStackAmount(1);
3384 delete Aur;
3385 return false;
3387 // can be only single (this check done at _each_ aura add
3388 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3389 break;
3392 bool stop = false;
3393 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3395 // DoT/HoT/etc
3396 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3397 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3398 case SPELL_AURA_PERIODIC_LEECH:
3399 case SPELL_AURA_PERIODIC_HEAL:
3400 case SPELL_AURA_OBS_MOD_HEALTH:
3401 case SPELL_AURA_PERIODIC_MANA_LEECH:
3402 case SPELL_AURA_PERIODIC_ENERGIZE:
3403 case SPELL_AURA_OBS_MOD_MANA:
3404 case SPELL_AURA_POWER_BURN_MANA:
3405 break;
3406 default: // not allow
3407 // can be only single (this check done at _each_ aura add
3408 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3409 stop = true;
3410 break;
3413 if(stop)
3414 break;
3419 // passive auras not stacable with other ranks
3420 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3422 if (!RemoveNoStackAurasDueToAura(Aur))
3424 delete Aur;
3425 return false; // couldn't remove conflicting aura with higher rank
3429 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3430 if (IsSingleTargetSpell(aurSpellInfo) && Aur->GetTarget())
3432 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3433 for(;;)
3435 Unit* caster = Aur->GetCaster();
3436 if(!caster) // caster deleted and not required adding scAura
3437 break;
3439 bool restart = false;
3440 AuraList& scAuras = caster->GetSingleCastAuras();
3441 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3443 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3444 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3446 if ((*itr)->IsInUse())
3448 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());
3449 continue;
3451 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3452 restart = true;
3453 break;
3457 if(!restart)
3459 // done
3460 scAuras.push_back(Aur);
3461 break;
3466 // add aura, register in lists and arrays
3467 Aur->_AddAura();
3468 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3469 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3471 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3474 Aur->ApplyModifier(true,true);
3475 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3476 return true;
3479 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3481 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3482 if(!spellInfo)
3483 return;
3484 AuraMap::iterator i,next;
3485 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3487 next = i;
3488 ++next;
3489 uint32 i_spellId = (*i).second->GetId();
3490 if((*i).second && i_spellId && i_spellId != spellId)
3492 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3494 RemoveAurasDueToSpell(i_spellId);
3496 if( m_Auras.empty() )
3497 break;
3498 else
3499 next = m_Auras.begin();
3505 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3507 if (!Aur)
3508 return false;
3510 SpellEntry const* spellProto = Aur->GetSpellProto();
3511 if (!spellProto)
3512 return false;
3514 uint32 spellId = Aur->GetId();
3515 uint32 effIndex = Aur->GetEffIndex();
3517 // passive spell special case (only non stackable with ranks)
3518 if(IsPassiveSpell(spellId))
3520 if(IsPassiveSpellStackableWithRanks(spellProto))
3521 return true;
3524 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3526 AuraMap::iterator i,next;
3527 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3529 next = i;
3530 ++next;
3531 if (!(*i).second) continue;
3533 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3535 if (!i_spellProto)
3536 continue;
3538 uint32 i_spellId = i_spellProto->Id;
3540 // early checks that spellId is passive non stackable spell
3541 if(IsPassiveSpell(i_spellId))
3543 // passive non-stackable spells not stackable only for same caster
3544 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3545 continue;
3547 // passive non-stackable spells not stackable only with another rank of same spell
3548 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3549 continue;
3552 uint32 i_effIndex = (*i).second->GetEffIndex();
3554 if(i_spellId == spellId) continue;
3556 bool is_triggered_by_spell = false;
3557 // prevent triggered aura of removing aura that triggered it
3558 for(int j = 0; j < 3; ++j)
3559 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3560 is_triggered_by_spell = true;
3562 if (is_triggered_by_spell)
3563 continue;
3565 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3567 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3569 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3571 // cannot remove higher rank
3572 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3573 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3574 return false;
3576 // Its a parent aura (create this aura in ApplyModifier)
3577 if ((*i).second->IsInUse())
3579 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());
3580 continue;
3582 RemoveAurasDueToSpell(i_spellId);
3584 if( m_Auras.empty() )
3585 break;
3586 else
3587 next = m_Auras.begin();
3589 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3591 // Its a parent aura (create this aura in ApplyModifier)
3592 if ((*i).second->IsInUse())
3594 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());
3595 continue;
3597 RemoveAurasDueToSpell(i_spellId);
3599 if( m_Auras.empty() )
3600 break;
3601 else
3602 next = m_Auras.begin();
3604 // Potions stack aura by aura (elixirs/flask already checked)
3605 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3607 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3609 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3610 return false; // cannot remove higher rank
3612 // Its a parent aura (create this aura in ApplyModifier)
3613 if ((*i).second->IsInUse())
3615 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());
3616 continue;
3618 RemoveAura(i);
3619 next = i;
3623 return true;
3626 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3628 spellEffectPair spair = spellEffectPair(spellId, effindex);
3629 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3631 if(iter->second!=except)
3633 RemoveAura(iter);
3634 iter = m_Auras.lower_bound(spair);
3636 else
3637 ++iter;
3641 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3643 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3645 Aura *aur = iter->second;
3646 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3647 RemoveAura(iter);
3648 else
3649 ++iter;
3653 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3655 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3657 Aura *aur = iter->second;
3658 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3660 // Custom dispel case
3661 // Unstable Affliction
3662 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3664 int32 damage = aur->GetModifier()->m_amount*9;
3665 uint64 caster_guid = aur->GetCasterGUID();
3667 // Remove aura
3668 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3670 // backfire damage and silence
3671 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3673 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3675 else
3676 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3678 else
3679 ++iter;
3683 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3685 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3687 Aura *aur = iter->second;
3688 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3690 int32 basePoints = aur->GetBasePoints();
3691 // construct the new aura for the attacker
3692 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer);
3693 if(!new_aur)
3694 continue;
3696 // set its duration and maximum duration
3697 // max duration 2 minutes (in msecs)
3698 int32 dur = aur->GetAuraDuration();
3699 const int32 max_dur = 2*MINUTE*1000;
3700 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3701 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3703 // add the new aura to stealer
3704 stealer->AddAura(new_aur);
3706 // Remove aura as dispel
3707 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3709 else
3710 ++iter;
3714 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3716 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3718 if (iter->second->GetId() == spellId)
3719 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3720 else
3721 ++iter;
3725 void Unit::RemoveAurasWithDispelType( DispelType type )
3727 // Create dispel mask by dispel type
3728 uint32 dispelMask = GetDispellMask(type);
3729 // Dispel all existing auras vs current dispel type
3730 AuraMap& auras = GetAuras();
3731 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3733 SpellEntry const* spell = itr->second->GetSpellProto();
3734 if( (1<<spell->Dispel) & dispelMask )
3736 // Dispel aura
3737 RemoveAurasDueToSpell(spell->Id);
3738 itr = auras.begin();
3740 else
3741 ++itr;
3745 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3747 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3748 if(iter != m_Auras.end())
3750 if (iter->second->modStackAmount(-1))
3751 RemoveAura(iter);
3755 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3757 for (int i=0; i<3; ++i)
3758 RemoveSingleAuraFromStack(spellId, i);
3761 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3763 for (int i = 0; i < 3; ++i)
3764 RemoveAura(spellId,i,except);
3767 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3769 for (int k=0; k < 3; ++k)
3771 spellEffectPair spair = spellEffectPair(spellId, k);
3772 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3774 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3776 RemoveAura(iter);
3777 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3779 else
3780 ++iter;
3785 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3787 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3789 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3790 RemoveAura(iter);
3791 else
3792 ++iter;
3796 void Unit::RemoveNotOwnSingleTargetAuras()
3798 // single target auras from other casters
3799 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3801 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3802 RemoveAura(iter);
3803 else
3804 ++iter;
3807 // single target auras at other targets
3808 AuraList& scAuras = GetSingleCastAuras();
3809 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3811 Aura* aura = *iter;
3812 if (aura->GetTarget()!=this)
3814 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3815 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3816 iter = scAuras.begin();
3818 else
3819 ++iter;
3824 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3826 Aura* Aur = i->second;
3827 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3829 Unit* caster = NULL;
3830 if (IsSingleTargetSpell(AurSpellInfo))
3832 caster = Aur->GetCaster();
3833 if(caster)
3835 AuraList& scAuras = caster->GetSingleCastAuras();
3836 scAuras.remove(Aur);
3838 else
3840 sLog.outError("Couldn't find the caster of the single target aura, may crash later!");
3841 assert(false);
3845 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3846 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3848 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3851 // Set remove mode
3852 Aur->SetRemoveMode(mode);
3853 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3854 // remove aura from list before to prevent deleting it before
3855 m_Auras.erase(i);
3856 ++m_removedAuras; // internal count used by unit update
3858 // Statue unsummoned at aura remove
3859 Totem* statue = NULL;
3860 bool caster_channeled = false;
3861 if(IsChanneledSpell(AurSpellInfo))
3863 if(!caster) // can be already located for IsSingleTargetSpell case
3864 caster = Aur->GetCaster();
3866 if(caster)
3868 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3869 statue = ((Totem*)caster);
3870 else
3871 caster_channeled = caster==this;
3875 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3876 Aur->ApplyModifier(false,true);
3877 Aur->_RemoveAura();
3878 delete Aur;
3880 if(caster_channeled)
3881 RemoveAurasAtChanneledTarget (AurSpellInfo);
3883 if(statue)
3884 statue->UnSummon();
3886 // only way correctly remove all auras from list
3887 if( m_Auras.empty() )
3888 i = m_Auras.end();
3889 else
3890 i = m_Auras.begin();
3893 void Unit::RemoveAllAuras()
3895 while (!m_Auras.empty())
3897 AuraMap::iterator iter = m_Auras.begin();
3898 RemoveAura(iter);
3902 void Unit::RemoveArenaAuras(bool onleave)
3904 // in join, remove positive buffs, on end, remove negative
3905 // used to remove positive visible auras in arenas
3906 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3908 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3909 && !iter->second->IsPassive() // don't remove passive auras
3910 && (!(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)
3911 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3912 RemoveAura(iter);
3913 else
3914 ++iter;
3918 void Unit::RemoveAllAurasOnDeath()
3920 // used just after dieing to remove all visible auras
3921 // and disable the mods for the passive ones
3922 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3924 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3925 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3926 else
3927 ++iter;
3931 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3933 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3934 if (iter != m_Auras.end())
3936 if (iter->second->GetAuraDuration() < delaytime)
3937 iter->second->SetAuraDuration(0);
3938 else
3939 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3940 iter->second->SendAuraUpdate(false);
3941 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3945 void Unit::_RemoveAllAuraMods()
3947 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3949 (*i).second->ApplyModifier(false);
3953 void Unit::_ApplyAllAuraMods()
3955 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3957 (*i).second->ApplyModifier(true);
3961 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3963 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3964 if (iter != m_Auras.end())
3965 return iter->second;
3966 return NULL;
3969 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
3971 AuraList const& auras = GetAurasByType(type);
3972 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
3974 SpellEntry const *spell = (*i)->GetSpellProto();
3975 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
3977 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
3978 continue;
3979 return (*i);
3982 return NULL;
3985 bool Unit::HasAura(uint32 spellId) const
3987 for (int i = 0; i < 3 ; ++i)
3989 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3990 if (iter != m_Auras.end())
3991 return true;
3993 return false;
3996 void Unit::AddDynObject(DynamicObject* dynObj)
3998 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4001 void Unit::RemoveDynObject(uint32 spellid)
4003 if(m_dynObjGUIDs.empty())
4004 return;
4005 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4007 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
4008 if(!dynObj)
4010 i = m_dynObjGUIDs.erase(i);
4012 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4014 dynObj->Delete();
4015 i = m_dynObjGUIDs.erase(i);
4017 else
4018 ++i;
4022 void Unit::RemoveAllDynObjects()
4024 while(!m_dynObjGUIDs.empty())
4026 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
4027 if(dynObj)
4028 dynObj->Delete();
4029 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4033 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4035 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4037 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
4038 if(!dynObj)
4040 i = m_dynObjGUIDs.erase(i);
4041 continue;
4044 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4045 return dynObj;
4046 ++i;
4048 return NULL;
4051 DynamicObject * Unit::GetDynObject(uint32 spellId)
4053 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4055 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
4056 if(!dynObj)
4058 i = m_dynObjGUIDs.erase(i);
4059 continue;
4062 if (dynObj->GetSpellId() == spellId)
4063 return dynObj;
4064 ++i;
4066 return NULL;
4069 void Unit::AddGameObject(GameObject* gameObj)
4071 assert(gameObj && gameObj->GetOwnerGUID()==0);
4072 m_gameObj.push_back(gameObj);
4073 gameObj->SetOwnerGUID(GetGUID());
4076 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4078 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4080 // GO created by some spell
4081 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4083 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4084 // Need activate spell use for owner
4085 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4086 ((Player*)this)->SendCooldownEvent(createBySpell);
4088 gameObj->SetOwnerGUID(0);
4089 m_gameObj.remove(gameObj);
4090 if(del)
4092 gameObj->SetRespawnTime(0);
4093 gameObj->Delete();
4097 void Unit::RemoveGameObject(uint32 spellid, bool del)
4099 if(m_gameObj.empty())
4100 return;
4101 std::list<GameObject*>::iterator i, next;
4102 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4104 next = i;
4105 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4107 (*i)->SetOwnerGUID(0);
4108 if(del)
4110 (*i)->SetRespawnTime(0);
4111 (*i)->Delete();
4114 next = m_gameObj.erase(i);
4116 else
4117 ++next;
4121 void Unit::RemoveAllGameObjects()
4123 // remove references to unit
4124 for(std::list<GameObject*>::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4126 (*i)->SetOwnerGUID(0);
4127 (*i)->SetRespawnTime(0);
4128 (*i)->Delete();
4129 i = m_gameObj.erase(i);
4133 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4135 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4136 data.append(log->target->GetPackGUID());
4137 data.append(log->attacker->GetPackGUID());
4138 data << uint32(log->SpellID);
4139 data << uint32(log->damage); //damage amount
4140 data << uint32(0);
4141 data << uint8 (log->schoolMask); //damage school
4142 data << uint32(log->absorb); //AbsorbedDamage
4143 data << uint32(log->resist); //resist
4144 data << uint8 (log->phusicalLog); // damsge type? flag
4145 data << uint8 (log->unused); //unused
4146 data << uint32(log->blocked); //blocked
4147 data << uint32(log->HitInfo);
4148 data << uint8 (0); // flag to use extend data
4149 SendMessageToSet( &data, true );
4152 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4154 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
4155 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4156 data.append(target->GetPackGUID());
4157 data.append(GetPackGUID());
4158 data << uint32(SpellID);
4159 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
4160 data << uint32(0); // wotlk
4161 data << uint8(damageSchoolMask); // spell school
4162 data << uint32(AbsorbedDamage); // AbsorbedDamage
4163 data << uint32(Resist); // resist
4164 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
4165 data << uint8(0); // unk isFromAura
4166 data << uint32(Blocked); // blocked
4167 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
4168 data << uint8(0); // isDebug?
4169 SendMessageToSet( &data, true );
4172 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4174 // Not much to do if no flags are set.
4175 if (procAttacker)
4176 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4177 // Now go on with a victim's events'n'auras
4178 // Not much to do if no flags are set or there is no victim
4179 if(pVictim && pVictim->isAlive() && procVictim)
4180 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4183 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4185 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4186 data << uint32(spellID);
4187 data << uint64(GetGUID());
4188 data << uint8(0); // can be 0 or 1
4189 data << uint32(1); // target count
4190 // for(i = 0; i < target count; ++i)
4191 data << uint64(target->GetGUID()); // target GUID
4192 data << uint8(missInfo);
4193 // end loop
4194 SendMessageToSet(&data, true);
4197 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4199 uint32 count = 1;
4200 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4201 data << (uint32)damageInfo->HitInfo;
4202 data.append(GetPackGUID());
4203 data.append(damageInfo->target->GetPackGUID());
4204 data << (uint32)(damageInfo->damage); // Full damage
4205 data << uint32(0); // overkill value
4207 data << (uint8)count; // Sub damage count
4209 for(int i = 0; i < count; ++i)
4211 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4212 data << (float)damageInfo->damage; // sub damage
4213 data << (uint32)damageInfo->damage; // Sub Damage
4216 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4218 for(int i = 0; i < count; ++i)
4219 data << (uint32)damageInfo->absorb; // Absorb
4222 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4224 for(int i = 0; i < count; ++i)
4225 data << (uint32)damageInfo->resist; // Resist
4228 data << (uint8)damageInfo->TargetState;
4229 data << (uint32)0;
4230 data << (uint32)0;
4232 if(damageInfo->HitInfo & HITINFO_BLOCK)
4233 data << (uint32)damageInfo->blocked_amount;
4235 if(damageInfo->HitInfo & HITINFO_UNK3)
4236 data << uint32(0);
4238 if(damageInfo->HitInfo & HITINFO_UNK1)
4240 data << uint32(0);
4241 data << float(0);
4242 data << float(0);
4243 data << float(0);
4244 data << float(0);
4245 data << float(0);
4246 data << float(0);
4247 data << float(0);
4248 data << float(0);
4249 for(uint8 i = 0; i < 5; ++i)
4251 data << float(0);
4252 data << float(0);
4254 data << uint32(0);
4257 SendMessageToSet( &data, true );
4260 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4262 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4264 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4265 data << uint32(HitInfo); // flags
4266 data.append(GetPackGUID());
4267 data.append(target->GetPackGUID());
4268 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4269 data << uint32(0); // overkill value
4271 data << (uint8)SwingType; // count?
4273 // for(i = 0; i < SwingType; ++i)
4274 data << (uint32)damageSchoolMask;
4275 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4276 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4277 // end loop
4279 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4281 // for(i = 0; i < SwingType; ++i)
4282 data << uint32(AbsorbDamage);
4283 // end loop
4286 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4288 // for(i = 0; i < SwingType; ++i)
4289 data << uint32(Resist);
4290 // end loop
4293 data << (uint8)TargetState;
4294 data << (uint32)0;
4295 data << (uint32)0;
4297 if(HitInfo & HITINFO_BLOCK)
4299 data << uint32(BlockedAmount);
4302 if(HitInfo & HITINFO_UNK3)
4304 data << uint32(0);
4307 if(HitInfo & HITINFO_UNK1)
4309 data << uint32(0);
4310 data << float(0);
4311 data << float(0);
4312 data << float(0);
4313 data << float(0);
4314 data << float(0);
4315 data << float(0);
4316 data << float(0);
4317 data << float(0);
4318 for(uint8 i = 0; i < 5; ++i)
4320 data << float(0);
4321 data << float(0);
4323 data << uint32(0);
4326 SendMessageToSet( &data, true );
4329 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4331 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4333 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4334 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4336 uint32 triggered_spell_id = 0;
4337 Unit* target = pVictim;
4338 int32 basepoints0 = 0;
4340 switch(hasteSpell->SpellFamilyName)
4342 case SPELLFAMILY_ROGUE:
4344 switch(hasteSpell->Id)
4346 // Blade Flurry
4347 case 13877:
4348 case 33735:
4350 target = SelectNearbyTarget();
4351 if(!target)
4352 return false;
4353 basepoints0 = damage;
4354 triggered_spell_id = 22482;
4355 break;
4358 break;
4362 // processed charge only counting case
4363 if(!triggered_spell_id)
4364 return true;
4366 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4368 if(!triggerEntry)
4370 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4371 return false;
4374 // default case
4375 if(!target || target!=this && !target->isAlive())
4376 return false;
4378 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4379 return false;
4381 if(basepoints0)
4382 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4383 else
4384 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4386 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4387 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4389 return true;
4392 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4394 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4395 uint32 effIndex = triggeredByAura->GetEffIndex();
4396 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4398 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4399 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4401 uint32 triggered_spell_id = 0;
4402 Unit* target = pVictim;
4403 int32 basepoints0 = 0;
4405 switch(dummySpell->SpellFamilyName)
4407 case SPELLFAMILY_GENERIC:
4409 switch (dummySpell->Id)
4411 // Eye for an Eye
4412 case 9799:
4413 case 25988:
4415 // prevent damage back from weapon special attacks
4416 if (!procSpell || procSpell->DmgClass != SPELL_DAMAGE_CLASS_MAGIC )
4417 return false;
4419 // return damage % to attacker but < 50% own total health
4420 basepoints0 = triggerAmount*int32(damage)/100;
4421 if(basepoints0 > GetMaxHealth()/2)
4422 basepoints0 = GetMaxHealth()/2;
4424 triggered_spell_id = 25997;
4425 break;
4427 // Sweeping Strikes
4428 case 12328:
4429 case 18765:
4430 case 35429:
4432 // prevent chain of triggered spell from same triggered spell
4433 if(procSpell && procSpell->Id==26654)
4434 return false;
4436 target = SelectNearbyTarget();
4437 if(!target)
4438 return false;
4440 triggered_spell_id = 26654;
4441 break;
4443 // Unstable Power
4444 case 24658:
4446 if (!procSpell || procSpell->Id == 24659)
4447 return false;
4448 // Need remove one 24659 aura
4449 RemoveSingleSpellAurasFromStack(24659);
4450 return true;
4452 // Restless Strength
4453 case 24661:
4455 // Need remove one 24662 aura
4456 RemoveSingleSpellAurasFromStack(24662);
4457 return true;
4459 // Adaptive Warding (Frostfire Regalia set)
4460 case 28764:
4462 if(!procSpell)
4463 return false;
4465 // find Mage Armor
4466 bool found = false;
4467 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4468 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4470 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4472 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4474 found=true;
4475 break;
4479 if(!found)
4480 return false;
4482 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4484 case SPELL_SCHOOL_NORMAL:
4485 case SPELL_SCHOOL_HOLY:
4486 return false; // ignored
4487 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4488 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4489 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4490 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4491 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4492 default:
4493 return false;
4496 target = this;
4497 break;
4499 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4500 case 27539:
4502 if(!procSpell)
4503 return false;
4505 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4507 case SPELL_SCHOOL_NORMAL:
4508 return false; // ignore
4509 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4510 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4511 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4512 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4513 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4514 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4515 default:
4516 return false;
4519 target = this;
4520 break;
4522 // Mana Leech (Passive) (Priest Pet Aura)
4523 case 28305:
4525 // Cast on owner
4526 target = GetOwner();
4527 if(!target)
4528 return false;
4530 triggered_spell_id = 34650;
4531 break;
4533 // Mark of Malice
4534 case 33493:
4536 // Cast finish spell at last charge
4537 if (triggeredByAura->GetAuraCharges() > 1)
4538 return false;
4540 target = this;
4541 triggered_spell_id = 33494;
4542 break;
4544 // Twisted Reflection (boss spell)
4545 case 21063:
4546 triggered_spell_id = 21064;
4547 break;
4548 // Vampiric Aura (boss spell)
4549 case 38196:
4551 basepoints0 = 3 * damage; // 300%
4552 if (basepoints0 < 0)
4553 return false;
4555 triggered_spell_id = 31285;
4556 target = this;
4557 break;
4559 // Aura of Madness (Darkmoon Card: Madness trinket)
4560 //=====================================================
4561 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4562 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4563 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4564 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4565 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4566 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4567 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4568 // 41011 Martyr Complex: +35 stamina (All classes)
4569 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4570 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4571 case 39446:
4573 if(GetTypeId() != TYPEID_PLAYER)
4574 return false;
4576 // Select class defined buff
4577 switch (getClass())
4579 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4580 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4582 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4583 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4584 break;
4586 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4587 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4589 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4590 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4591 break;
4593 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4594 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4595 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4596 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4598 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4599 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4600 break;
4602 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4604 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4605 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4606 break;
4608 default:
4609 return false;
4612 target = this;
4613 if (roll_chance_i(10))
4614 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4615 break;
4618 // TODO: need find item for aura and triggered spells
4619 // Sunwell Exalted Caster Neck (??? neck)
4620 // cast ??? Light's Wrath if Exalted by Aldor
4621 // cast ??? Arcane Bolt if Exalted by Scryers*/
4622 case 46569:
4623 return false; // disable for while
4626 if(GetTypeId() != TYPEID_PLAYER)
4627 return false;
4629 // Get Aldor reputation rank
4630 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4632 target = this;
4633 triggered_spell_id = ???
4634 break;
4636 // Get Scryers reputation rank
4637 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4639 triggered_spell_id = ???
4640 break;
4642 return false;
4643 }/**/
4644 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4645 // cast 45479 Light's Wrath if Exalted by Aldor
4646 // cast 45429 Arcane Bolt if Exalted by Scryers
4647 case 45481:
4649 if(GetTypeId() != TYPEID_PLAYER)
4650 return false;
4652 // Get Aldor reputation rank
4653 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4655 target = this;
4656 triggered_spell_id = 45479;
4657 break;
4659 // Get Scryers reputation rank
4660 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4662 triggered_spell_id = 45429;
4663 break;
4665 return false;
4667 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4668 // cast 45480 Light's Strength if Exalted by Aldor
4669 // cast 45428 Arcane Strike if Exalted by Scryers
4670 case 45482:
4672 if(GetTypeId() != TYPEID_PLAYER)
4673 return false;
4675 // Get Aldor reputation rank
4676 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4678 target = this;
4679 triggered_spell_id = 45480;
4680 break;
4682 // Get Scryers reputation rank
4683 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4685 triggered_spell_id = 45428;
4686 break;
4688 return false;
4690 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4691 // cast 45431 Arcane Insight if Exalted by Aldor
4692 // cast 45432 Light's Ward if Exalted by Scryers
4693 case 45483:
4695 if(GetTypeId() != TYPEID_PLAYER)
4696 return false;
4698 // Get Aldor reputation rank
4699 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4701 target = this;
4702 triggered_spell_id = 45432;
4703 break;
4705 // Get Scryers reputation rank
4706 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4708 target = this;
4709 triggered_spell_id = 45431;
4710 break;
4712 return false;
4714 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4715 // cast 45478 Light's Salvation if Exalted by Aldor
4716 // cast 45430 Arcane Surge if Exalted by Scryers
4717 case 45484:
4719 if(GetTypeId() != TYPEID_PLAYER)
4720 return false;
4722 // Get Aldor reputation rank
4723 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4725 target = this;
4726 triggered_spell_id = 45478;
4727 break;
4729 // Get Scryers reputation rank
4730 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4732 triggered_spell_id = 45430;
4733 break;
4735 return false;
4737 // Living Seed
4738 case 48504:
4740 triggered_spell_id = 48503;
4741 basepoints0 = triggerAmount;
4742 target = this;
4743 break;
4745 // Vampiric Touch (generic, used by some boss)
4746 case 52723:
4747 case 60501:
4749 triggered_spell_id = 52724;
4750 basepoints0 = damage / 2;
4751 target = this;
4752 break;
4754 // Divine purpose
4755 case 31871:
4756 case 31872:
4758 // Roll chane
4759 if (!roll_chance_i(triggerAmount))
4760 return false;
4762 // Remove any stun effect on target
4763 AuraMap& Auras = pVictim->GetAuras();
4764 for(AuraMap::iterator iter = Auras.begin(); iter != Auras.end();)
4766 SpellEntry const *spell = iter->second->GetSpellProto();
4767 if( spell->Mechanic == MECHANIC_STUN ||
4768 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4770 pVictim->RemoveAurasDueToSpell(spell->Id);
4771 iter = Auras.begin();
4773 else
4774 ++iter;
4776 return true;
4779 break;
4781 case SPELLFAMILY_MAGE:
4783 // Magic Absorption
4784 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4786 if (getPowerType() != POWER_MANA)
4787 return false;
4789 // mana reward
4790 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
4791 target = this;
4792 triggered_spell_id = 29442;
4793 break;
4795 // Master of Elements
4796 if (dummySpell->SpellIconID == 1920)
4798 if(!procSpell)
4799 return false;
4801 // mana cost save
4802 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4803 basepoints0 = cost * triggerAmount/100;
4804 if( basepoints0 <=0 )
4805 return false;
4807 target = this;
4808 triggered_spell_id = 29077;
4809 break;
4811 // Hot Streak
4812 if (dummySpell->SpellIconID == 2999)
4814 if (effIndex!=0)
4815 return true;
4816 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4817 if (!counter)
4818 return true;
4820 // Count spell criticals in a row in second aura
4821 Modifier *mod = counter->GetModifier();
4822 if (procEx & PROC_EX_CRITICAL_HIT)
4824 mod->m_amount *=2;
4825 if (mod->m_amount < 100) // not enough
4826 return true;
4827 // Crititcal counted -> roll chance
4828 if (roll_chance_i(triggerAmount))
4829 CastSpell(this, 48108, true, castItem, triggeredByAura);
4831 mod->m_amount = 25;
4832 return true;
4834 // Burnout
4835 if (dummySpell->SpellIconID == 2998)
4837 if(!procSpell)
4838 return false;
4840 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4841 basepoints0 = cost * triggerAmount/100;
4842 if( basepoints0 <=0 )
4843 return false;
4844 triggered_spell_id = 44450;
4845 target = this;
4846 break;
4848 // Incanter's Regalia set (add trigger chance to Mana Shield)
4849 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4851 if(GetTypeId() != TYPEID_PLAYER)
4852 return false;
4854 target = this;
4855 triggered_spell_id = 37436;
4856 break;
4858 switch(dummySpell->Id)
4860 // Ignite
4861 case 11119:
4862 case 11120:
4863 case 12846:
4864 case 12847:
4865 case 12848:
4867 switch (dummySpell->Id)
4869 case 11119: basepoints0 = int32(0.04f*damage); break;
4870 case 11120: basepoints0 = int32(0.08f*damage); break;
4871 case 12846: basepoints0 = int32(0.12f*damage); break;
4872 case 12847: basepoints0 = int32(0.16f*damage); break;
4873 case 12848: basepoints0 = int32(0.20f*damage); break;
4874 default:
4875 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4876 return false;
4879 triggered_spell_id = 12654;
4880 break;
4882 // Combustion
4883 case 11129:
4885 //last charge and crit
4886 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4888 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4889 return true; // charge counting (will removed)
4892 CastSpell(this, 28682, true, castItem, triggeredByAura);
4893 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4896 break;
4898 case SPELLFAMILY_WARRIOR:
4900 // Retaliation
4901 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4903 // check attack comes not from behind
4904 if (!HasInArc(M_PI, pVictim))
4905 return false;
4907 triggered_spell_id = 22858;
4908 break;
4910 // Second Wind
4911 if (dummySpell->SpellIconID == 1697)
4913 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4914 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4915 return false;
4916 // Need stun or root mechanic
4917 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
4918 return false;
4920 switch (dummySpell->Id)
4922 case 29838: triggered_spell_id=29842; break;
4923 case 29834: triggered_spell_id=29841; break;
4924 case 42770: triggered_spell_id=42771; break;
4925 default:
4926 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4927 return false;
4930 target = this;
4931 break;
4933 // Damage Shield
4934 if (dummySpell->SpellIconID == 3214)
4936 triggered_spell_id = 59653;
4937 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
4938 break;
4940 break;
4942 case SPELLFAMILY_WARLOCK:
4944 // Seed of Corruption
4945 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4947 Modifier* mod = triggeredByAura->GetModifier();
4948 // if damage is more than need or target die from damage deal finish spell
4949 if( mod->m_amount <= damage || GetHealth() <= damage )
4951 // remember guid before aura delete
4952 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4954 // Remove aura (before cast for prevent infinite loop handlers)
4955 RemoveAurasDueToSpell(triggeredByAura->GetId());
4957 // Cast finish spell (triggeredByAura already not exist!)
4958 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4959 return true; // no hidden cooldown
4962 // Damage counting
4963 mod->m_amount-=damage;
4964 return true;
4966 // Seed of Corruption (Mobs cast) - no die req
4967 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4969 Modifier* mod = triggeredByAura->GetModifier();
4970 // if damage is more than need deal finish spell
4971 if( mod->m_amount <= damage )
4973 // remember guid before aura delete
4974 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4976 // Remove aura (before cast for prevent infinite loop handlers)
4977 RemoveAurasDueToSpell(triggeredByAura->GetId());
4979 // Cast finish spell (triggeredByAura already not exist!)
4980 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
4981 return true; // no hidden cooldown
4983 // Damage counting
4984 mod->m_amount-=damage;
4985 return true;
4987 // Fel Synergy
4988 if (dummySpell->SpellIconID == 3222)
4990 target = GetPet();
4991 if (!target)
4992 return false;
4993 triggered_spell_id = 54181;
4994 basepoints0 = damage * triggerAmount / 100;
4995 break;
4997 switch(dummySpell->Id)
4999 // Nightfall
5000 case 18094:
5001 case 18095:
5003 target = this;
5004 triggered_spell_id = 17941;
5005 break;
5007 //Soul Leech
5008 case 30293:
5009 case 30295:
5010 case 30296:
5012 // health
5013 basepoints0 = int32(damage*triggerAmount/100);
5014 target = this;
5015 triggered_spell_id = 30294;
5016 break;
5018 // Shadowflame (Voidheart Raiment set bonus)
5019 case 37377:
5021 triggered_spell_id = 37379;
5022 break;
5024 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5025 case 37381:
5027 target = GetPet();
5028 if(!target)
5029 return false;
5031 // heal amount
5032 basepoints0 = damage * triggerAmount/100;
5033 triggered_spell_id = 37382;
5034 break;
5036 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5037 case 39437:
5039 triggered_spell_id = 37378;
5040 break;
5043 break;
5045 case SPELLFAMILY_PRIEST:
5047 // Vampiric Touch
5048 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
5050 if(!pVictim || !pVictim->isAlive())
5051 return false;
5053 // pVictim is caster of aura
5054 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5055 return false;
5057 // energize amount
5058 basepoints0 = triggerAmount*damage/100;
5059 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5060 return true; // no hidden cooldown
5062 // Divine Aegis
5063 if (dummySpell->SpellIconID == 2820)
5065 basepoints0 = damage * triggerAmount/100;
5066 triggered_spell_id = 47753;
5067 break;
5069 switch(dummySpell->Id)
5071 // Vampiric Embrace
5072 case 15286:
5074 if(!pVictim || !pVictim->isAlive())
5075 return false;
5077 // pVictim is caster of aura
5078 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5079 return false;
5081 // heal amount
5082 int32 team = triggerAmount*damage/500;
5083 int32 self = triggerAmount*damage/100 - team;
5084 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5085 return true; // no hidden cooldown
5087 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5088 case 40438:
5090 // Shadow Word: Pain
5091 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
5092 triggered_spell_id = 40441;
5093 // Renew
5094 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5095 triggered_spell_id = 40440;
5096 else
5097 return false;
5099 target = this;
5100 break;
5102 // Oracle Healing Bonus ("Garments of the Oracle" set)
5103 case 26169:
5105 // heal amount
5106 basepoints0 = int32(damage * 10/100);
5107 target = this;
5108 triggered_spell_id = 26170;
5109 break;
5111 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5112 case 39372:
5114 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5115 return false;
5117 // heal amount
5118 basepoints0 = damage * triggerAmount/100;
5119 target = this;
5120 triggered_spell_id = 39373;
5121 break;
5123 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5124 case 28809:
5126 triggered_spell_id = 28810;
5127 break;
5130 break;
5132 case SPELLFAMILY_DRUID:
5134 switch(dummySpell->Id)
5136 // Healing Touch (Dreamwalker Raiment set)
5137 case 28719:
5139 // mana back
5140 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5141 target = this;
5142 triggered_spell_id = 28742;
5143 break;
5145 // Healing Touch Refund (Idol of Longevity trinket)
5146 case 28847:
5148 target = this;
5149 triggered_spell_id = 28848;
5150 break;
5152 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5153 case 37288:
5154 case 37295:
5156 target = this;
5157 triggered_spell_id = 37238;
5158 break;
5160 // Druid Tier 6 Trinket
5161 case 40442:
5163 float chance;
5165 // Starfire
5166 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
5168 triggered_spell_id = 40445;
5169 chance = 25.f;
5171 // Rejuvenation
5172 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5174 triggered_spell_id = 40446;
5175 chance = 25.f;
5177 // Mangle (cat/bear)
5178 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
5180 triggered_spell_id = 40452;
5181 chance = 40.f;
5183 else
5184 return false;
5186 if (!roll_chance_f(chance))
5187 return false;
5189 target = this;
5190 break;
5192 // Maim Interrupt
5193 case 44835:
5195 // Deadly Interrupt Effect
5196 triggered_spell_id = 32747;
5197 break;
5200 // Eclipse
5201 if (dummySpell->SpellIconID == 2856)
5203 if (!procSpell)
5204 return false;
5205 // Only 0 aura can proc
5206 if (effIndex!=0)
5207 return true;
5208 // Wrath crit
5209 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5211 if (!roll_chance_i(60))
5212 return false;
5213 triggered_spell_id = 48518;
5214 target = this;
5215 break;
5217 // Starfire crit
5218 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
5220 triggered_spell_id = 48517;
5221 target = this;
5222 break;
5224 return false;
5226 // Living Seed
5227 else if (dummySpell->SpellIconID == 2860)
5229 triggered_spell_id = 48504;
5230 basepoints0 = triggerAmount * damage / 100;
5231 break;
5233 break;
5235 case SPELLFAMILY_ROGUE:
5237 switch(dummySpell->Id)
5239 // Deadly Throw Interrupt
5240 case 32748:
5242 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5243 if(this == pVictim)
5244 return false;
5246 triggered_spell_id = 32747;
5247 break;
5250 // Cut to the Chase
5251 if( dummySpell->SpellIconID == 2909 )
5253 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5254 // lookup Slice and Dice
5255 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5256 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5258 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5259 if( spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5260 spellProto->SpellFamilyFlags & 0x0000000000040000LL)
5262 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5263 (*itr)->RefreshAura();
5264 return true;
5267 return false;
5269 // Deadly Brew
5270 if( dummySpell->SpellIconID == 2963 )
5272 triggered_spell_id = 25809;
5273 break;
5275 // Quick Recovery
5276 if( dummySpell->SpellIconID == 2116 )
5278 if(!procSpell)
5279 return false;
5281 // energy cost save
5282 basepoints0 = procSpell->manaCost * triggerAmount/100;
5283 if(basepoints0 <= 0)
5284 return false;
5286 target = this;
5287 triggered_spell_id = 31663;
5288 break;
5290 break;
5292 case SPELLFAMILY_HUNTER:
5294 // Thrill of the Hunt
5295 if ( dummySpell->SpellIconID == 2236 )
5297 if(!procSpell)
5298 return false;
5300 // mana cost save
5301 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5302 basepoints0 = mana * 40/100;
5303 if(basepoints0 <= 0)
5304 return false;
5306 target = this;
5307 triggered_spell_id = 34720;
5308 break;
5310 // Hunting Party
5311 if ( dummySpell->SpellIconID == 3406 )
5313 triggered_spell_id = 57669;
5314 target = this;
5315 break;
5317 // Lock and Load
5318 if ( dummySpell->SpellIconID == 3579 )
5320 // Proc only from periodic (from trap activation proc another aura of this spell)
5321 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5322 return false;
5323 triggered_spell_id = 56453;
5324 target = this;
5325 break;
5327 // Rapid Recuperation
5328 if ( dummySpell->SpellIconID == 3560 )
5330 // This effect only from Rapid Killing (mana regen)
5331 if (!(procSpell->SpellFamilyFlags & 0x0100000000000000LL))
5332 return false;
5333 triggered_spell_id = 56654;
5334 target = this;
5335 break;
5337 break;
5339 case SPELLFAMILY_PALADIN:
5341 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5342 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && effIndex==0)
5344 triggered_spell_id = 25742;
5345 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5346 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5347 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5348 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5349 break;
5351 // Sacred Shield
5352 if (dummySpell->SpellFamilyFlags&0x0008000000000000LL)
5354 triggered_spell_id = 58597;
5355 target = this;
5356 break;
5358 // Righteous Vengeance
5359 if (dummySpell->SpellIconID == 3025)
5361 // 4 damage tick
5362 basepoints0 = triggerAmount*damage/400;
5363 triggered_spell_id = 61840;
5364 break;
5366 // Sheath of Light
5367 if (dummySpell->SpellIconID == 3030)
5369 // 4 healing tick
5370 basepoints0 = triggerAmount*damage/400;
5371 triggered_spell_id = 54203;
5372 break;
5374 switch(dummySpell->Id)
5376 // Judgement of Light
5377 case 20185:
5379 // Get judgement caster
5380 Unit *caster = triggeredByAura->GetCaster();
5381 if (!caster)
5382 return false;
5383 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5384 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5385 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5386 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5387 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
5388 return true;
5390 // Judgement of Wisdom
5391 case 20186:
5393 if (pVictim->getPowerType() == POWER_MANA)
5394 pVictim->CastSpell(pVictim, 20268, true, 0, triggeredByAura);
5395 return true;
5397 // Holy Power (Redemption Armor set)
5398 case 28789:
5400 if(!pVictim)
5401 return false;
5403 // Set class defined buff
5404 switch (pVictim->getClass())
5406 case CLASS_PALADIN:
5407 case CLASS_PRIEST:
5408 case CLASS_SHAMAN:
5409 case CLASS_DRUID:
5410 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5411 break;
5412 case CLASS_MAGE:
5413 case CLASS_WARLOCK:
5414 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5415 break;
5416 case CLASS_HUNTER:
5417 case CLASS_ROGUE:
5418 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5419 break;
5420 case CLASS_WARRIOR:
5421 triggered_spell_id = 28790; // Increases the friendly target's armor
5422 break;
5423 default:
5424 return false;
5426 break;
5428 // Seal of Vengeance (damage calc on apply aura)
5429 case 31801:
5431 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5432 return false;
5434 triggered_spell_id = 31803;
5435 break;
5437 // Spiritual Attunement
5438 case 31785:
5439 case 33776:
5441 // if healed by another unit (pVictim)
5442 if(this == pVictim)
5443 return false;
5445 // heal amount
5446 basepoints0 = triggerAmount*damage/100;
5447 target = this;
5448 triggered_spell_id = 31786;
5449 break;
5451 // Seal of Blood do damage trigger
5452 case 31892:
5454 if (effIndex == 0) // 0 effect - is proc on enemy
5455 triggered_spell_id = 31893;
5456 else if (effIndex == 1) // 1 effect - is proc on self
5458 // add spell damage from prev effect (27%)
5459 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5460 basepoints0 = triggerAmount * damage / 100;
5461 target = this;
5462 triggered_spell_id = 32221;
5464 else
5465 return true;
5466 break;
5468 // Seal of the Martyr do damage trigger
5469 case 53720:
5471 if (effIndex == 0) // 0 effect - is proc on enemy
5472 triggered_spell_id = 53719;
5473 else if (effIndex == 1) // 1 effect - is proc on self
5475 // add spell damage from prev effect (27%)
5476 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5477 basepoints0 = triggerAmount * damage / 100;
5478 target = this;
5479 triggered_spell_id = 53718;
5481 else
5482 return true;
5483 break;
5485 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5486 case 40470:
5488 if( !procSpell )
5489 return false;
5491 float chance;
5493 // Flash of light/Holy light
5494 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5496 triggered_spell_id = 40471;
5497 chance = 15.f;
5499 // Judgement
5500 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5502 triggered_spell_id = 40472;
5503 chance = 50.f;
5505 else
5506 return false;
5508 if (!roll_chance_f(chance))
5509 return false;
5511 break;
5513 // Glyph of Divinity
5514 case 54939:
5516 // Lookup base amount mana restore
5517 for (int i=0; i<3;i++)
5518 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5520 int32 mana = procSpell->EffectBasePoints[i];
5521 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5522 break;
5524 return true;
5526 // Glyph of Flash of Light
5527 case 54936:
5529 triggered_spell_id = 54957;
5530 basepoints0 = triggerAmount*damage/100;
5531 break;
5533 // Glyph of Holy Light
5534 case 54937:
5536 triggered_spell_id = 54968;
5537 basepoints0 = triggerAmount*damage/100;
5538 break;
5541 break;
5543 case SPELLFAMILY_SHAMAN:
5545 switch(dummySpell->Id)
5547 // Totemic Power (The Earthshatterer set)
5548 case 28823:
5550 if( !pVictim )
5551 return false;
5553 // Set class defined buff
5554 switch (pVictim->getClass())
5556 case CLASS_PALADIN:
5557 case CLASS_PRIEST:
5558 case CLASS_SHAMAN:
5559 case CLASS_DRUID:
5560 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5561 break;
5562 case CLASS_MAGE:
5563 case CLASS_WARLOCK:
5564 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5565 break;
5566 case CLASS_HUNTER:
5567 case CLASS_ROGUE:
5568 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5569 break;
5570 case CLASS_WARRIOR:
5571 triggered_spell_id = 28827; // Increases the friendly target's armor
5572 break;
5573 default:
5574 return false;
5576 break;
5578 // Lesser Healing Wave (Totem of Flowing Water Relic)
5579 case 28849:
5581 target = this;
5582 triggered_spell_id = 28850;
5583 break;
5585 // Windfury Weapon (Passive) 1-5 Ranks
5586 case 33757:
5588 if(GetTypeId()!=TYPEID_PLAYER)
5589 return false;
5591 if(!castItem || !castItem->IsEquipped())
5592 return false;
5594 // custom cooldown processing case
5595 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5596 return false;
5598 // Now amount of extra power stored in 1 effect of Enchant spell
5599 // Get it by item enchant id
5600 uint32 spellId;
5601 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5603 case 283: spellId = 8232; break; // 1 Rank
5604 case 284: spellId = 8235; break; // 2 Rank
5605 case 525: spellId = 10486; break; // 3 Rank
5606 case 1669:spellId = 16362; break; // 4 Rank
5607 case 2636:spellId = 25505; break; // 5 Rank
5608 case 3785:spellId = 58801; break; // 6 Rank
5609 case 3786:spellId = 58803; break; // 7 Rank
5610 case 3787:spellId = 58804; break; // 8 Rank
5611 default:
5613 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5614 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5615 return false;
5619 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5620 if(!windfurySpellEntry)
5622 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5623 return false;
5626 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
5628 // Off-Hand case
5629 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5631 // Value gained from additional AP
5632 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5633 triggered_spell_id = 33750;
5635 // Main-Hand case
5636 else
5638 // Value gained from additional AP
5639 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5640 triggered_spell_id = 25504;
5643 // apply cooldown before cast to prevent processing itself
5644 if( cooldown )
5645 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5647 // Attack Twice
5648 for ( uint32 i = 0; i<2; ++i )
5649 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5651 return true;
5653 // Shaman Tier 6 Trinket
5654 case 40463:
5656 if( !procSpell )
5657 return false;
5659 float chance;
5660 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5662 triggered_spell_id = 40465; // Lightning Bolt
5663 chance = 15.f;
5665 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5667 triggered_spell_id = 40465; // Lesser Healing Wave
5668 chance = 10.f;
5670 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5672 triggered_spell_id = 40466; // Stormstrike
5673 chance = 50.f;
5675 else
5676 return false;
5678 if (!roll_chance_f(chance))
5679 return false;
5681 target = this;
5682 break;
5684 // Glyph of Healing Wave
5685 case 55440:
5687 // Not proc from self heals
5688 if (this==pVictim)
5689 return false;
5690 basepoints0 = triggerAmount * damage / 100;
5691 target = this;
5692 triggered_spell_id = 55533;
5693 break;
5695 // Spirit Hunt
5696 case 58877:
5698 // Cast on owner
5699 target = GetOwner();
5700 if(!target)
5701 return false;
5702 basepoints0 = triggerAmount * damage / 100;
5703 triggered_spell_id = 58879;
5704 break;
5707 // Ancestral Awakening
5708 if (dummySpell->SpellIconID == 2018)
5710 // TODO: frite dummy fot triggered spell
5711 triggered_spell_id = 52759;
5712 basepoints0 = triggerAmount * damage / 100;
5713 target = this;
5714 break;
5716 // Earth Shield
5717 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5719 basepoints0 = triggerAmount;
5720 target = this;
5721 triggered_spell_id = 379;
5722 break;
5724 // Improved Water Shield
5725 if (dummySpell->SpellIconID == 2287)
5727 // Lesser Healing Wave need aditional 60% roll
5728 if (procSpell->SpellFamilyFlags & 0x0000000000000080LL && !roll_chance_i(60))
5729 return false;
5730 // lookup water shield
5731 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5732 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5734 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5735 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000002000000000LL)
5737 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
5738 CastSpell(this, spell, true, castItem, triggeredByAura);
5739 if ((*itr)->DropAuraCharge())
5740 RemoveAurasDueToSpell((*itr)->GetId());
5741 return true;
5744 return false;
5745 break;
5747 // Lightning Overload
5748 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5750 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5751 return false;
5753 // custom cooldown processing case
5754 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5755 return false;
5757 uint32 spellId = 0;
5758 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5759 switch (procSpell->Id)
5761 // Lightning Bolt
5762 case 403: spellId = 45284; break; // Rank 1
5763 case 529: spellId = 45286; break; // Rank 2
5764 case 548: spellId = 45287; break; // Rank 3
5765 case 915: spellId = 45288; break; // Rank 4
5766 case 943: spellId = 45289; break; // Rank 5
5767 case 6041: spellId = 45290; break; // Rank 6
5768 case 10391: spellId = 45291; break; // Rank 7
5769 case 10392: spellId = 45292; break; // Rank 8
5770 case 15207: spellId = 45293; break; // Rank 9
5771 case 15208: spellId = 45294; break; // Rank 10
5772 case 25448: spellId = 45295; break; // Rank 11
5773 case 25449: spellId = 45296; break; // Rank 12
5774 case 49237: spellId = 49239; break; // Rank 13
5775 case 49238: spellId = 49240; break; // Rank 14
5776 // Chain Lightning
5777 case 421: spellId = 45297; break; // Rank 1
5778 case 930: spellId = 45298; break; // Rank 2
5779 case 2860: spellId = 45299; break; // Rank 3
5780 case 10605: spellId = 45300; break; // Rank 4
5781 case 25439: spellId = 45301; break; // Rank 5
5782 case 25442: spellId = 45302; break; // Rank 6
5783 case 49268: spellId = 49270; break; // Rank 7
5784 case 49269: spellId = 49271; break; // Rank 8
5785 default:
5786 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5787 return false;
5789 // No thread generated mod
5790 // TODO: exist special flag in spell attributes for this, need found and use!
5791 SpellModifier *mod = new SpellModifier;
5792 mod->op = SPELLMOD_THREAT;
5793 mod->value = -100;
5794 mod->type = SPELLMOD_PCT;
5795 mod->spellId = dummySpell->Id;
5796 mod->mask = 0x0000000000000003LL;
5797 mod->mask2= 0LL;
5798 ((Player*)this)->AddSpellMod(mod, true);
5800 // Remove cooldown (Chain Lightning - have Category Recovery time)
5801 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5802 ((Player*)this)->RemoveSpellCooldown(spellId);
5804 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5806 ((Player*)this)->AddSpellMod(mod, false);
5808 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5809 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5811 return true;
5813 // Static Shock
5814 if(dummySpell->SpellIconID == 3059)
5816 // lookup Lightning Shield
5817 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5818 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5820 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5821 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000000000000400LL)
5823 uint32 spell = 0;
5824 switch ((*itr)->GetId())
5826 case 324: spell = 26364; break;
5827 case 325: spell = 26365; break;
5828 case 905: spell = 26366; break;
5829 case 945: spell = 26367; break;
5830 case 8134: spell = 26369; break;
5831 case 10431: spell = 26370; break;
5832 case 10432: spell = 26363; break;
5833 case 25469: spell = 26371; break;
5834 case 25472: spell = 26372; break;
5835 case 49280: spell = 49278; break;
5836 case 49281: spell = 49279; break;
5837 default:
5838 return false;
5840 CastSpell(this, spell, true, castItem, triggeredByAura);
5841 if ((*itr)->DropAuraCharge())
5842 RemoveAurasDueToSpell((*itr)->GetId());
5843 return true;
5846 return false;
5847 break;
5849 break;
5851 case SPELLFAMILY_DEATHKNIGHT:
5853 // Blood Aura
5854 if (dummySpell->SpellIconID == 2636)
5856 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
5857 return false;
5858 basepoints0 = triggerAmount * damage / 100;
5859 triggered_spell_id = 53168;
5860 break;
5862 // Butchery
5863 if (dummySpell->SpellIconID == 2664)
5865 basepoints0 = triggerAmount;
5866 triggered_spell_id = 50163;
5867 target = this;
5868 break;
5870 // Dancing Rune Weapon
5871 if (dummySpell->Id == 49028)
5873 // 1 dummy aura for dismiss rune blade
5874 if (effIndex!=2)
5875 return false;
5876 // TODO: wite script for this "fights on its own, doing the same attacks"
5877 // NOTE: Trigger here on every attack and spell cast
5878 return false;
5880 // Mark of Blood
5881 if (dummySpell->Id == 49005)
5883 // TODO: need more info (cooldowns/PPM)
5884 triggered_spell_id = 50424;
5885 break;
5887 // Vendetta
5888 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
5890 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5891 triggered_spell_id = 50181;
5892 target = this;
5893 break;
5895 // Necrosis
5896 if (dummySpell->SpellIconID == 2709)
5898 basepoints0 = triggerAmount * damage / 100;
5899 triggered_spell_id = 51460;
5900 break;
5902 // Runic Power Back on Snare/Root
5903 if (dummySpell->Id == 61257)
5905 // only for spells and hit/crit (trigger start always) and not start from self casted spells
5906 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5907 return false;
5908 // Need snare or root mechanic
5909 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
5910 return false;
5911 triggered_spell_id = 61258;
5912 target = this;
5913 break;
5915 // Wandering Plague
5916 if (dummySpell->SpellIconID == 1614)
5918 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
5919 return false;
5920 basepoints0 = triggerAmount * damage / 100;
5921 triggered_spell_id = 50526;
5922 break;
5924 break;
5926 default:
5927 break;
5930 // processed charge only counting case
5931 if(!triggered_spell_id)
5932 return true;
5934 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5936 if(!triggerEntry)
5938 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5939 return false;
5942 // default case
5943 if(!target || target!=this && !target->isAlive())
5944 return false;
5946 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5947 return false;
5949 if(basepoints0)
5950 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5951 else
5952 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5954 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5955 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5957 return true;
5960 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5962 // Get triggered aura spell info
5963 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5965 // Basepoints of trigger aura
5966 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5968 // Set trigger spell id, target, custom basepoints
5969 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
5970 Unit* target = NULL;
5971 int32 basepoints0 = 0;
5973 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
5974 basepoints0 = triggerAmount;
5976 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5977 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5979 // Try handle uncnown trigger spells
5980 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
5982 switch (auraSpellInfo->SpellFamilyName)
5984 case SPELLFAMILY_GENERIC:
5985 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
5986 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
5987 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
5988 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
5989 trigger_spell_id = 23781;
5990 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
5991 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
5993 // trigger_spell_id = 48877;
5995 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
5997 // trigger_spell_id = 59233;
5999 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6001 // trigger_spell_id = 29471; // gain mana
6002 // 27526; // drain mana if possible
6004 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6005 //else if (auraSpellInfo->Id==54476) // Blood Presence
6006 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6007 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6008 //else if (auraSpellInfo->Id==52856) // Charge
6009 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6011 // Pct value stored in dummy
6012 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6013 target = pVictim;
6014 break;
6016 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6017 // trigger_spell_id = 41249;
6018 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6019 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6020 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6021 // trigger_spell_id = 41055;
6022 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6023 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6024 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6026 uint32 stat = 0;
6027 // strength
6028 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6029 // agility
6030 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6031 // intellect
6032 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6033 // spirit
6034 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
6036 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6037 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6038 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6039 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6040 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6041 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6042 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6043 trigger_spell_id = 33898;
6044 //else if (auraSpellInfo->Id==18943) // Double Attack
6045 //else if (auraSpellInfo->Id==19194) // Double Attack
6046 //else if (auraSpellInfo->Id==19817) // Double Attack
6047 //else if (auraSpellInfo->Id==19818) // Double Attack
6048 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6049 // trigger_spell_id = 14822;
6051 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6053 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6055 case 34191:
6056 case 34329:
6057 case 34524:
6058 case 34582:
6059 case 36733:
6060 break;
6061 default:
6062 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6063 return false;
6065 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6066 switch (procSpell->School)
6068 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6069 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6070 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6071 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6072 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6073 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6074 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6075 default:
6076 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6077 return false;
6081 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6082 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6083 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6084 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6085 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6086 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6087 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6088 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6089 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6090 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6091 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6092 //else if (auraSpellInfo->Id==40250) // Improved Duration
6093 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6094 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6095 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6096 // Mana Drain Trigger
6098 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6099 if (this && this->isAlive())
6100 CastSpell(this, 29471, true, castItem, triggeredByAura);
6101 if (pVictim && pVictim->isAlive())
6102 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6103 return true;
6105 //else if (auraSpellInfo->Id==55580) // Mana Link
6106 //else if (auraSpellInfo->Id==45903) // Offensive State
6107 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6108 //else if (auraSpellInfo->Id==43453) // Rune Ward
6109 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6110 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6111 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6112 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6113 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6114 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6115 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6116 //else if (auraSpellInfo->Id==35205) // Vanish
6117 //else if (auraSpellInfo->Id==42730) // Woe Strike
6118 //else if (auraSpellInfo->Id==59735) // Woe Strike
6119 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6120 break;
6121 case SPELLFAMILY_MAGE:
6122 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6124 switch (auraSpellInfo->Id)
6126 case 31641: // Rank 1
6127 case 31642: // Rank 2
6128 trigger_spell_id = 31643;
6129 break;
6130 default:
6131 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6132 return false;
6135 break;
6136 case SPELLFAMILY_WARRIOR:
6137 if (auraSpellInfo->Id == 50421) // Scent of Blood
6138 trigger_spell_id = 50422;
6139 break;
6140 case SPELLFAMILY_WARLOCK:
6142 // Pyroclasm
6143 if (auraSpellInfo->SpellIconID == 1137)
6145 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6146 return false;
6147 // Calculate spell tick count for spells
6148 uint32 tick = 1; // Default tick = 1
6150 // Hellfire have 15 tick
6151 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
6152 tick = 15;
6153 // Rain of Fire have 4 tick
6154 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
6155 tick = 4;
6156 else
6157 return false;
6159 // Calculate chance = baseChance / tick
6160 float chance = 0;
6161 switch (auraSpellInfo->Id)
6163 case 18096: chance = 13.0f / tick; break;
6164 case 18073: chance = 26.0f / tick; break;
6166 // Roll chance
6167 if (!roll_chance_f(chance))
6168 return false;
6170 trigger_spell_id = 18093;
6172 // Drain Soul
6173 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
6175 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6176 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6178 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6180 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
6181 // Drain Soul
6182 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
6183 break;
6186 // Not remove charge (aura removed on death in any cases)
6187 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6188 return false;
6190 // Nether Protection
6191 else if (auraSpellInfo->SpellIconID == 1985)
6193 if (!procSpell)
6194 return false;
6195 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6197 case SPELL_SCHOOL_NORMAL:
6198 case SPELL_SCHOOL_HOLY:
6199 return false; // ignore
6200 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6201 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6202 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6203 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6204 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6205 default:
6206 return false;
6209 break;
6211 case SPELLFAMILY_PRIEST:
6213 // Greater Heal Refund
6214 if (auraSpellInfo->Id==37594)
6215 trigger_spell_id = 37595;
6216 // Blessed Recovery
6217 else if (auraSpellInfo->SpellIconID == 1875)
6219 switch (auraSpellInfo->Id)
6221 case 27811: trigger_spell_id = 27813; break;
6222 case 27815: trigger_spell_id = 27817; break;
6223 case 27816: trigger_spell_id = 27818; break;
6224 default:
6225 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6226 return false;
6228 basepoints0 = damage * triggerAmount / 100 / 3;
6229 target = this;
6231 break;
6233 case SPELLFAMILY_DRUID:
6235 // Druid Forms Trinket
6236 if (auraSpellInfo->Id==37336)
6238 switch(m_form)
6240 case FORM_NONE: trigger_spell_id = 37344;break;
6241 case FORM_CAT: trigger_spell_id = 37341;break;
6242 case FORM_BEAR:
6243 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6244 case FORM_TREE: trigger_spell_id = 37342;break;
6245 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6246 default:
6247 return false;
6250 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6251 // trigger_spell_id = ????;
6252 // Leader of the Pack
6253 else if (auraSpellInfo->Id == 24932)
6255 if (triggerAmount == 0)
6256 return false;
6257 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6258 trigger_spell_id = 34299;
6260 break;
6262 case SPELLFAMILY_HUNTER:
6263 break;
6264 case SPELLFAMILY_PALADIN:
6267 // Blessed Life
6268 if (auraSpellInfo->SpellIconID == 2137)
6270 switch (auraSpellInfo->Id)
6272 case 31828: // Rank 1
6273 case 31829: // Rank 2
6274 case 31830: // Rank 3
6275 break;
6276 default:
6277 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6278 return false;
6282 // Healing Discount
6283 if (auraSpellInfo->Id==37705)
6285 trigger_spell_id = 37706;
6286 target = this;
6288 // Soul Preserver
6289 if (auraSpellInfo->Id==60510)
6291 trigger_spell_id = 60515;
6292 target = this;
6294 // Illumination
6295 else if (auraSpellInfo->SpellIconID==241)
6297 if(!procSpell)
6298 return false;
6299 // procspell is triggered spell but we need mana cost of original casted spell
6300 uint32 originalSpellId = procSpell->Id;
6301 // Holy Shock heal
6302 if(procSpell->SpellFamilyFlags & 0x0001000000000000LL)
6304 switch(procSpell->Id)
6306 case 25914: originalSpellId = 20473; break;
6307 case 25913: originalSpellId = 20929; break;
6308 case 25903: originalSpellId = 20930; break;
6309 case 27175: originalSpellId = 27174; break;
6310 case 33074: originalSpellId = 33072; break;
6311 case 48820: originalSpellId = 48824; break;
6312 case 48821: originalSpellId = 48825; break;
6313 default:
6314 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6315 return false;
6318 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6319 if(!originalSpell)
6321 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6322 return false;
6324 // percent stored in effect 1 (class scripts) base points
6325 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6326 basepoints0 = cost*(auraSpellInfo->EffectBasePoints[1]+1)/100;
6327 trigger_spell_id = 20272;
6328 target = this;
6330 // Lightning Capacitor
6331 else if (auraSpellInfo->Id==37657)
6333 if(!pVictim || !pVictim->isAlive())
6334 return false;
6335 // stacking
6336 CastSpell(this, 37658, true, NULL, triggeredByAura);
6338 Aura * dummy = GetDummyAura(37658);
6339 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6340 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6341 return false;
6343 RemoveAurasDueToSpell(37658);
6344 trigger_spell_id = 37661;
6345 target = pVictim;
6347 // Thunder Capacitor
6348 else if (auraSpellInfo->Id == 54841)
6350 if(!pVictim || !pVictim->isAlive())
6351 return false;
6352 // stacking
6353 CastSpell(this, 54842, true, NULL, triggeredByAura);
6355 // counting
6356 Aura * dummy = GetDummyAura(54842);
6357 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6358 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6359 return false;
6361 RemoveAurasDueToSpell(54842);
6362 trigger_spell_id = 54843;
6363 target = pVictim;
6365 break;
6367 case SPELLFAMILY_SHAMAN:
6369 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6370 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
6372 switch(auraSpellInfo->Id)
6374 case 324: // Rank 1
6375 trigger_spell_id = 26364; break;
6376 case 325: // Rank 2
6377 trigger_spell_id = 26365; break;
6378 case 905: // Rank 3
6379 trigger_spell_id = 26366; break;
6380 case 945: // Rank 4
6381 trigger_spell_id = 26367; break;
6382 case 8134: // Rank 5
6383 trigger_spell_id = 26369; break;
6384 case 10431: // Rank 6
6385 trigger_spell_id = 26370; break;
6386 case 10432: // Rank 7
6387 trigger_spell_id = 26363; break;
6388 case 25469: // Rank 8
6389 trigger_spell_id = 26371; break;
6390 case 25472: // Rank 9
6391 trigger_spell_id = 26372; break;
6392 case 49280: // Rank 10
6393 trigger_spell_id = 49278; break;
6394 case 49281: // Rank 11
6395 trigger_spell_id = 49279; break;
6396 default:
6397 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6398 return false;
6401 // Lightning Shield (The Ten Storms set)
6402 else if (auraSpellInfo->Id == 23551)
6404 trigger_spell_id = 23552;
6405 target = pVictim;
6407 // Damage from Lightning Shield (The Ten Storms set)
6408 else if (auraSpellInfo->Id == 23552)
6409 trigger_spell_id = 27635;
6410 // Mana Surge (The Earthfury set)
6411 else if (auraSpellInfo->Id == 23572)
6413 if(!procSpell)
6414 return false;
6415 basepoints0 = procSpell->manaCost * 35 / 100;
6416 trigger_spell_id = 23571;
6417 target = this;
6419 // Nature's Guardian
6420 else if (auraSpellInfo->SpellIconID == 2013)
6422 // Check health condition - should drop to less 30% (damage deal after this!)
6423 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6424 return false;
6426 if(pVictim && pVictim->isAlive())
6427 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6429 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6430 trigger_spell_id = 31616;
6431 target = this;
6433 break;
6435 case SPELLFAMILY_DEATHKNIGHT:
6437 // Acclimation
6438 if (auraSpellInfo->SpellIconID == 1930)
6440 if (!procSpell)
6441 return false;
6442 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6444 case SPELL_SCHOOL_NORMAL:
6445 return false; // ignore
6446 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6447 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6448 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6449 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6450 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6451 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6452 default:
6453 return false;
6456 // Blood Presence
6457 else if (auraSpellInfo->Id == 48266)
6459 if (GetTypeId() != TYPEID_PLAYER)
6460 return false;
6461 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6462 return false;
6463 trigger_spell_id = 50475;
6464 basepoints0 = damage * triggerAmount / 100;
6466 break;
6468 default:
6469 break;
6473 // All ok. Check current trigger spell
6474 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6475 if ( triggerEntry == NULL )
6477 // Not cast unknown spell
6478 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6479 return false;
6482 // not allow proc extra attack spell at extra attack
6483 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6484 return false;
6486 // Costum requirements (not listed in procEx) Warning! damage dealing after this
6487 // Custom triggered spells
6488 switch (auraSpellInfo->Id)
6490 // Persistent Shield (Scarab Brooch trinket)
6491 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6492 case 26467:
6494 basepoints0 = damage * 15 / 100;
6495 target = pVictim;
6496 trigger_spell_id = 26470;
6497 break;
6499 // Cheat Death
6500 case 28845:
6502 // When your health drops below 20% ....
6503 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6504 return false;
6505 break;
6507 // Deadly Swiftness (Rank 1)
6508 case 31255:
6510 // whenever you deal damage to a target who is below 20% health.
6511 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6512 return false;
6514 target = this;
6515 trigger_spell_id = 22588;
6517 // Greater Heal Refund (Avatar Raiment set)
6518 case 37594:
6520 // Not give if target alredy have full health
6521 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6522 return false;
6523 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6524 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6525 return false;
6526 break;
6528 // Bonus Healing (Crystal Spire of Karabor mace)
6529 case 40971:
6531 // If your target is below $s1% health
6532 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6533 return false;
6534 break;
6536 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6537 case 45057:
6539 // reduce you below $s1% health
6540 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6541 return false;
6542 break;
6544 // Rapid Recuperation
6545 case 53228:
6546 case 53232:
6548 // This effect only from Rapid Fire (ability cast)
6549 if (!(procSpell->SpellFamilyFlags & 0x0000000000000020LL))
6550 return false;
6551 break;
6555 // Costum basepoints/target for exist spell
6556 // dummy basepoints or other customs
6557 switch(trigger_spell_id)
6559 // Cast positive spell on enemy target
6560 case 7099: // Curse of Mending
6561 case 39647: // Curse of Mending
6562 case 29494: // Temptation
6563 case 20233: // Improved Lay on Hands (cast on target)
6565 target = pVictim;
6566 break;
6568 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
6569 case 15250: // Rogue Setup
6571 if(!pVictim || pVictim != getVictim()) // applied only for main target
6572 return false;
6573 break; // continue normal case
6575 // Finish movies that add combo
6576 case 14189: // Seal Fate (Netherblade set)
6577 case 14157: // Ruthlessness
6579 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6580 break;
6582 // Bloodthirst (($m/100)% of max health)
6583 case 23880:
6585 basepoints0 = int32(GetMaxHealth() * triggerAmount / 10000);
6586 break;
6588 // Shamanistic Rage triggered spell
6589 case 30824:
6591 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6592 break;
6594 // Enlightenment (trigger only from mana cost spells)
6595 case 35095:
6597 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6598 return false;
6599 break;
6601 // Brain Freeze
6602 case 57761:
6604 if(!procSpell)
6605 return false;
6606 // For trigger from Blizzard need exist Improved Blizzard
6607 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && procSpell->SpellFamilyFlags & 0x0000000000000080LL)
6609 bool found = false;
6610 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6611 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6613 int32 script = (*i)->GetModifier()->m_miscvalue;
6614 if(script==836 || script==988 || script==989)
6616 found=true;
6617 break;
6620 if(!found)
6621 return false;
6623 break;
6625 // Astral Shift
6626 case 52179:
6628 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6629 return false;
6631 // Need stun, fear or silence mechanic
6632 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
6633 return false;
6634 break;
6636 // Burning Determination
6637 case 54748:
6639 if(!procSpell)
6640 return false;
6641 // Need Interrupt or Silenced mechanic
6642 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
6643 return false;
6644 break;
6646 // Lock and Load
6647 case 56453:
6649 // Proc only from trap activation (from periodic proc another aura of this spell)
6650 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
6651 return false;
6652 break;
6656 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6657 return false;
6659 // try detect target manually if not set
6660 if ( target == NULL )
6661 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6663 // default case
6664 if(!target || target!=this && !target->isAlive())
6665 return false;
6667 if(basepoints0)
6668 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6669 else
6670 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6672 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6673 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6675 return true;
6678 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6680 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6682 if(!pVictim || !pVictim->isAlive())
6683 return false;
6685 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6686 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6688 uint32 triggered_spell_id = 0;
6690 switch(scriptId)
6692 case 836: // Improved Blizzard (Rank 1)
6694 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6695 return false;
6696 triggered_spell_id = 12484;
6697 break;
6699 case 988: // Improved Blizzard (Rank 2)
6701 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6702 return false;
6703 triggered_spell_id = 12485;
6704 break;
6706 case 989: // Improved Blizzard (Rank 3)
6708 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6709 return false;
6710 triggered_spell_id = 12486;
6711 break;
6713 case 4086: // Improved Mend Pet (Rank 1)
6714 case 4087: // Improved Mend Pet (Rank 2)
6716 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6717 if(!roll_chance_i(chance))
6718 return false;
6720 triggered_spell_id = 24406;
6721 break;
6723 case 4533: // Dreamwalker Raiment 2 pieces bonus
6725 // Chance 50%
6726 if (!roll_chance_i(50))
6727 return false;
6729 switch (pVictim->getPowerType())
6731 case POWER_MANA: triggered_spell_id = 28722; break;
6732 case POWER_RAGE: triggered_spell_id = 28723; break;
6733 case POWER_ENERGY: triggered_spell_id = 28724; break;
6734 default:
6735 return false;
6737 break;
6739 case 4537: // Dreamwalker Raiment 6 pieces bonus
6740 triggered_spell_id = 28750; // Blessing of the Claw
6741 break;
6742 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6743 triggered_spell_id = 37445; // Mana Surge
6744 break;
6745 case 8152: // Serendipity
6747 // if heal your target over maximum health
6748 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6749 return false;
6750 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6751 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
6752 CastCustomSpell(this, 47762, &basepoints0, 0, 0, true, 0, triggeredByAura);
6753 return true;
6757 // not processed
6758 if(!triggered_spell_id)
6759 return false;
6761 // standard non-dummy case
6762 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6764 if(!triggerEntry)
6766 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6767 return false;
6770 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6771 return false;
6773 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6775 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6776 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6778 return true;
6781 void Unit::setPowerType(Powers new_powertype)
6783 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6785 if(GetTypeId() == TYPEID_PLAYER)
6787 if(((Player*)this)->GetGroup())
6788 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6790 else if(((Creature*)this)->isPet())
6792 Pet *pet = ((Pet*)this);
6793 if(pet->isControlled())
6795 Unit *owner = GetOwner();
6796 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6797 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6801 switch(new_powertype)
6803 default:
6804 case POWER_MANA:
6805 break;
6806 case POWER_RAGE:
6807 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6808 SetPower( POWER_RAGE,0);
6809 break;
6810 case POWER_FOCUS:
6811 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6812 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6813 break;
6814 case POWER_ENERGY:
6815 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6816 SetPower( POWER_ENERGY,0);
6817 break;
6818 case POWER_HAPPINESS:
6819 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6820 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6821 break;
6825 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6827 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6828 if(!entry)
6830 static uint64 guid = 0; // prevent repeating spam same faction problem
6832 if(GetGUID() != guid)
6834 if(GetTypeId() == TYPEID_PLAYER)
6835 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6836 else
6837 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6838 guid = GetGUID();
6841 return entry;
6844 bool Unit::IsHostileTo(Unit const* unit) const
6846 // always non-hostile to self
6847 if(unit==this)
6848 return false;
6850 // always non-hostile to GM in GM mode
6851 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6852 return false;
6854 // always hostile to enemy
6855 if(getVictim()==unit || unit->getVictim()==this)
6856 return true;
6858 // test pet/charm masters instead pers/charmeds
6859 Unit const* testerOwner = GetCharmerOrOwner();
6860 Unit const* targetOwner = unit->GetCharmerOrOwner();
6862 // always hostile to owner's enemy
6863 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6864 return true;
6866 // always hostile to enemy owner
6867 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6868 return true;
6870 // always hostile to owner of owner's enemy
6871 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6872 return true;
6874 Unit const* tester = testerOwner ? testerOwner : this;
6875 Unit const* target = targetOwner ? targetOwner : unit;
6877 // always non-hostile to target with common owner, or to owner/pet
6878 if(tester==target)
6879 return false;
6881 // special cases (Duel, etc)
6882 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6884 Player const* pTester = (Player const*)tester;
6885 Player const* pTarget = (Player const*)target;
6887 // Duel
6888 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6889 return true;
6891 // Group
6892 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6893 return false;
6895 // Sanctuary
6896 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6897 return false;
6899 // PvP FFA state
6900 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))
6901 return true;
6903 //= PvP states
6904 // Green/Blue (can't attack)
6905 if(pTester->GetTeam()==pTarget->GetTeam())
6906 return false;
6908 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6909 return pTester->IsPvP() && pTarget->IsPvP();
6912 // faction base cases
6913 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6914 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6915 if(!tester_faction || !target_faction)
6916 return false;
6918 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6919 return true;
6921 // PvC forced reaction and reputation case
6922 if(tester->GetTypeId()==TYPEID_PLAYER)
6924 // forced reaction
6925 ForcedReactions::const_iterator forceItr = ((Player*)tester)->m_forcedReactions.find(target_faction->faction);
6926 if(forceItr!=((Player*)tester)->m_forcedReactions.end())
6927 return forceItr->second <= REP_HOSTILE;
6929 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6930 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6931 if(raw_target_faction->reputationListID >=0)
6932 if(FactionState const* factionState = ((Player*)tester)->GetFactionState(raw_target_faction))
6933 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6935 // CvP forced reaction and reputation case
6936 else if(target->GetTypeId()==TYPEID_PLAYER)
6938 // forced reaction
6939 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
6940 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
6941 return forceItr->second <= REP_HOSTILE;
6943 // apply reputation state
6944 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6945 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6946 return ((Player const*)target)->GetReputationRank(raw_tester_faction) <= REP_HOSTILE;
6949 // common faction based case (CvC,PvC,CvP)
6950 return tester_faction->IsHostileTo(*target_faction);
6953 bool Unit::IsFriendlyTo(Unit const* unit) const
6955 // always friendly to self
6956 if(unit==this)
6957 return true;
6959 // always friendly to GM in GM mode
6960 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6961 return true;
6963 // always non-friendly to enemy
6964 if(getVictim()==unit || unit->getVictim()==this)
6965 return false;
6967 // test pet/charm masters instead pers/charmeds
6968 Unit const* testerOwner = GetCharmerOrOwner();
6969 Unit const* targetOwner = unit->GetCharmerOrOwner();
6971 // always non-friendly to owner's enemy
6972 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6973 return false;
6975 // always non-friendly to enemy owner
6976 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6977 return false;
6979 // always non-friendly to owner of owner's enemy
6980 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6981 return false;
6983 Unit const* tester = testerOwner ? testerOwner : this;
6984 Unit const* target = targetOwner ? targetOwner : unit;
6986 // always friendly to target with common owner, or to owner/pet
6987 if(tester==target)
6988 return true;
6990 // special cases (Duel)
6991 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6993 Player const* pTester = (Player const*)tester;
6994 Player const* pTarget = (Player const*)target;
6996 // Duel
6997 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
6998 return false;
7000 // Group
7001 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7002 return true;
7004 // Sanctuary
7005 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7006 return true;
7008 // PvP FFA state
7009 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))
7010 return false;
7012 //= PvP states
7013 // Green/Blue (non-attackable)
7014 if(pTester->GetTeam()==pTarget->GetTeam())
7015 return true;
7017 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7018 return !pTarget->IsPvP();
7021 // faction base cases
7022 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7023 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7024 if(!tester_faction || !target_faction)
7025 return false;
7027 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7028 return false;
7030 // PvC forced reaction and reputation case
7031 if(tester->GetTypeId()==TYPEID_PLAYER)
7033 // forced reaction
7034 ForcedReactions::const_iterator forceItr = ((Player const*)tester)->m_forcedReactions.find(target_faction->faction);
7035 if(forceItr!=((Player const*)tester)->m_forcedReactions.end())
7036 return forceItr->second >= REP_FRIENDLY;
7038 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7039 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7040 if(raw_target_faction->reputationListID >=0)
7041 if(FactionState const* FactionState = ((Player*)tester)->GetFactionState(raw_target_faction))
7042 return !(FactionState->Flags & FACTION_FLAG_AT_WAR);
7044 // CvP forced reaction and reputation case
7045 else if(target->GetTypeId()==TYPEID_PLAYER)
7047 // forced reaction
7048 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
7049 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
7050 return forceItr->second >= REP_FRIENDLY;
7052 // apply reputation state
7053 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7054 if(raw_tester_faction->reputationListID >=0 )
7055 return ((Player const*)target)->GetReputationRank(raw_tester_faction) >= REP_FRIENDLY;
7058 // common faction based case (CvC,PvC,CvP)
7059 return tester_faction->IsFriendlyTo(*target_faction);
7062 bool Unit::IsHostileToPlayers() const
7064 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7065 if(!my_faction)
7066 return false;
7068 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7069 if(raw_faction && raw_faction->reputationListID >=0 )
7070 return false;
7072 return my_faction->IsHostileToPlayers();
7075 bool Unit::IsNeutralToAll() const
7077 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7078 if(!my_faction)
7079 return true;
7081 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7082 if(raw_faction && raw_faction->reputationListID >=0 )
7083 return false;
7085 return my_faction->IsNeutralToAll();
7088 bool Unit::Attack(Unit *victim, bool meleeAttack)
7090 if(!victim || victim == this)
7091 return false;
7093 // dead units can neither attack nor be attacked
7094 if(!isAlive() || !victim->isAlive())
7095 return false;
7097 // player cannot attack in mount state
7098 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7099 return false;
7101 // nobody can attack GM in GM-mode
7102 if(victim->GetTypeId()==TYPEID_PLAYER)
7104 if(((Player*)victim)->isGameMaster())
7105 return false;
7107 else
7109 if(((Creature*)victim)->IsInEvadeMode())
7110 return false;
7113 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7114 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7115 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7117 if (m_attacking)
7119 if (m_attacking == victim)
7121 // switch to melee attack from ranged/magic
7122 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7124 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7125 SendAttackStart(victim);
7126 return true;
7128 return false;
7130 AttackStop();
7133 //Set our target
7134 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7136 if(meleeAttack)
7137 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7139 // set position before any AI calls/assistance
7140 if(GetTypeId()==TYPEID_UNIT)
7141 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7143 m_attacking = victim;
7144 m_attacking->_addAttacker(this);
7146 if(m_attacking->GetTypeId()==TYPEID_UNIT && ((Creature*)m_attacking)->AI())
7147 ((Creature*)m_attacking)->AI()->AttackedBy(this);
7149 if(GetTypeId()==TYPEID_UNIT)
7151 WorldPacket data(SMSG_AI_REACTION, 12);
7152 data << uint64(GetGUID());
7153 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7154 ((WorldObject*)this)->SendMessageToSet(&data, true);
7156 ((Creature*)this)->CallAssistance();
7159 // delay offhand weapon attack to next attack time
7160 if(haveOffhandWeapon())
7161 resetAttackTimer(OFF_ATTACK);
7163 if(meleeAttack)
7164 SendAttackStart(victim);
7166 return true;
7169 bool Unit::AttackStop()
7171 if (!m_attacking)
7172 return false;
7174 Unit* victim = m_attacking;
7176 m_attacking->_removeAttacker(this);
7177 m_attacking = NULL;
7179 //Clear our target
7180 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7182 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7184 InterruptSpell(CURRENT_MELEE_SPELL);
7186 if( GetTypeId()==TYPEID_UNIT )
7188 // reset call assistance
7189 ((Creature*)this)->SetNoCallAssistance(false);
7192 SendAttackStop(victim);
7194 return true;
7197 void Unit::CombatStop(bool cast)
7199 if(cast& IsNonMeleeSpellCasted(false))
7200 InterruptNonMeleeSpells(false);
7202 AttackStop();
7203 RemoveAllAttackers();
7204 if( GetTypeId()==TYPEID_PLAYER )
7205 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7206 ClearInCombat();
7209 void Unit::CombatStopWithPets(bool cast)
7211 CombatStop(cast);
7212 if(Pet* pet = GetPet())
7213 pet->CombatStop(cast);
7214 if(Unit* charm = GetCharm())
7215 charm->CombatStop(cast);
7216 if(GetTypeId()==TYPEID_PLAYER)
7218 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
7219 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
7220 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7221 guardian->CombatStop(cast);
7225 bool Unit::isAttackingPlayer() const
7227 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7228 return true;
7230 Pet* pet = GetPet();
7231 if(pet && pet->isAttackingPlayer())
7232 return true;
7234 Unit* charmed = GetCharm();
7235 if(charmed && charmed->isAttackingPlayer())
7236 return true;
7238 for (int8 i = 0; i < MAX_TOTEM; i++)
7240 if(m_TotemSlot[i])
7242 Creature *totem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
7243 if(totem && totem->isAttackingPlayer())
7244 return true;
7248 return false;
7251 void Unit::RemoveAllAttackers()
7253 while (!m_attackers.empty())
7255 AttackerSet::iterator iter = m_attackers.begin();
7256 if(!(*iter)->AttackStop())
7258 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7259 m_attackers.erase(iter);
7264 void Unit::ModifyAuraState(AuraState flag, bool apply)
7266 ApplyModFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1), apply);
7269 Unit *Unit::GetOwner() const
7271 uint64 ownerid = GetOwnerGUID();
7272 if(!ownerid)
7273 return NULL;
7274 return ObjectAccessor::GetUnit(*this, ownerid);
7277 Unit *Unit::GetCharmer() const
7279 if(uint64 charmerid = GetCharmerGUID())
7280 return ObjectAccessor::GetUnit(*this, charmerid);
7281 return NULL;
7284 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7286 uint64 guid = GetCharmerOrOwnerGUID();
7287 if(IS_PLAYER_GUID(guid))
7288 return ObjectAccessor::GetPlayer(*this, guid);
7290 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7293 Pet* Unit::GetPet() const
7295 if(uint64 pet_guid = GetPetGUID())
7297 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7298 return pet;
7300 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7301 const_cast<Unit*>(this)->SetPet(0);
7304 return NULL;
7307 Unit* Unit::GetCharm() const
7309 if(uint64 charm_guid = GetCharmGUID())
7311 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7312 return pet;
7314 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7315 const_cast<Unit*>(this)->SetCharm(0);
7318 return NULL;
7321 void Unit::SetPet(Pet* pet)
7323 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7325 // FIXME: hack, speed must be set only at follow
7326 if(pet)
7327 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7328 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7331 void Unit::SetCharm(Unit* pet)
7333 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7335 if(GetTypeId() == TYPEID_PLAYER)
7336 ((Player*)this)->m_mover = pet ? pet : this;
7339 void Unit::UnsummonAllTotems()
7341 for (int8 i = 0; i < MAX_TOTEM; ++i)
7343 if(!m_TotemSlot[i])
7344 continue;
7346 Creature *OldTotem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
7347 if (OldTotem && OldTotem->isTotem())
7348 ((Totem*)OldTotem)->UnSummon();
7352 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
7354 // we guess size
7355 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
7356 data.append(pVictim->GetPackGUID());
7357 data.append(GetPackGUID());
7358 data << uint32(SpellID);
7359 data << uint32(Damage);
7360 data << uint32(0); // over healing?
7361 data << uint8(critical ? 1 : 0);
7362 data << uint8(0); // unused in client?
7363 SendMessageToSet(&data, true);
7366 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
7368 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
7369 data.append(pVictim->GetPackGUID());
7370 data.append(GetPackGUID());
7371 data << uint32(SpellID);
7372 data << uint32(powertype);
7373 data << uint32(Damage);
7374 SendMessageToSet(&data, true);
7377 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
7379 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
7380 return pdamage;
7382 // For totems get damage bonus from owner (statue isn't totem in fact)
7383 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7385 if(Unit* owner = GetOwner())
7386 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
7389 // Taken/Done total percent damage auras
7390 float DoneTotalMod = 1.0f;
7391 float TakenTotalMod = 1.0f;
7392 int32 DoneTotal = 0;
7393 int32 TakenTotal = 0;
7395 // ..done
7396 // Pet damage
7397 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7398 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7400 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7401 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
7403 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
7404 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7405 // -1 == any item class (not wand then)
7406 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7407 // 0 == any inventory type (not wand then)
7409 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7413 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7414 // Add flat bonus from spell damage versus
7415 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7416 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7417 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7418 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7419 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7421 // done scripted mod (take it from owner)
7422 Unit *owner = GetOwner();
7423 if (!owner) owner = this;
7424 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7425 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7427 if (!(*i)->isAffectedOnSpell(spellProto))
7428 continue;
7429 switch((*i)->GetModifier()->m_miscvalue)
7431 case 4920: // Molten Fury
7432 case 4919:
7433 case 6917: // Death's Embrace
7434 case 6926:
7435 case 6928:
7437 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7438 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7439 break;
7441 // Soul Siphon
7442 case 4992:
7443 case 4993:
7445 // effect 1 m_amount
7446 int32 maxPercent = (*i)->GetModifier()->m_amount;
7447 // effect 0 m_amount
7448 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
7449 // count affliction effects and calc additional damage in percentage
7450 int32 modPercent = 0;
7451 AuraMap const& victimAuras = pVictim->GetAuras();
7452 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
7454 SpellEntry const* m_spell = itr->second->GetSpellProto();
7455 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & 0x0004071B8044C402LL))
7456 continue;
7457 modPercent += stepPercent * itr->second->GetStackAmount();
7458 if (modPercent >= maxPercent)
7460 modPercent = maxPercent;
7461 break;
7464 DoneTotalMod *= (modPercent+100.0f)/100.0f;
7465 break;
7467 case 6916: // Death's Embrace
7468 case 6925:
7469 case 6927:
7470 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
7471 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7472 break;
7473 case 5481: // Starfire Bonus
7475 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x0000000000200002LL))
7476 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7477 break;
7479 case 4418: // Increased Shock Damage
7480 case 4554: // Increased Lightning Damage
7481 case 4555: // Improved Moonfire
7482 case 5142: // Increased Lightning Damage
7483 case 5147: // Improved Consecration / Libram of Resurgence
7484 case 5148: // Idol of the Shooting Star
7485 case 6008: // Increased Lightning Damage / Totem of Hex
7487 DoneTotal+=(*i)->GetModifier()->m_amount;
7488 break;
7490 // Tundra Stalker
7491 // Merciless Combat
7492 case 7277:
7494 // Merciless Combat
7495 if ((*i)->GetSpellProto()->SpellIconID == 2656)
7497 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7498 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7500 else // Tundra Stalker
7502 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_DEATHKNIGHT, 0x0400000000000000LL))
7503 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7504 break;
7506 break;
7508 case 7293: // Rage of Rivendare
7510 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0x0200000000000000LL))
7511 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7512 break;
7514 // Twisted Faith
7515 case 7377:
7517 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x0000000000008000LL, 0, GetGUID()))
7518 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7519 break;
7521 // Marked for Death
7522 case 7598:
7523 case 7599:
7524 case 7600:
7525 case 7601:
7526 case 7602:
7528 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x0000000000000400LL))
7529 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7530 break;
7535 // Custom scripted damage
7536 // Ice Lance
7537 if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellIconID == 186)
7539 if (pVictim->isFrozen())
7540 DoneTotalMod *= 3.0f;
7543 // ..taken
7544 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7545 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7546 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
7547 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7549 // .. taken pct: dummy auras
7550 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7552 //Cheat Death
7553 if (Aura *dummy = pVictim->GetDummyAura(45182))
7555 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
7556 if (mod < dummy->GetModifier()->m_amount)
7557 mod = dummy->GetModifier()->m_amount;
7558 TakenTotalMod *= (mod+100.0f)/100.0f;
7562 // From caster spells
7563 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
7564 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
7565 if( (*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
7566 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7568 // Mod damage from spell mechanic
7569 uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
7570 if (mechanicMask)
7572 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
7573 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
7574 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
7575 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7578 // Taken/Done fixed damage bonus auras
7579 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
7580 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7582 // Pets just add their bonus damage to their spell damage
7583 // note that their spell damage is just gain of their own auras
7584 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
7585 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
7587 float LvlPenalty = CalculateLevelPenalty(spellProto);
7588 // Spellmod SpellDamage
7589 float SpellModSpellDamage = 100.0f;
7590 if(Player* modOwner = GetSpellModOwner())
7591 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7592 SpellModSpellDamage /= 100.0f;
7594 // Check for table values
7595 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
7596 if (bonus)
7598 float coeff;
7599 if (damagetype == DOT)
7600 coeff = bonus->dot_damage * LvlPenalty * stack;
7601 else
7602 coeff = bonus->direct_damage * LvlPenalty * stack;
7603 if (bonus->ap_bonus)
7604 DoneTotal+=bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack;
7605 DoneTotal += DoneAdvertisedBenefit * coeff * SpellModSpellDamage;
7606 TakenTotal+= TakenAdvertisedBenefit * coeff;
7608 // Default calculation
7609 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
7611 // Damage Done from spell damage bonus
7612 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
7613 // Damage over Time spells bonus calculation
7614 float DotFactor = 1.0f;
7615 if(damagetype == DOT)
7617 int32 DotDuration = GetSpellDuration(spellProto);
7618 // 200% limit
7619 if(DotDuration > 0)
7621 if(DotDuration > 30000) DotDuration = 30000;
7622 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7623 int x = 0;
7624 for(int j = 0; j < 3; j++)
7626 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7627 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
7628 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7630 x = j;
7631 break;
7634 int32 DotTicks = 6;
7635 if(spellProto->EffectAmplitude[x] != 0)
7636 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7637 if(DotTicks)
7639 DoneAdvertisedBenefit /= DotTicks*int32(stack);
7640 TakenAdvertisedBenefit /= DotTicks*int32(stack);
7644 // Distribute Damage over multiple effects, reduce by AoE
7645 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7646 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7647 for(int j = 0; j < 3; ++j)
7649 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7650 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7652 CastingTime /= 2;
7653 break;
7656 DoneTotal += DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage;
7657 TakenTotal+= TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
7660 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
7661 // apply spellmod to Done damage (flat and pct)
7662 if(Player* modOwner = GetSpellModOwner())
7663 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7665 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
7667 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7670 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7672 int32 DoneAdvertisedBenefit = 0;
7674 // ..done
7675 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7676 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7677 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7678 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7679 // -1 == any item class (not wand then)
7680 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7681 // 0 == any inventory type (not wand then)
7682 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7684 if (GetTypeId() == TYPEID_PLAYER)
7686 // Base value
7687 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellDamageBonus();
7689 // Damage bonus from stats
7690 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7691 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7693 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7695 // stat used stored in miscValueB for this aura
7696 Stats usedStat = Stats((*i)->GetMiscBValue());
7697 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7700 // ... and attack power
7701 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7702 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7703 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7704 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7707 return DoneAdvertisedBenefit;
7710 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7712 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7714 int32 TakenAdvertisedBenefit = 0;
7715 // ..done (for creature type by mask) in taken
7716 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7717 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7718 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7719 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7721 // ..taken
7722 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7723 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7724 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7725 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7727 return TakenAdvertisedBenefit;
7730 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7732 // not critting spell
7733 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7734 return false;
7736 float crit_chance = 0.0f;
7737 switch(spellProto->DmgClass)
7739 case SPELL_DAMAGE_CLASS_NONE:
7740 return false;
7741 case SPELL_DAMAGE_CLASS_MAGIC:
7743 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7744 crit_chance = 0.0f;
7745 // For other schools
7746 else if (GetTypeId() == TYPEID_PLAYER)
7747 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7748 else
7750 crit_chance = m_baseSpellCritChance;
7751 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7753 // taken
7754 if (pVictim)
7756 if (!IsPositiveSpell(spellProto->Id))
7758 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7759 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7760 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7761 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7762 // Modify by player victim resilience
7763 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7764 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7767 // scripted (increase crit chance ... against ... target by x%
7768 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7769 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7771 if (!((*i)->isAffectedOnSpell(spellProto)))
7772 continue;
7773 switch((*i)->GetModifier()->m_miscvalue)
7775 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
7776 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
7777 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
7778 case 7917: // Glyph of Shadowburn
7779 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7780 crit_chance+=(*i)->GetModifier()->m_amount;
7781 break;
7782 case 7997: // Renewed Hope
7783 case 7998:
7784 if (pVictim->HasAura(6788))
7785 crit_chance+=(*i)->GetModifier()->m_amount;
7786 break;
7787 case 21: // Test of Faith
7788 case 6935:
7789 case 6918:
7790 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
7791 crit_chance+=(*i)->GetModifier()->m_amount;
7792 break;
7793 default:
7794 break;
7797 // Custom crit by class
7798 switch(spellProto->SpellFamilyName)
7800 case SPELLFAMILY_PALADIN:
7801 // Sacred Shield
7802 if (spellProto->SpellFamilyFlags & 0x0000000040000000LL)
7804 Aura *aura = pVictim->GetDummyAura(58597);
7805 if (aura && aura->GetCasterGUID() == GetGUID())
7806 crit_chance+=aura->GetModifier()->m_amount;
7807 break;
7809 break;
7810 case SPELLFAMILY_SHAMAN:
7811 // Lava Burst
7812 if (spellProto->SpellFamilyFlags & 0x0000100000000000LL)
7814 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x0000000010000000LL, 0, GetGUID()))
7816 // Consume shock aura if not have Glyph of Flame Shock
7817 if (!GetAura(55447, 0))
7818 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
7819 return true;
7821 break;
7823 break;
7827 break;
7829 case SPELL_DAMAGE_CLASS_MELEE:
7830 case SPELL_DAMAGE_CLASS_RANGED:
7832 if (pVictim)
7834 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7835 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7837 break;
7839 default:
7840 return false;
7842 // percent done
7843 // only players use intelligence for critical chance computations
7844 if(Player* modOwner = GetSpellModOwner())
7845 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7847 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7848 if (roll_chance_f(crit_chance))
7849 return true;
7850 return false;
7853 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7855 // Calculate critical bonus
7856 int32 crit_bonus;
7857 switch(spellProto->DmgClass)
7859 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7860 case SPELL_DAMAGE_CLASS_RANGED:
7861 // TODO: write here full calculation for melee/ranged spells
7862 crit_bonus = damage;
7863 break;
7864 default:
7865 crit_bonus = damage / 2; // for spells is 50%
7866 break;
7869 // adds additional damage to crit_bonus (from talents)
7870 if(Player* modOwner = GetSpellModOwner())
7871 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
7873 if(pVictim)
7875 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7876 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7879 if(crit_bonus > 0)
7880 damage += crit_bonus;
7882 return damage;
7885 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7887 // Calculate critical bonus
7888 int32 crit_bonus;
7889 switch(spellProto->DmgClass)
7891 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7892 case SPELL_DAMAGE_CLASS_RANGED:
7893 // TODO: write here full calculation for melee/ranged spells
7894 crit_bonus = damage;
7895 break;
7896 default:
7897 crit_bonus = damage / 2; // for spells is 50%
7898 break;
7901 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_BONUS));
7903 if(pVictim)
7905 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7906 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7909 if(crit_bonus > 0)
7910 damage += crit_bonus;
7912 return damage;
7915 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
7917 // No heal amount for this class spells
7918 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
7919 return healamount;
7921 // For totems get healing bonus from owner (statue isn't totem in fact)
7922 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7923 if(Unit* owner = GetOwner())
7924 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
7926 // Healing Done
7927 // Taken/Done total percent damage auras
7928 float DoneTotalMod = 1.0f;
7929 float TakenTotalMod = 1.0f;
7930 int32 DoneTotal = 0;
7931 int32 TakenTotal = 0;
7933 // Healing done percent
7934 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
7935 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
7936 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
7938 // done scripted mod (take it from owner)
7939 Unit *owner = GetOwner();
7940 if (!owner) owner = this;
7941 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7942 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7944 if (!(*i)->isAffectedOnSpell(spellProto))
7945 continue;
7946 switch((*i)->GetModifier()->m_miscvalue)
7948 case 4415: // Increased Rejuvenation Healing
7949 case 4953:
7950 case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind
7951 DoneTotal+=(*i)->GetModifier()->m_amount;
7952 break;
7953 case 7997: // Renewed Hope
7954 case 7998:
7955 if (pVictim->HasAura(6788))
7956 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
7957 break;
7958 case 21: // Test of Faith
7959 case 6935:
7960 case 6918:
7961 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
7962 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
7963 break;
7964 case 7798: // Glyph of Regrowth
7966 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x0000000000000040LL))
7967 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7968 break;
7970 case 8477: // Nourish Heal Boost
7972 int32 stepPercent = (*i)->GetModifier()->m_amount;
7973 int32 modPercent = 0;
7974 AuraMap const& victimAuras = pVictim->GetAuras();
7975 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
7977 if (itr->second->GetCasterGUID()!=GetGUID())
7978 continue;
7979 SpellEntry const* m_spell = itr->second->GetSpellProto();
7980 if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
7981 !(m_spell->SpellFamilyFlags & 0x0000001000000050LL))
7982 continue;
7983 modPercent += stepPercent * itr->second->GetStackAmount();
7985 DoneTotalMod *= (modPercent+100.0f)/100.0f;
7986 break;
7988 case 7871: // Glyph of Lesser Healing Wave
7990 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x0000040000000000LL, 0, GetGUID()))
7991 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7992 break;
7994 default:
7995 break;
7999 // Taken/Done fixed damage bonus auras
8000 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
8001 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8003 float LvlPenalty = CalculateLevelPenalty(spellProto);
8004 // Spellmod SpellDamage
8005 float SpellModSpellDamage = 100.0f;
8006 if(Player* modOwner = GetSpellModOwner())
8007 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
8008 SpellModSpellDamage /= 100.0f;
8010 // Check for table values
8011 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8012 if (bonus)
8014 float coeff;
8015 if (damagetype == DOT)
8016 coeff = bonus->dot_damage * LvlPenalty * stack;
8017 else
8018 coeff = bonus->direct_damage * LvlPenalty * stack;
8019 if (bonus->ap_bonus)
8020 DoneTotal+=bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack;
8021 DoneTotal += DoneAdvertisedBenefit * coeff * SpellModSpellDamage;
8022 TakenTotal+= TakenAdvertisedBenefit * coeff;
8024 // Default calculation
8025 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8027 // Damage Done from spell damage bonus
8028 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8029 // Damage over Time spells bonus calculation
8030 float DotFactor = 1.0f;
8031 if(damagetype == DOT)
8033 int32 DotDuration = GetSpellDuration(spellProto);
8034 // 200% limit
8035 if(DotDuration > 0)
8037 if(DotDuration > 30000) DotDuration = 30000;
8038 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8039 int x = 0;
8040 for(int j = 0; j < 3; j++)
8042 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8043 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8044 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8046 x = j;
8047 break;
8050 int32 DotTicks = 6;
8051 if(spellProto->EffectAmplitude[x] != 0)
8052 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8053 if(DotTicks)
8055 DoneAdvertisedBenefit /= DotTicks*int32(stack);
8056 TakenAdvertisedBenefit /= DotTicks*int32(stack);
8060 // Distribute Damage over multiple effects, reduce by AoE
8061 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8062 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8063 for(int j = 0; j < 3; ++j)
8065 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8066 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8068 CastingTime /= 2;
8069 break;
8072 DoneTotal += DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f;
8073 TakenTotal+= TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f;
8076 // use float as more appropriate for negative values and percent applying
8077 float heal = (healamount + DoneTotal)*DoneTotalMod;
8078 // apply spellmod to Done amount
8079 if(Player* modOwner = GetSpellModOwner())
8080 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8082 // Taken mods
8083 // Healing Wave cast
8084 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
8086 // Search for Healing Way on Victim
8087 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8088 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8089 if((*itr)->GetId() == 29203)
8090 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
8093 // Healing taken percent
8094 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8095 if(minval)
8096 TakenTotalMod *= (100.0f + minval) / 100.0f;
8098 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8099 if(maxval)
8100 TakenTotalMod *= (100.0f + maxval) / 100.0f;
8102 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
8103 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
8104 if ((*i)->isAffectedOnSpell(spellProto))
8105 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8107 heal = (heal + TakenTotal) * TakenTotalMod;
8109 return heal < 0 ? 0 : uint32(heal);
8112 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8114 int32 AdvertisedBenefit = 0;
8116 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8117 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8118 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8119 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8121 // Healing bonus of spirit, intellect and strength
8122 if (GetTypeId() == TYPEID_PLAYER)
8124 // Base value
8125 AdvertisedBenefit +=((Player*)this)->GetBaseSpellHealingBonus();
8127 // Healing bonus from stats
8128 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8129 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8131 // stat used dependent from misc value (stat index)
8132 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8133 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8136 // ... and attack power
8137 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8138 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8139 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8140 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8142 return AdvertisedBenefit;
8145 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8147 int32 AdvertisedBenefit = 0;
8148 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8149 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8150 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8151 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8152 return AdvertisedBenefit;
8155 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8157 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8158 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8159 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8160 if(itr->type & shoolMask)
8161 return true;
8163 //If m_immuneToDamage type contain magic, IMMUNE damage.
8164 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8165 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8166 if(itr->type & shoolMask)
8167 return true;
8169 return false;
8172 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8174 if (!spellInfo)
8175 return false;
8177 //FIX ME this hack: don't get feared if stunned
8178 if (spellInfo->Mechanic == MECHANIC_FEAR )
8180 if ( hasUnitState(UNIT_STAT_STUNNED) )
8181 return true;
8184 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8185 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8186 if(itr->type == spellInfo->Dispel)
8187 return true;
8189 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8190 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8192 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8193 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8194 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8195 (itr->type & GetSpellSchoolMask(spellInfo)) )
8196 return true;
8199 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8200 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8202 if(itr->type == spellInfo->Mechanic)
8204 return true;
8208 return false;
8211 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
8213 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8214 uint32 effect = spellInfo->Effect[index];
8215 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8216 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8217 if(itr->type == effect)
8218 return true;
8220 if(uint32 mechanic = spellInfo->EffectMechanic[index])
8222 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8223 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8224 if(itr->type == mechanic)
8225 return true;
8228 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
8230 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
8231 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
8232 if(itr->type == aura)
8233 return true;
8234 // Check for immune to application of harmful magical effects
8235 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
8236 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
8237 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
8238 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
8239 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
8240 return true;
8243 return false;
8246 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8248 if(!spellInfo)
8249 return false;
8251 uint32 family = spellInfo->SpellFamilyName;
8252 uint64 flags = spellInfo->SpellFamilyFlags;
8254 if((family == 5 && flags == 256) || //Searing Pain
8255 (family == 6 && flags == 8192) || //Mind Blast
8256 (family == 11 && flags == 1048576)) //Earth Shock
8257 return true;
8259 return false;
8262 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8264 if(!pVictim)
8265 return;
8267 if(*pdamage == 0)
8268 return;
8270 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8272 // Taken/Done fixed damage bonus auras
8273 int32 DoneFlatBenefit = 0;
8274 int32 TakenFlatBenefit = 0;
8276 // ..done (for creature type by mask) in taken
8277 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8278 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8279 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8280 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
8282 // ..done
8283 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
8285 // ..done (base at attack power for marked target and base at attack power for creature type)
8286 int32 APbonus = 0;
8287 if(attType == RANGED_ATTACK)
8289 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
8291 // ..done (base at attack power and creature type)
8292 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
8293 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8294 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8295 APbonus += (*i)->GetModifier()->m_amount;
8297 else
8299 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
8301 // ..done (base at attack power and creature type)
8302 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
8303 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8304 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8305 APbonus += (*i)->GetModifier()->m_amount;
8308 if (APbonus!=0) // Can be negative
8310 bool normalized = false;
8311 if(spellProto)
8313 for (uint8 i = 0; i<3;i++)
8315 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
8317 normalized = true;
8318 break;
8323 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
8326 // ..taken
8327 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8328 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8329 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8330 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
8332 if(attType!=RANGED_ATTACK)
8333 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
8334 else
8335 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
8337 // Done/Taken total percent damage auras
8338 float DoneTotalMod = 1.0f;
8339 float TakenTotalMod = 1.0f;
8341 // ..done
8342 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
8343 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
8345 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8346 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8347 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8348 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8350 // ..taken
8351 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8352 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8353 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8354 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8356 // .. taken pct: dummy auras
8357 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8358 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
8360 switch((*i)->GetSpellProto()->SpellIconID)
8362 //Cheat Death
8363 case 2109:
8364 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
8366 if(pVictim->GetTypeId() != TYPEID_PLAYER)
8367 continue;
8368 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
8369 if (mod < (*i)->GetModifier()->m_amount)
8370 mod = (*i)->GetModifier()->m_amount;
8371 TakenTotalMod *= (mod+100.0f)/100.0f;
8373 break;
8374 //Mangle
8375 case 2312:
8376 if(spellProto==NULL)
8377 break;
8378 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
8379 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
8380 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8381 break;
8385 // .. taken pct: class scripts
8386 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8387 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
8389 switch((*i)->GetMiscValue())
8391 case 6427: case 6428: // Dirty Deeds
8392 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8394 Aura* eff0 = GetAura((*i)->GetId(),0);
8395 if(!eff0 || (*i)->GetEffIndex()!=1)
8397 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
8398 continue;
8401 // effect 0 have expected value but in negative state
8402 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
8404 break;
8408 if(attType != RANGED_ATTACK)
8410 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
8411 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
8412 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8414 else
8416 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
8417 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
8418 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8421 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
8423 // apply spellmod to Done damage
8424 if(spellProto)
8426 if(Player* modOwner = GetSpellModOwner())
8427 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
8430 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
8432 // bonus result can be negative
8433 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
8436 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
8438 if (apply)
8440 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
8442 next = itr; ++next;
8443 if(itr->type == type)
8445 m_spellImmune[op].erase(itr);
8446 next = m_spellImmune[op].begin();
8449 SpellImmune Immune;
8450 Immune.spellId = spellId;
8451 Immune.type = type;
8452 m_spellImmune[op].push_back(Immune);
8454 else
8456 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
8458 if(itr->spellId == spellId)
8460 m_spellImmune[op].erase(itr);
8461 break;
8468 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
8470 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
8472 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
8473 RemoveAurasWithDispelType(type);
8476 float Unit::GetWeaponProcChance() const
8478 // normalized proc chance for weapon attack speed
8479 // (odd formula...)
8480 if(isAttackReady(BASE_ATTACK))
8481 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
8482 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
8483 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
8484 return 0;
8487 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
8489 // proc per minute chance calculation
8490 if (PPM <= 0) return 0.0f;
8491 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
8492 return result;
8495 void Unit::Mount(uint32 mount)
8497 if(!mount)
8498 return;
8500 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
8502 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
8504 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8506 // unsummon pet
8507 if(GetTypeId() == TYPEID_PLAYER)
8509 Pet* pet = GetPet();
8510 if(pet)
8512 if(pet->isControlled())
8514 ((Player*)this)->SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
8515 ((Player*)this)->SetOldPetSpell(pet->GetUInt32Value(UNIT_CREATED_BY_SPELL));
8518 ((Player*)this)->RemovePet(NULL,PET_SAVE_NOT_IN_SLOT);
8520 else
8521 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8525 void Unit::Unmount()
8527 if(!IsMounted())
8528 return;
8530 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8532 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8533 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8535 // only resummon old pet if the player is already added to a map
8536 // this prevents adding a pet to a not created map which would otherwise cause a crash
8537 // (it could probably happen when logging in after a previous crash)
8538 if(GetTypeId() == TYPEID_PLAYER && IsInWorld() && ((Player*)this)->GetTemporaryUnsummonedPetNumber() && isAlive())
8540 Pet* NewPet = new Pet;
8541 if(!NewPet->LoadPetFromDB((Player*)this, 0, ((Player*)this)->GetTemporaryUnsummonedPetNumber(), true))
8542 delete NewPet;
8544 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8548 void Unit::SetInCombatWith(Unit* enemy)
8550 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8551 if(eOwner->IsPvP())
8553 SetInCombatState(true);
8554 return;
8557 //check for duel
8558 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8560 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8561 if(((Player const*)eOwner)->duel->opponent == myOwner)
8563 SetInCombatState(true);
8564 return;
8567 SetInCombatState(false);
8570 void Unit::SetInCombatState(bool PvP)
8572 // only alive units can be in combat
8573 if(!isAlive())
8574 return;
8576 if(PvP)
8577 m_CombatTimer = 5000;
8578 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8580 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8581 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8584 void Unit::ClearInCombat()
8586 m_CombatTimer = 0;
8587 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8589 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8590 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8592 // Player's state will be cleared in Player::UpdateContestedPvP
8593 if(GetTypeId()!=TYPEID_PLAYER)
8594 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8597 bool Unit::isTargetableForAttack() const
8599 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8600 return false;
8602 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8603 return false;
8605 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8608 int32 Unit::ModifyHealth(int32 dVal)
8610 int32 gain = 0;
8612 if(dVal==0)
8613 return 0;
8615 int32 curHealth = (int32)GetHealth();
8617 int32 val = dVal + curHealth;
8618 if(val <= 0)
8620 SetHealth(0);
8621 return -curHealth;
8624 int32 maxHealth = (int32)GetMaxHealth();
8626 if(val < maxHealth)
8628 SetHealth(val);
8629 gain = val - curHealth;
8631 else if(curHealth != maxHealth)
8633 SetHealth(maxHealth);
8634 gain = maxHealth - curHealth;
8637 return gain;
8640 int32 Unit::ModifyPower(Powers power, int32 dVal)
8642 int32 gain = 0;
8644 if(dVal==0)
8645 return 0;
8647 int32 curPower = (int32)GetPower(power);
8649 int32 val = dVal + curPower;
8650 if(val <= 0)
8652 SetPower(power,0);
8653 return -curPower;
8656 int32 maxPower = (int32)GetMaxPower(power);
8658 if(val < maxPower)
8660 SetPower(power,val);
8661 gain = val - curPower;
8663 else if(curPower != maxPower)
8665 SetPower(power,maxPower);
8666 gain = maxPower - curPower;
8669 return gain;
8672 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8674 if(!u)
8675 return false;
8677 // Always can see self
8678 if (u==this)
8679 return true;
8681 // player visible for other player if not logout and at same transport
8682 // including case when player is out of world
8683 bool at_same_transport =
8684 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8685 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8686 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8687 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8689 // not in world
8690 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8691 return false;
8693 // forbidden to seen (at GM respawn command)
8694 if(m_Visibility==VISIBILITY_RESPAWN)
8695 return false;
8697 // always seen by owner
8698 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8699 return true;
8701 // Grid dead/alive checks
8702 if( u->GetTypeId()==TYPEID_PLAYER)
8704 // non visible at grid for any stealth state
8705 if(!IsVisibleInGridForPlayer((Player *)u))
8706 return false;
8708 // if player is dead then he can't detect anyone in any cases
8709 if(!u->isAlive())
8710 detect = false;
8712 else
8714 // all dead creatures/players not visible for any creatures
8715 if(!u->isAlive() || !isAlive())
8716 return false;
8719 // different visible distance checks
8720 if(u->isInFlight()) // what see player in flight
8722 // use object grey distance for all (only see objects any way)
8723 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8724 return false;
8726 else if(!isAlive()) // distance for show body
8728 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8729 return false;
8731 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8733 if(u->GetTypeId()==TYPEID_PLAYER)
8735 // Players far than max visible distance for player or not in our map are not visible too
8736 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8737 return false;
8739 else
8741 // Units far than max visible distance for creature or not in our map are not visible too
8742 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8743 return false;
8746 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8748 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8749 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8750 return false;
8752 else // distance for show creature
8754 // Units far than max visible distance for creature or not in our map are not visible too
8755 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8756 return false;
8759 // Visible units, always are visible for all units, except for units under invisibility and phases
8760 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
8761 return true;
8763 // GMs see any players, not higher GMs and all units in any phase
8764 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8766 if(GetTypeId() == TYPEID_PLAYER)
8767 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8768 else
8769 return true;
8772 // non faction visibility non-breakable for non-GMs
8773 if (m_Visibility == VISIBILITY_OFF)
8774 return false;
8776 // phased visibility (both must phased in same way)
8777 if(!InSamePhase(u))
8778 return false;
8780 // raw invisibility
8781 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8783 // detectable invisibility case
8784 if( invisible && (
8785 // Invisible units, always are visible for units under same invisibility type
8786 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8787 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8788 u->canDetectInvisibilityOf(this) ||
8789 // Units that can detect invisibility always are visible for units that can be detected
8790 canDetectInvisibilityOf(u) ))
8792 invisible = false;
8795 // special cases for always overwrite invisibility/stealth
8796 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8798 // non-hostile case
8799 if (!u->IsHostileTo(this))
8801 // 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)
8802 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8804 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8805 return true;
8807 // else apply same rules as for hostile case (detecting check for stealth)
8810 // hostile case
8811 else
8813 // Hunter mark functionality
8814 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8815 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8816 if((*iter)->GetCasterGUID()==u->GetGUID())
8817 return true;
8819 // else apply detecting check for stealth
8822 // none other cases for detect invisibility, so invisible
8823 if(invisible)
8824 return false;
8826 // else apply stealth detecting check
8829 // unit got in stealth in this moment and must ignore old detected state
8830 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8831 return false;
8833 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8834 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8835 return true;
8837 // NOW ONLY STEALTH CASE
8839 // stealth and detected and visible for some seconds
8840 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8841 return true;
8843 //if in non-detect mode then invisible for unit
8844 if (!detect)
8845 return false;
8847 // Special cases
8849 // If is attacked then stealth is lost, some creature can use stealth too
8850 if( !getAttackers().empty() )
8851 return true;
8853 // If there is collision rogue is seen regardless of level difference
8854 // TODO: check sizes in DB
8855 float distance = GetDistance(u);
8856 if (distance < 0.24f)
8857 return true;
8859 //If a mob or player is stunned he will not be able to detect stealth
8860 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8861 return false;
8863 // Creature can detect target only in aggro radius
8864 if(u->GetTypeId() != TYPEID_PLAYER)
8866 //Always invisible from back and out of aggro range
8867 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
8868 if(!isInFront)
8869 return false;
8871 else
8873 //Always invisible from back
8874 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
8875 if(!isInFront)
8876 return false;
8879 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
8880 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
8882 //Calculation if target is in front
8884 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
8885 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
8887 //Visible distance is modified by
8888 //-Level Diff (every level diff = 1.0f in visible distance)
8889 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
8891 //This allows to check talent tree and will add addition stealth dependent on used points)
8892 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
8893 if(stealthMod < 0)
8894 stealthMod = 0;
8896 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
8897 //based on wowwiki every 5 mod we have 1 more level diff in calculation
8898 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
8900 if(distance > visibleDistance)
8901 return false;
8904 // Now check is target visible with LoS
8905 float ox,oy,oz;
8906 u->GetPosition(ox,oy,oz);
8907 return IsWithinLOS(ox,oy,oz);
8910 void Unit::SetVisibility(UnitVisibility x)
8912 m_Visibility = x;
8914 if(IsInWorld())
8916 Map *m = GetMap();
8918 if(GetTypeId()==TYPEID_PLAYER)
8919 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8920 else
8921 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8925 bool Unit::canDetectInvisibilityOf(Unit const* u) const
8927 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
8929 for(uint32 i = 0; i < 10; ++i)
8931 if(((1 << i) & mask)==0)
8932 continue;
8934 // find invisibility level
8935 uint32 invLevel = 0;
8936 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
8937 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
8938 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
8939 invLevel = (*itr)->GetModifier()->m_amount;
8941 // find invisibility detect level
8942 uint32 detectLevel = 0;
8943 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
8944 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
8945 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
8946 detectLevel = (*itr)->GetModifier()->m_amount;
8948 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
8950 detectLevel = ((Player*)this)->GetDrunkValue();
8953 if(invLevel <= detectLevel)
8954 return true;
8958 return false;
8961 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
8963 int32 main_speed_mod = 0;
8964 float stack_bonus = 1.0f;
8965 float non_stack_bonus = 1.0f;
8967 switch(mtype)
8969 case MOVE_WALK:
8970 return;
8971 case MOVE_RUN:
8973 if (IsMounted()) // Use on mount auras
8975 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
8976 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
8977 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
8979 else
8981 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
8982 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
8983 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
8985 break;
8987 case MOVE_RUN_BACK:
8988 return;
8989 case MOVE_SWIM:
8991 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
8992 break;
8994 case MOVE_SWIM_BACK:
8995 return;
8996 case MOVE_FLIGHT:
8998 if (IsMounted()) // Use on mount auras
8999 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
9000 else // Use not mount (shapeshift for example) auras (should stack)
9001 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
9002 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
9003 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
9004 break;
9006 case MOVE_FLIGHT_BACK:
9007 return;
9008 default:
9009 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
9010 return;
9013 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
9014 // now we ready for speed calculation
9015 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
9017 switch(mtype)
9019 case MOVE_RUN:
9020 case MOVE_SWIM:
9021 case MOVE_FLIGHT:
9023 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
9024 // TODO: possible affect only on MOVE_RUN
9025 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
9027 // Use speed from aura
9028 float max_speed = normalization / baseMoveSpeed[mtype];
9029 if (speed > max_speed)
9030 speed = max_speed;
9032 break;
9034 default:
9035 break;
9038 // Apply strongest slow aura mod to speed
9039 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
9040 if (slow)
9041 speed *=(100.0f + slow)/100.0f;
9042 SetSpeed(mtype, speed, forced);
9045 float Unit::GetSpeed( UnitMoveType mtype ) const
9047 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
9050 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
9052 if (rate < 0)
9053 rate = 0.0f;
9055 // Update speed only on change
9056 if (m_speed_rate[mtype] == rate)
9057 return;
9059 m_speed_rate[mtype] = rate;
9061 propagateSpeedChange();
9063 WorldPacket data;
9064 if(!forced)
9066 switch(mtype)
9068 case MOVE_WALK:
9069 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9070 break;
9071 case MOVE_RUN:
9072 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
9073 break;
9074 case MOVE_RUN_BACK:
9075 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9076 break;
9077 case MOVE_SWIM:
9078 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9079 break;
9080 case MOVE_SWIM_BACK:
9081 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9082 break;
9083 case MOVE_TURN_RATE:
9084 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9085 break;
9086 case MOVE_FLIGHT:
9087 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9088 break;
9089 case MOVE_FLIGHT_BACK:
9090 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9091 break;
9092 case MOVE_PITCH_RATE:
9093 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9094 break;
9095 default:
9096 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9097 return;
9100 data.append(GetPackGUID());
9101 data << uint32(0); // movement flags
9102 data << uint16(0); // unk flags
9103 data << uint32(getMSTime());
9104 data << float(GetPositionX());
9105 data << float(GetPositionY());
9106 data << float(GetPositionZ());
9107 data << float(GetOrientation());
9108 data << uint32(0); // fall time
9109 data << float(GetSpeed(mtype));
9110 SendMessageToSet( &data, true );
9112 else
9114 if(GetTypeId() == TYPEID_PLAYER)
9116 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9117 // and do it only for real sent packets and use run for run/mounted as client expected
9118 ++((Player*)this)->m_forced_speed_changes[mtype];
9121 switch(mtype)
9123 case MOVE_WALK:
9124 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9125 break;
9126 case MOVE_RUN:
9127 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9128 break;
9129 case MOVE_RUN_BACK:
9130 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9131 break;
9132 case MOVE_SWIM:
9133 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9134 break;
9135 case MOVE_SWIM_BACK:
9136 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9137 break;
9138 case MOVE_TURN_RATE:
9139 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9140 break;
9141 case MOVE_FLIGHT:
9142 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9143 break;
9144 case MOVE_FLIGHT_BACK:
9145 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9146 break;
9147 case MOVE_PITCH_RATE:
9148 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9149 break;
9150 default:
9151 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9152 return;
9154 data.append(GetPackGUID());
9155 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9156 if (mtype == MOVE_RUN)
9157 data << uint8(0); // new 2.1.0
9158 data << float(GetSpeed(mtype));
9159 SendMessageToSet( &data, true );
9161 if(Pet* pet = GetPet())
9162 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9165 void Unit::SetHover(bool on)
9167 if(on)
9168 CastSpell(this,11010,true);
9169 else
9170 RemoveAurasDueToSpell(11010);
9173 void Unit::setDeathState(DeathState s)
9175 if (s != ALIVE && s!= JUST_ALIVED)
9177 CombatStop();
9178 DeleteThreatList();
9179 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9181 if(IsNonMeleeSpellCasted(false))
9182 InterruptNonMeleeSpells(false);
9185 if (s == JUST_DIED)
9187 RemoveAllAurasOnDeath();
9188 UnsummonAllTotems();
9190 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9191 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9192 // remove aurastates allowing special moves
9193 ClearAllReactives();
9194 ClearDiminishings();
9196 else if(s == JUST_ALIVED)
9198 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9201 if (m_deathState != ALIVE && s == ALIVE)
9203 //_ApplyAllAuraMods();
9205 m_deathState = s;
9208 /*########################################
9209 ######## ########
9210 ######## AGGRO SYSTEM ########
9211 ######## ########
9212 ########################################*/
9213 bool Unit::CanHaveThreatList() const
9215 // only creatures can have threat list
9216 if( GetTypeId() != TYPEID_UNIT )
9217 return false;
9219 // only alive units can have threat list
9220 if( !isAlive() )
9221 return false;
9223 // totems can not have threat list
9224 if( ((Creature*)this)->isTotem() )
9225 return false;
9227 // vehicles can not have threat list
9228 if( ((Creature*)this)->isVehicle() )
9229 return false;
9231 // pets can not have a threat list, unless they are controlled by a creature
9232 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9233 return false;
9235 return true;
9238 //======================================================================
9240 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9242 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9243 return threat;
9245 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9247 return threat * m_threatModifier[school];
9250 //======================================================================
9252 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9254 // Only mobs can manage threat lists
9255 if(CanHaveThreatList())
9256 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9259 //======================================================================
9261 void Unit::DeleteThreatList()
9263 m_ThreatManager.clearReferences();
9266 //======================================================================
9268 void Unit::TauntApply(Unit* taunter)
9270 assert(GetTypeId()== TYPEID_UNIT);
9272 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9273 return;
9275 if(!CanHaveThreatList())
9276 return;
9278 Unit *target = getVictim();
9279 if(target && target == taunter)
9280 return;
9282 SetInFront(taunter);
9283 if (((Creature*)this)->AI())
9284 ((Creature*)this)->AI()->AttackStart(taunter);
9286 m_ThreatManager.tauntApply(taunter);
9289 //======================================================================
9291 void Unit::TauntFadeOut(Unit *taunter)
9293 assert(GetTypeId()== TYPEID_UNIT);
9295 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9296 return;
9298 if(!CanHaveThreatList())
9299 return;
9301 Unit *target = getVictim();
9302 if(!target || target != taunter)
9303 return;
9305 if(m_ThreatManager.isThreatListEmpty())
9307 if(((Creature*)this)->AI())
9308 ((Creature*)this)->AI()->EnterEvadeMode();
9309 return;
9312 m_ThreatManager.tauntFadeOut(taunter);
9313 target = m_ThreatManager.getHostilTarget();
9315 if (target && target != taunter)
9317 SetInFront(target);
9318 if (((Creature*)this)->AI())
9319 ((Creature*)this)->AI()->AttackStart(target);
9323 //======================================================================
9325 bool Unit::SelectHostilTarget()
9327 //function provides main threat functionality
9328 //next-victim-selection algorithm and evade mode are called
9329 //threat list sorting etc.
9331 assert(GetTypeId()== TYPEID_UNIT);
9333 if (!this->isAlive())
9334 return false;
9335 //This function only useful once AI has been initialized
9336 if (!((Creature*)this)->AI())
9337 return false;
9339 Unit* target = NULL;
9341 // First checking if we have some taunt on us
9342 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
9343 if ( !tauntAuras.empty() )
9345 Unit* caster;
9347 // The last taunt aura caster is alive an we are happy to attack him
9348 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
9349 return true;
9350 else if (tauntAuras.size() > 1)
9352 // We do not have last taunt aura caster but we have more taunt auras,
9353 // so find first available target
9355 // Auras are pushed_back, last caster will be on the end
9356 AuraList::const_iterator aura = --tauntAuras.end();
9359 --aura;
9360 if ( (caster = (*aura)->GetCaster()) &&
9361 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
9363 target = caster;
9364 break;
9366 }while (aura != tauntAuras.begin());
9370 if ( !target && !m_ThreatManager.isThreatListEmpty() )
9371 // No taunt aura or taunt aura caster is dead standart target selection
9372 target = m_ThreatManager.getHostilTarget();
9374 if(target)
9376 if(!hasUnitState(UNIT_STAT_STUNNED))
9377 SetInFront(target);
9378 ((Creature*)this)->AI()->AttackStart(target);
9379 return true;
9382 // no target but something prevent go to evade mode
9383 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
9384 return false;
9386 // last case when creature don't must go to evade mode:
9387 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
9388 // for example at owner command to pet attack some far away creature
9389 // Note: creature not have targeted movement generator but have attacker in this case
9390 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
9392 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
9394 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
9395 return false;
9399 // enter in evade mode in other case
9400 ((Creature*)this)->AI()->EnterEvadeMode();
9402 return false;
9405 //======================================================================
9406 //======================================================================
9407 //======================================================================
9409 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
9411 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9413 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9415 int32 level = int32(getLevel());
9416 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
9417 level = (int32)spellProto->maxLevel;
9418 else if (level < (int32)spellProto->baseLevel)
9419 level = (int32)spellProto->baseLevel;
9420 level-= (int32)spellProto->spellLevel;
9422 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
9423 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
9424 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
9425 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
9426 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
9428 // range can have possitive and negative values, so order its for irand
9429 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
9430 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
9431 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
9433 int32 value = basePoints + randvalue;
9434 //random damage
9435 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
9436 value += (int32)(comboDamage * comboPoints);
9438 if(Player* modOwner = GetSpellModOwner())
9440 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
9441 switch(effect_index)
9443 case 0:
9444 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
9445 break;
9446 case 1:
9447 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
9448 break;
9449 case 2:
9450 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
9451 break;
9455 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
9456 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
9457 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
9458 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
9460 return value;
9463 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
9465 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9467 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9469 int32 minduration = GetSpellDuration(spellProto);
9470 int32 maxduration = GetSpellMaxDuration(spellProto);
9472 int32 duration;
9474 if( minduration != -1 && minduration != maxduration )
9475 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
9476 else
9477 duration = minduration;
9479 if (duration > 0)
9481 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
9482 // Find total mod value (negative bonus)
9483 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
9484 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
9485 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
9486 // Find max mod (negative bonus)
9487 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
9489 int32 durationMod = 0;
9490 // Select strongest negative mod
9491 if (durationMod_always > durationMod_not_stack)
9492 durationMod = durationMod_not_stack;
9493 else
9494 durationMod = durationMod_always;
9496 if (durationMod != 0)
9497 duration = int32(int64(duration) * (100+durationMod) /100);
9499 if (duration < 0) duration = 0;
9502 return duration;
9505 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
9507 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9509 if(i->DRGroup != group)
9510 continue;
9512 if(!i->hitCount)
9513 return DIMINISHING_LEVEL_1;
9515 if(!i->hitTime)
9516 return DIMINISHING_LEVEL_1;
9518 // If last spell was casted more than 15 seconds ago - reset the count.
9519 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
9521 i->hitCount = DIMINISHING_LEVEL_1;
9522 return DIMINISHING_LEVEL_1;
9524 // or else increase the count.
9525 else
9527 return DiminishingLevels(i->hitCount);
9530 return DIMINISHING_LEVEL_1;
9533 void Unit::IncrDiminishing(DiminishingGroup group)
9535 // Checking for existing in the table
9536 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9538 if(i->DRGroup != group)
9539 continue;
9540 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
9541 i->hitCount += 1;
9542 return;
9544 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9547 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9549 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9550 return;
9552 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9553 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9555 // test pet/charm masters instead pets/charmeds
9556 Unit const* targetOwner = GetCharmerOrOwner();
9557 Unit const* casterOwner = caster->GetCharmerOrOwner();
9559 Unit const* target = targetOwner ? targetOwner : this;
9560 Unit const* source = casterOwner ? casterOwner : caster;
9562 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9563 duration = 10000;
9566 float mod = 1.0f;
9568 // Some diminishings applies to mobs too (for example, Stun)
9569 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9571 DiminishingLevels diminish = Level;
9572 switch(diminish)
9574 case DIMINISHING_LEVEL_1: break;
9575 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9576 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9577 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9578 default: break;
9582 duration = int32(duration * mod);
9585 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9587 // Checking for existing in the table
9588 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9590 if(i->DRGroup != group)
9591 continue;
9593 if(apply)
9594 i->stack += 1;
9595 else if(i->stack)
9597 i->stack -= 1;
9598 // Remember time after last aura from group removed
9599 if (i->stack == 0)
9600 i->hitTime = getMSTime();
9602 break;
9606 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9608 return ObjectAccessor::GetUnit(object,guid);
9611 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9613 return isVisibleForOrDetect(u, false, inVisibleList, false);
9616 uint32 Unit::GetCreatureType() const
9618 if(GetTypeId() == TYPEID_PLAYER)
9620 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(((Player*)this)->m_form);
9621 if(ssEntry && ssEntry->creatureType > 0)
9622 return ssEntry->creatureType;
9623 else
9624 return CREATURE_TYPE_HUMANOID;
9626 else
9627 return ((Creature*)this)->GetCreatureInfo()->type;
9630 /*#######################################
9631 ######## ########
9632 ######## STAT SYSTEM ########
9633 ######## ########
9634 #######################################*/
9636 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9638 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9640 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9641 return false;
9644 float val = 1.0f;
9646 switch(modifierType)
9648 case BASE_VALUE:
9649 case TOTAL_VALUE:
9650 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9651 break;
9652 case BASE_PCT:
9653 case TOTAL_PCT:
9654 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9655 amount = -200.0f;
9657 val = (100.0f + amount) / 100.0f;
9658 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9659 break;
9661 default:
9662 break;
9665 if(!CanModifyStats())
9666 return false;
9668 switch(unitMod)
9670 case UNIT_MOD_STAT_STRENGTH:
9671 case UNIT_MOD_STAT_AGILITY:
9672 case UNIT_MOD_STAT_STAMINA:
9673 case UNIT_MOD_STAT_INTELLECT:
9674 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9676 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9677 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9679 case UNIT_MOD_MANA:
9680 case UNIT_MOD_RAGE:
9681 case UNIT_MOD_FOCUS:
9682 case UNIT_MOD_ENERGY:
9683 case UNIT_MOD_HAPPINESS:
9684 case UNIT_MOD_RUNE:
9685 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9687 case UNIT_MOD_RESISTANCE_HOLY:
9688 case UNIT_MOD_RESISTANCE_FIRE:
9689 case UNIT_MOD_RESISTANCE_NATURE:
9690 case UNIT_MOD_RESISTANCE_FROST:
9691 case UNIT_MOD_RESISTANCE_SHADOW:
9692 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9694 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9695 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9697 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9698 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9699 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9701 default:
9702 break;
9705 return true;
9708 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9710 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9712 sLog.outError("ERROR: trial to access non existed modifier value from UnitMods!");
9713 return 0.0f;
9716 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9717 return 0.0f;
9719 return m_auraModifiersGroup[unitMod][modifierType];
9722 float Unit::GetTotalStatValue(Stats stat) const
9724 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9726 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9727 return 0.0f;
9729 // value = ((base_value * base_pct) + total_value) * total_pct
9730 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9731 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9732 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9733 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9735 return value;
9738 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9740 if(unitMod >= UNIT_MOD_END)
9742 sLog.outError("ERROR: trial to access non existed UnitMods in GetTotalAuraModValue()!");
9743 return 0.0f;
9746 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9747 return 0.0f;
9749 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9750 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9751 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9752 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9754 return value;
9757 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9759 SpellSchools school = SPELL_SCHOOL_NORMAL;
9761 switch(unitMod)
9763 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9764 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9765 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9766 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9767 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9768 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9770 default:
9771 break;
9774 return school;
9777 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9779 Stats stat = STAT_STRENGTH;
9781 switch(unitMod)
9783 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9784 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9785 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9786 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9787 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9789 default:
9790 break;
9793 return stat;
9796 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9798 switch(unitMod)
9800 case UNIT_MOD_MANA: return POWER_MANA;
9801 case UNIT_MOD_RAGE: return POWER_RAGE;
9802 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9803 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9804 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9805 case UNIT_MOD_RUNE: return POWER_RUNE;
9806 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9809 return POWER_MANA;
9812 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9814 if (attType == RANGED_ATTACK)
9816 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
9817 if (ap < 0)
9818 return 0.0f;
9819 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
9821 else
9823 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
9824 if (ap < 0)
9825 return 0.0f;
9826 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
9830 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9832 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9833 return 0.0f;
9835 return m_weaponDamage[attType][type];
9838 void Unit::SetLevel(uint32 lvl)
9840 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9842 // group update
9843 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9844 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9847 void Unit::SetHealth(uint32 val)
9849 uint32 maxHealth = GetMaxHealth();
9850 if(maxHealth < val)
9851 val = maxHealth;
9853 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9855 // group update
9856 if(GetTypeId() == TYPEID_PLAYER)
9858 if(((Player*)this)->GetGroup())
9859 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9861 else if(((Creature*)this)->isPet())
9863 Pet *pet = ((Pet*)this);
9864 if(pet->isControlled())
9866 Unit *owner = GetOwner();
9867 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9868 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
9873 void Unit::SetMaxHealth(uint32 val)
9875 uint32 health = GetHealth();
9876 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
9878 // group update
9879 if(GetTypeId() == TYPEID_PLAYER)
9881 if(((Player*)this)->GetGroup())
9882 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
9884 else if(((Creature*)this)->isPet())
9886 Pet *pet = ((Pet*)this);
9887 if(pet->isControlled())
9889 Unit *owner = GetOwner();
9890 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9891 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
9895 if(val < health)
9896 SetHealth(val);
9899 void Unit::SetPower(Powers power, uint32 val)
9901 if(GetPower(power) == val)
9902 return;
9904 uint32 maxPower = GetMaxPower(power);
9905 if(maxPower < val)
9906 val = maxPower;
9908 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
9910 WorldPacket data(SMSG_POWER_UPDATE);
9911 data.append(GetPackGUID());
9912 data << uint8(power);
9913 data << uint32(val);
9914 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
9916 // group update
9917 if(GetTypeId() == TYPEID_PLAYER)
9919 if(((Player*)this)->GetGroup())
9920 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9922 else if(((Creature*)this)->isPet())
9924 Pet *pet = ((Pet*)this);
9925 if(pet->isControlled())
9927 Unit *owner = GetOwner();
9928 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9929 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9932 // Update the pet's character sheet with happiness damage bonus
9933 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
9935 pet->UpdateDamagePhysical(BASE_ATTACK);
9940 void Unit::SetMaxPower(Powers power, uint32 val)
9942 uint32 cur_power = GetPower(power);
9943 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
9945 // group update
9946 if(GetTypeId() == TYPEID_PLAYER)
9948 if(((Player*)this)->GetGroup())
9949 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9951 else if(((Creature*)this)->isPet())
9953 Pet *pet = ((Pet*)this);
9954 if(pet->isControlled())
9956 Unit *owner = GetOwner();
9957 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9958 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
9962 if(val < cur_power)
9963 SetPower(power, val);
9966 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
9968 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
9970 // group update
9971 if(GetTypeId() == TYPEID_PLAYER)
9973 if(((Player*)this)->GetGroup())
9974 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9976 else if(((Creature*)this)->isPet())
9978 Pet *pet = ((Pet*)this);
9979 if(pet->isControlled())
9981 Unit *owner = GetOwner();
9982 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9983 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9988 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
9990 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
9992 // group update
9993 if(GetTypeId() == TYPEID_PLAYER)
9995 if(((Player*)this)->GetGroup())
9996 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9998 else if(((Creature*)this)->isPet())
10000 Pet *pet = ((Pet*)this);
10001 if(pet->isControlled())
10003 Unit *owner = GetOwner();
10004 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10005 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10010 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
10012 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
10013 if(apply)
10014 tAuraProcTriggerDamage.push_back(aura);
10015 else
10016 tAuraProcTriggerDamage.remove(aura);
10019 uint32 Unit::GetCreatePowers( Powers power ) const
10021 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
10022 switch(power)
10024 case POWER_MANA: return GetCreateMana();
10025 case POWER_RAGE: return 1000;
10026 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
10027 case POWER_ENERGY: return 100;
10028 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
10029 case POWER_RUNIC_POWER: return 1000;
10032 return 0;
10035 void Unit::AddToWorld()
10037 Object::AddToWorld();
10040 void Unit::RemoveFromWorld()
10042 // cleanup
10043 if(IsInWorld())
10045 RemoveNotOwnSingleTargetAuras();
10048 Object::RemoveFromWorld();
10051 void Unit::CleanupsBeforeDelete()
10053 if(m_uint32Values) // only for fully created object
10055 InterruptNonMeleeSpells(true);
10056 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
10057 CombatStop();
10058 ClearComboPointHolders();
10059 DeleteThreatList();
10060 getHostilRefManager().setOnlineOfflineState(false);
10061 RemoveAllAuras();
10062 RemoveAllGameObjects();
10063 RemoveAllDynObjects();
10064 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
10066 RemoveFromWorld();
10069 CharmInfo* Unit::InitCharmInfo(Unit *charm)
10071 if(!m_charmInfo)
10072 m_charmInfo = new CharmInfo(charm);
10073 return m_charmInfo;
10076 CharmInfo::CharmInfo(Unit* unit)
10077 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10079 for(int i =0; i<4; ++i)
10081 m_charmspells[i].spellId = 0;
10082 m_charmspells[i].active = ACT_DISABLED;
10086 void CharmInfo::InitPetActionBar()
10088 // the first 3 SpellOrActions are attack, follow and stay
10089 for(uint32 i = 0; i < 3; i++)
10091 PetActionBar[i].Type = ACT_COMMAND;
10092 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
10094 PetActionBar[i + 7].Type = ACT_REACTION;
10095 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
10097 for(uint32 i=0; i < 4; i++)
10099 PetActionBar[i + 3].Type = ACT_DISABLED;
10100 PetActionBar[i + 3].SpellOrAction = 0;
10104 void CharmInfo::InitEmptyActionBar()
10106 for(uint32 x = 1; x < 10; ++x)
10108 PetActionBar[x].Type = ACT_PASSIVE;
10109 PetActionBar[x].SpellOrAction = 0;
10111 PetActionBar[0].Type = ACT_COMMAND;
10112 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
10115 void CharmInfo::InitPossessCreateSpells()
10117 if(m_unit->GetTypeId() == TYPEID_PLAYER)
10118 return;
10120 InitEmptyActionBar(); //charm action bar
10122 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10124 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10125 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10126 else
10127 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10131 void CharmInfo::InitCharmCreateSpells()
10133 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10135 InitEmptyActionBar();
10136 return;
10139 InitPetActionBar();
10141 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10143 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10144 m_charmspells[x].spellId = spellId;
10146 if(!spellId)
10147 continue;
10149 if (IsPassiveSpell(spellId))
10151 m_unit->CastSpell(m_unit, spellId, true);
10152 m_charmspells[x].active = ACT_PASSIVE;
10154 else
10156 ActiveStates newstate;
10157 bool onlyselfcast = true;
10158 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10160 if(!spellInfo) onlyselfcast = false;
10161 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10163 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10164 onlyselfcast = false;
10167 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10168 newstate = ACT_DISABLED;
10169 else
10170 newstate = ACT_PASSIVE;
10172 AddSpellToAB(0, spellId, newstate);
10177 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
10179 for(uint8 i = 0; i < 10; i++)
10181 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
10183 PetActionBar[i].SpellOrAction = newid;
10184 if(!oldid)
10186 if(newstate == ACT_DECIDE)
10187 PetActionBar[i].Type = ACT_DISABLED;
10188 else
10189 PetActionBar[i].Type = newstate;
10192 return true;
10195 return false;
10198 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10200 if(IsPassiveSpell(spellid))
10201 return;
10203 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10205 if(spellid == m_charmspells[x].spellId)
10207 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
10212 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10214 m_petnumber = petnumber;
10215 if(statwindow)
10216 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10217 else
10218 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10221 bool Unit::isFrozen() const
10223 return HasAuraState(AURA_STATE_FROZEN);
10226 struct ProcTriggeredData
10228 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
10229 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
10230 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
10232 SpellProcEventEntry const *spellProcEvent;
10233 Aura* triggeredByAura;
10234 Unit::spellEffectPair triggeredByAura_SpellPair;
10237 typedef std::list< ProcTriggeredData > ProcTriggeredList;
10238 typedef std::list< uint32> RemoveSpellList;
10240 // List of auras that CAN be trigger but may not exist in spell_proc_event
10241 // in most case need for drop charges
10242 // in some types of aura need do additional check
10243 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
10244 bool InitTriggerAuraData()
10246 for (int i=0;i<TOTAL_AURAS;i++)
10248 isTriggerAura[i]=false;
10249 isNonTriggerAura[i] = false;
10251 isTriggerAura[SPELL_AURA_DUMMY] = true;
10252 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
10253 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
10254 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
10255 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
10256 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
10257 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
10258 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
10259 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
10260 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
10261 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
10262 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
10263 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
10264 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
10265 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
10266 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
10267 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
10268 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
10269 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
10270 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
10271 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
10272 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
10273 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
10274 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
10275 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
10276 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
10277 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
10278 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
10279 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
10281 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
10282 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
10284 return true;
10287 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
10289 uint32 procEx = PROC_EX_NONE;
10290 // Check victim state
10291 if (missCondition!=SPELL_MISS_NONE)
10292 switch (missCondition)
10294 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
10295 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
10296 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
10297 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
10298 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
10299 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
10300 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
10301 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
10302 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
10303 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
10304 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
10305 default:
10306 break;
10308 else
10310 // On block
10311 if (damageInfo->blocked)
10312 procEx|=PROC_EX_BLOCK;
10313 // On absorb
10314 if (damageInfo->absorb)
10315 procEx|=PROC_EX_ABSORB;
10316 // On crit
10317 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
10318 procEx|=PROC_EX_CRITICAL_HIT;
10319 else
10320 procEx|=PROC_EX_NORMAL_HIT;
10322 return procEx;
10325 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
10327 // For melee/ranged based attack need update skills and set some Aura states
10328 if (procFlag & MELEE_BASED_TRIGGER_MASK)
10330 // Update skills here for players
10331 if (GetTypeId() == TYPEID_PLAYER)
10333 // On melee based hit/miss/resist need update skill (for victim and attacker)
10334 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
10336 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
10337 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
10339 // Update defence if player is victim and parry/dodge/block
10340 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
10341 ((Player*)this)->UpdateDefense();
10343 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
10344 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
10346 // for victim
10347 if (isVictim)
10349 // if victim and dodge attack
10350 if (procExtra&PROC_EX_DODGE)
10352 //Update AURA_STATE on dodge
10353 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
10355 ModifyAuraState(AURA_STATE_DEFENSE, true);
10356 StartReactiveTimer( REACTIVE_DEFENSE );
10359 // if victim and parry attack
10360 if (procExtra & PROC_EX_PARRY)
10362 // For Hunters only Counterattack (skip Mongoose bite)
10363 if (getClass() == CLASS_HUNTER)
10365 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
10366 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
10368 else
10370 ModifyAuraState(AURA_STATE_DEFENSE, true);
10371 StartReactiveTimer( REACTIVE_DEFENSE );
10374 // if and victim block attack
10375 if (procExtra & PROC_EX_BLOCK)
10377 ModifyAuraState(AURA_STATE_DEFENSE,true);
10378 StartReactiveTimer( REACTIVE_DEFENSE );
10381 else //For attacker
10383 // Overpower on victim dodge
10384 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
10386 ((Player*)this)->AddComboPoints(pTarget, 1);
10387 StartReactiveTimer( REACTIVE_OVERPOWER );
10393 RemoveSpellList removedSpells;
10394 ProcTriggeredList procTriggered;
10395 // Fill procTriggered list
10396 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
10398 SpellProcEventEntry const* spellProcEvent = NULL;
10399 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
10400 continue;
10402 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
10405 // Nothing found
10406 if (procTriggered.empty())
10407 return;
10409 // Handle effects proceed this time
10410 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
10412 // Some auras can be deleted in function called in this loop (except first, ofc)
10413 // Until storing auars in std::multimap to hard check deleting by another way
10414 if(i != procTriggered.begin())
10416 bool found = false;
10417 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10418 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10419 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10421 if(itr->second==i->triggeredByAura)
10423 found = true;
10424 break;
10427 if(!found)
10429 // 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);
10430 // sLog.outDebug("It can be deleted one from early proccesed auras:");
10431 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
10432 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
10433 // sLog.outDebug(" <end of list>");
10434 continue;
10438 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
10439 Aura *triggeredByAura = i->triggeredByAura;
10440 Modifier *auraModifier = triggeredByAura->GetModifier();
10441 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
10442 uint32 effIndex = triggeredByAura->GetEffIndex();
10443 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
10444 // For players set spell cooldown if need
10445 uint32 cooldown = 0;
10446 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
10447 cooldown = spellProcEvent->cooldown;
10449 switch(auraModifier->m_auraname)
10451 case SPELL_AURA_PROC_TRIGGER_SPELL:
10453 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
10454 // Don`t drop charge or add cooldown for not started trigger
10455 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10456 continue;
10457 break;
10459 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
10461 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());
10462 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
10463 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
10464 SendSpellNonMeleeDamageLog(&damageInfo);
10465 DealSpellDamage(&damageInfo, true);
10466 break;
10468 case SPELL_AURA_MANA_SHIELD:
10469 case SPELL_AURA_DUMMY:
10471 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());
10472 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10473 continue;
10474 break;
10476 case SPELL_AURA_MOD_HASTE:
10478 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());
10479 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10480 continue;
10481 break;
10483 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
10485 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());
10486 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
10487 continue;
10488 break;
10490 case SPELL_AURA_PRAYER_OF_MENDING:
10492 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
10493 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
10495 HandleMeandingAuraProc(triggeredByAura);
10496 break;
10498 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
10500 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());
10502 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10503 continue;
10504 break;
10506 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
10507 // Skip melee hits or instant cast spells
10508 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
10509 continue;
10510 break;
10511 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
10512 // Skip Melee hits and spells ws wrong school
10513 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
10514 continue;
10515 break;
10516 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
10517 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
10518 // Skip melee hits and spells ws wrong school or zero cost
10519 if (procSpell == NULL ||
10520 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
10521 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
10522 continue;
10523 break;
10524 case SPELL_AURA_MECHANIC_IMMUNITY:
10525 // Compare mechanic
10526 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10527 continue;
10528 break;
10529 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
10530 // Compare mechanic
10531 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10532 continue;
10533 break;
10534 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
10535 // Compare casters
10536 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
10537 continue;
10538 break;
10539 default:
10540 // nothing do, just charges counter
10541 break;
10543 // Remove charge (aura can be removed by triggers)
10544 if(useCharges)
10546 // need found aura on drop (can be dropped by triggers)
10547 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10548 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10549 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10551 // If last charge dropped add spell to remove list
10552 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
10554 removedSpells.push_back(triggeredByAura->GetId());
10555 break;
10560 if (!removedSpells.empty())
10562 // Sort spells and remove dublicates
10563 removedSpells.sort();
10564 removedSpells.unique();
10565 // Remove auras from removedAuras
10566 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
10567 RemoveAurasDueToSpell(*i);
10571 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10573 return SPELL_SCHOOL_MASK_NORMAL;
10576 Player* Unit::GetSpellModOwner()
10578 if(GetTypeId()==TYPEID_PLAYER)
10579 return (Player*)this;
10580 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10582 Unit* owner = GetOwner();
10583 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10584 return (Player*)owner;
10586 return NULL;
10589 ///----------Pet responses methods-----------------
10590 void Unit::SendPetCastFail(uint32 spellid, uint8 msg)
10592 Unit *owner = GetCharmerOrOwner();
10593 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10594 return;
10596 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
10597 data << uint8(0); // cast count?
10598 data << uint32(spellid);
10599 data << uint8(msg);
10600 // uint32 for some reason
10601 // uint32 for some reason
10602 ((Player*)owner)->GetSession()->SendPacket(&data);
10605 void Unit::SendPetActionFeedback (uint8 msg)
10607 Unit* owner = GetOwner();
10608 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10609 return;
10611 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10612 data << uint8(msg);
10613 ((Player*)owner)->GetSession()->SendPacket(&data);
10616 void Unit::SendPetTalk (uint32 pettalk)
10618 Unit* owner = GetOwner();
10619 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10620 return;
10622 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
10623 data << uint64(GetGUID());
10624 data << uint32(pettalk);
10625 ((Player*)owner)->GetSession()->SendPacket(&data);
10628 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10630 Unit* owner = GetOwner();
10631 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10632 return;
10634 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10635 data << uint64(GetGUID());
10636 data << uint8(0x0); // flags (0x1, 0x2)
10637 data << uint32(spellid);
10638 data << uint32(cooltime);
10640 ((Player*)owner)->GetSession()->SendPacket(&data);
10643 void Unit::SendPetClearCooldown (uint32 spellid)
10645 Unit* owner = GetOwner();
10646 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10647 return;
10649 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10650 data << uint32(spellid);
10651 data << uint64(GetGUID());
10652 ((Player*)owner)->GetSession()->SendPacket(&data);
10655 void Unit::SendPetAIReaction(uint64 guid)
10657 Unit* owner = GetOwner();
10658 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10659 return;
10661 WorldPacket data(SMSG_AI_REACTION, 12);
10662 data << uint64(guid) << uint32(00000002);
10663 ((Player*)owner)->GetSession()->SendPacket(&data);
10666 ///----------End of Pet responses methods----------
10668 void Unit::StopMoving()
10670 clearUnitState(UNIT_STAT_MOVING);
10672 // send explicit stop packet
10673 // rely on vmaps here because for example stormwind is in air
10674 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10675 //if (fabs(GetPositionZ() - z) < 2.0f)
10676 // Relocate(GetPositionX(), GetPositionY(), z);
10677 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10679 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10681 // update position and orientation;
10682 WorldPacket data;
10683 BuildHeartBeatMsg(&data);
10684 SendMessageToSet(&data,false);
10687 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10689 if( apply )
10691 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10692 return;
10694 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10696 GetMotionMaster()->MovementExpired(false);
10697 CastStop(GetGUID()==casterGUID ? spellID : 0);
10699 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10701 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10703 else
10705 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10707 GetMotionMaster()->MovementExpired(false);
10709 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10711 // restore appropriate movement generator
10712 if(getVictim())
10713 GetMotionMaster()->MoveChase(getVictim());
10714 else
10715 GetMotionMaster()->Initialize();
10717 // attack caster if can
10718 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10719 if(caster && caster != getVictim() && ((Creature*)this)->AI())
10720 ((Creature*)this)->AI()->AttackStart(caster);
10724 if (GetTypeId() == TYPEID_PLAYER)
10725 ((Player*)this)->SetClientControl(this, !apply);
10728 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10730 if( apply )
10732 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10734 CastStop(GetGUID()==casterGUID ? spellID : 0);
10736 GetMotionMaster()->MoveConfused();
10738 else
10740 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10742 GetMotionMaster()->MovementExpired(false);
10744 if (GetTypeId() == TYPEID_UNIT)
10746 // if in combat restore movement generator
10747 if(getVictim())
10748 GetMotionMaster()->MoveChase(getVictim());
10752 if(GetTypeId() == TYPEID_PLAYER)
10753 ((Player*)this)->SetClientControl(this, !apply);
10756 bool Unit::IsSitState() const
10758 uint8 s = getStandState();
10759 return
10760 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
10761 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
10762 s == UNIT_STAND_STATE_SIT;
10765 bool Unit::IsStandState() const
10767 uint8 s = getStandState();
10768 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
10771 void Unit::SetStandState(uint8 state)
10773 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10775 if (IsStandState())
10776 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10778 if(GetTypeId()==TYPEID_PLAYER)
10780 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10781 data << (uint8)state;
10782 ((Player*)this)->GetSession()->SendPacket(&data);
10786 bool Unit::IsPolymorphed() const
10788 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10791 void Unit::SetDisplayId(uint32 modelId)
10793 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10795 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10797 Pet *pet = ((Pet*)this);
10798 if(!pet->isControlled())
10799 return;
10800 Unit *owner = GetOwner();
10801 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10802 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10806 void Unit::ClearComboPointHolders()
10808 while(!m_ComboPointHolders.empty())
10810 uint32 lowguid = *m_ComboPointHolders.begin();
10812 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10813 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10814 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10815 else
10816 m_ComboPointHolders.erase(lowguid); // or remove manually
10820 void Unit::ClearAllReactives()
10822 for(int i=0; i < MAX_REACTIVE; ++i)
10823 m_reactiveTimer[i] = 0;
10825 if (HasAuraState( AURA_STATE_DEFENSE))
10826 ModifyAuraState(AURA_STATE_DEFENSE, false);
10827 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10828 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10829 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10830 ((Player*)this)->ClearComboPoints();
10833 void Unit::UpdateReactives( uint32 p_time )
10835 for(int i = 0; i < MAX_REACTIVE; ++i)
10837 ReactiveType reactive = ReactiveType(i);
10839 if(!m_reactiveTimer[reactive])
10840 continue;
10842 if ( m_reactiveTimer[reactive] <= p_time)
10844 m_reactiveTimer[reactive] = 0;
10846 switch ( reactive )
10848 case REACTIVE_DEFENSE:
10849 if (HasAuraState(AURA_STATE_DEFENSE))
10850 ModifyAuraState(AURA_STATE_DEFENSE, false);
10851 break;
10852 case REACTIVE_HUNTER_PARRY:
10853 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10854 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10855 break;
10856 case REACTIVE_OVERPOWER:
10857 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10858 ((Player*)this)->ClearComboPoints();
10859 break;
10860 default:
10861 break;
10864 else
10866 m_reactiveTimer[reactive] -= p_time;
10871 Unit* Unit::SelectNearbyTarget() const
10873 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
10874 Cell cell(p);
10875 cell.data.Part.reserved = ALL_DISTRICT;
10876 cell.SetNoCreate();
10878 std::list<Unit *> targets;
10881 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
10882 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
10884 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
10885 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
10887 CellLock<GridReadGuard> cell_lock(cell, p);
10888 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
10889 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
10892 // remove current target
10893 if(getVictim())
10894 targets.remove(getVictim());
10896 // remove not LoS targets
10897 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
10899 if(!IsWithinLOSInMap(*tIter))
10901 std::list<Unit *>::iterator tIter2 = tIter;
10902 ++tIter;
10903 targets.erase(tIter2);
10905 else
10906 ++tIter;
10909 // no appropriate targets
10910 if(targets.empty())
10911 return NULL;
10913 // select random
10914 uint32 rIdx = urand(0,targets.size()-1);
10915 std::list<Unit *>::const_iterator tcIter = targets.begin();
10916 for(uint32 i = 0; i < rIdx; ++i)
10917 ++tcIter;
10919 return *tcIter;
10922 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
10924 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
10926 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
10927 return true;
10929 return false;
10932 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
10934 if(val > 0)
10936 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
10937 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
10939 else
10941 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
10942 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
10946 void Unit::ApplyCastTimePercentMod(float val, bool apply )
10948 if(val > 0)
10949 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
10950 else
10951 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
10954 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
10956 // Not apply this to creature casted spells with casttime==0
10957 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
10958 return 3500;
10960 if (CastingTime > 7000) CastingTime = 7000;
10961 if (CastingTime < 1500) CastingTime = 1500;
10963 if(damagetype == DOT && !IsChanneledSpell(spellProto))
10964 CastingTime = 3500;
10966 int32 overTime = 0;
10967 uint8 effects = 0;
10968 bool DirectDamage = false;
10969 bool AreaEffect = false;
10971 for ( uint32 i=0; i<3;i++)
10973 switch ( spellProto->Effect[i] )
10975 case SPELL_EFFECT_SCHOOL_DAMAGE:
10976 case SPELL_EFFECT_POWER_DRAIN:
10977 case SPELL_EFFECT_HEALTH_LEECH:
10978 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
10979 case SPELL_EFFECT_POWER_BURN:
10980 case SPELL_EFFECT_HEAL:
10981 DirectDamage = true;
10982 break;
10983 case SPELL_EFFECT_APPLY_AURA:
10984 switch ( spellProto->EffectApplyAuraName[i] )
10986 case SPELL_AURA_PERIODIC_DAMAGE:
10987 case SPELL_AURA_PERIODIC_HEAL:
10988 case SPELL_AURA_PERIODIC_LEECH:
10989 if ( GetSpellDuration(spellProto) )
10990 overTime = GetSpellDuration(spellProto);
10991 break;
10992 default:
10993 // -5% per additional effect
10994 ++effects;
10995 break;
10997 default:
10998 break;
11001 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
11002 AreaEffect = true;
11005 // Combined Spells with Both Over Time and Direct Damage
11006 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
11008 // mainly for DoTs which are 3500 here otherwise
11009 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
11010 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
11011 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
11012 // Portion to Over Time
11013 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
11015 if ( damagetype == DOT )
11016 CastingTime = uint32(CastingTime * PtOT);
11017 else if ( PtOT < 1.0f )
11018 CastingTime = uint32(CastingTime * (1 - PtOT));
11019 else
11020 CastingTime = 0;
11023 // Area Effect Spells receive only half of bonus
11024 if ( AreaEffect )
11025 CastingTime /= 2;
11027 // -5% of total per any additional effect
11028 for ( uint8 i=0; i<effects; ++i)
11030 if ( CastingTime > 175 )
11032 CastingTime -= 175;
11034 else
11036 CastingTime = 0;
11037 break;
11041 return CastingTime;
11044 void Unit::UpdateAuraForGroup(uint8 slot)
11046 if(GetTypeId() == TYPEID_PLAYER)
11048 Player* player = (Player*)this;
11049 if(player->GetGroup())
11051 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
11052 player->SetAuraUpdateMask(slot);
11055 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11057 Pet *pet = ((Pet*)this);
11058 if(pet->isControlled())
11060 Unit *owner = GetOwner();
11061 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11063 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
11064 pet->SetAuraUpdateMask(slot);
11070 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
11072 if (!normalized || GetTypeId() != TYPEID_PLAYER)
11073 return float(GetAttackTime(attType))/1000.0f;
11075 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
11076 if (!Weapon)
11077 return 2.4; // fist attack
11079 switch (Weapon->GetProto()->InventoryType)
11081 case INVTYPE_2HWEAPON:
11082 return 3.3;
11083 case INVTYPE_RANGED:
11084 case INVTYPE_RANGEDRIGHT:
11085 case INVTYPE_THROWN:
11086 return 2.8;
11087 case INVTYPE_WEAPON:
11088 case INVTYPE_WEAPONMAINHAND:
11089 case INVTYPE_WEAPONOFFHAND:
11090 default:
11091 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11095 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11097 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11098 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11099 if ((*itr)->GetId() == spell_id)
11100 return *itr;
11102 return NULL;
11105 bool Unit::IsUnderLastManaUseEffect() const
11107 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
11110 void Unit::SetContestedPvP(Player *attackedPlayer)
11112 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11114 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11115 return;
11117 player->SetContestedPvPTimer(30000);
11118 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11120 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11121 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11122 // call MoveInLineOfSight for nearby contested guards
11123 SetVisibility(GetVisibility());
11125 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11127 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11128 // call MoveInLineOfSight for nearby contested guards
11129 SetVisibility(GetVisibility());
11133 void Unit::AddPetAura(PetAura const* petSpell)
11135 m_petAuras.insert(petSpell);
11136 if(Pet* pet = GetPet())
11137 pet->CastPetAura(petSpell);
11140 void Unit::RemovePetAura(PetAura const* petSpell)
11142 m_petAuras.erase(petSpell);
11143 if(Pet* pet = GetPet())
11144 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11147 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11149 Pet* pet = new Pet(HUNTER_PET);
11151 if(!pet->CreateBaseAtCreature(creatureTarget))
11153 delete pet;
11154 return NULL;
11157 pet->SetOwnerGUID(GetGUID());
11158 pet->SetCreatorGUID(GetGUID());
11159 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
11160 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11162 if(GetTypeId()==TYPEID_PLAYER)
11163 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11165 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11167 if(!pet->InitStatsForLevel(level))
11169 sLog.outError("ERROR: Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11170 delete pet;
11171 return NULL;
11174 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11175 // this enables pet details window (Shift+P)
11176 pet->AIM_Initialize();
11177 pet->InitPetCreateSpells();
11178 pet->InitTalentForLevel();
11179 pet->SetHealth(pet->GetMaxHealth());
11181 return pet;
11184 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11186 SpellEntry const* spellProto = aura->GetSpellProto ();
11188 // Get proc Event Entry
11189 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11191 // Aura info stored here
11192 Modifier *mod = aura->GetModifier();
11193 // Skip this auras
11194 if (isNonTriggerAura[mod->m_auraname])
11195 return false;
11196 // If not trigger by default and spellProcEvent==NULL - skip
11197 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11198 return false;
11200 // Get EventProcFlag
11201 uint32 EventProcFlag;
11202 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
11203 EventProcFlag = spellProcEvent->procFlags;
11204 else
11205 EventProcFlag = spellProto->procFlags; // else get from spell proto
11206 // Continue if no trigger exist
11207 if (!EventProcFlag)
11208 return false;
11210 // Check spellProcEvent data requirements
11211 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
11212 return false;
11214 // In most cases req get honor or XP from kill
11215 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
11217 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
11218 // Shadow Word: Death - can trigger from every kill
11219 if (aura->GetId() == 32409)
11220 allow = true;
11221 if (!allow)
11222 return false;
11224 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
11225 // But except periodic triggers (can triggered from self)
11226 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
11227 return false;
11229 // Check if current equipment allows aura to proc
11230 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
11232 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
11234 Item *item = NULL;
11235 if(attType == BASE_ATTACK)
11236 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
11237 else if (attType == OFF_ATTACK)
11238 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11239 else
11240 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
11242 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
11243 return false;
11245 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11246 return false;
11248 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
11250 // Check if player is wearing shield
11251 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11252 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11253 return false;
11256 // Get chance from spell
11257 float chance = (float)spellProto->procChance;
11258 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
11259 if(spellProcEvent && spellProcEvent->customChance)
11260 chance = spellProcEvent->customChance;
11261 // If PPM exist calculate chance from PPM
11262 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
11264 uint32 WeaponSpeed = GetAttackTime(attType);
11265 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
11267 // Apply chance modifer aura
11268 if(Player* modOwner = GetSpellModOwner())
11269 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
11271 return roll_chance_f(chance);
11274 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
11276 // aura can be deleted at casts
11277 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
11278 uint32 effIdx = triggeredByAura->GetEffIndex();
11279 int32 heal = triggeredByAura->GetModifier()->m_amount;
11280 uint64 caster_guid = triggeredByAura->GetCasterGUID();
11282 // jumps
11283 int32 jumps = triggeredByAura->GetAuraCharges()-1;
11285 // current aura expire
11286 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
11288 // next target selection
11289 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
11291 float radius;
11292 if (spellProto->EffectRadiusIndex[effIdx])
11293 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
11294 else
11295 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
11297 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
11299 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
11301 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
11303 // aura will applied from caster, but spell casted from current aura holder
11304 SpellModifier *mod = new SpellModifier;
11305 mod->op = SPELLMOD_CHARGES;
11306 mod->value = jumps-5; // negative
11307 mod->type = SPELLMOD_FLAT;
11308 mod->spellId = spellProto->Id;
11309 mod->mask = spellProto->SpellFamilyFlags;
11310 mod->mask2 = spellProto->SpellFamilyFlags2;
11312 caster->AddSpellMod(mod, true);
11313 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
11314 caster->AddSpellMod(mod, false);
11319 // heal
11320 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
11321 return true;
11324 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
11326 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
11328 if(!IS_UNIT_GUID(target_guid))
11329 return;
11331 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
11332 if(!target)
11333 return;
11335 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
11337 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
11338 target->RemoveAura(iter);
11339 else
11340 ++iter;
11344 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
11346 WorldObject::SetPhaseMask(newPhaseMask,update);
11348 if(IsInWorld())
11349 if(Pet* pet = GetPet())
11350 pet->SetPhaseMask(newPhaseMask,true);