[7022] Added support for packets > 64 kb
[getmangos.git] / src / game / Unit.cpp
blob7ee119f03c8bbdb74bb4ff9c31c2d4e6aee7d47d
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Log.h"
21 #include "Opcodes.h"
22 #include "WorldPacket.h"
23 #include "WorldSession.h"
24 #include "World.h"
25 #include "ObjectMgr.h"
26 #include "SpellMgr.h"
27 #include "Unit.h"
28 #include "QuestDef.h"
29 #include "Player.h"
30 #include "Creature.h"
31 #include "Spell.h"
32 #include "Group.h"
33 #include "SpellAuras.h"
34 #include "MapManager.h"
35 #include "ObjectAccessor.h"
36 #include "CreatureAI.h"
37 #include "Formulas.h"
38 #include "Pet.h"
39 #include "Util.h"
40 #include "Totem.h"
41 #include "BattleGround.h"
42 #include "InstanceSaveMgr.h"
43 #include "GridNotifiersImpl.h"
44 #include "CellImpl.h"
45 #include "Path.h"
47 #include <math.h>
49 float baseMoveSpeed[MAX_MOVE_TYPE] =
51 2.5f, // MOVE_WALK
52 7.0f, // MOVE_RUN
53 1.25f, // MOVE_RUN_BACK
54 4.722222f, // MOVE_SWIM
55 4.5f, // MOVE_SWIM_BACK
56 3.141594f, // MOVE_TURN_RATE
57 7.0f, // MOVE_FLIGHT
58 4.5f, // MOVE_FLIGHT_BACK
59 3.14f // MOVE_PITCH_RATE
62 // Used for prepare can/can`t triggr aura
63 static bool InitTriggerAuraData();
64 // Define can trigger auras
65 static bool isTriggerAura[TOTAL_AURAS];
66 // Define can`t trigger auras (need for disable second trigger)
67 static bool isNonTriggerAura[TOTAL_AURAS];
68 // Prepare lists
69 static bool procPrepared = InitTriggerAuraData();
71 Unit::Unit()
72 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
74 m_objectType |= TYPEMASK_UNIT;
75 m_objectTypeId = TYPEID_UNIT;
76 // 2.3.2 - 0x70
77 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
79 m_attackTimer[BASE_ATTACK] = 0;
80 m_attackTimer[OFF_ATTACK] = 0;
81 m_attackTimer[RANGED_ATTACK] = 0;
82 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
83 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
84 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
86 m_extraAttacks = 0;
88 m_state = 0;
89 m_form = FORM_NONE;
90 m_deathState = ALIVE;
92 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
93 m_currentSpells[i] = NULL;
95 m_addDmgOnce = 0;
97 for(int i = 0; i < MAX_TOTEM; ++i)
98 m_TotemSlot[i] = 0;
100 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
101 //m_Aura = NULL;
102 //m_AurasCheck = 2000;
103 //m_removeAuraTimer = 4;
104 //tmpAura = NULL;
105 waterbreath = false;
107 m_Visibility = VISIBILITY_ON;
109 m_detectInvisibilityMask = 0;
110 m_invisibilityMask = 0;
111 m_transform = 0;
112 m_ShapeShiftFormSpellId = 0;
113 m_canModifyStats = false;
115 for (int i = 0; i < MAX_SPELL_IMMUNITY; i++)
116 m_spellImmune[i].clear();
117 for (int i = 0; i < UNIT_MOD_END; i++)
119 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
120 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
121 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
122 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
124 // implement 50% base damage from offhand
125 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
127 for (int i = 0; i < 3; i++)
129 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
130 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
132 for (int i = 0; i < MAX_STATS; i++)
133 m_createStats[i] = 0.0f;
135 m_attacking = NULL;
136 m_modMeleeHitChance = 0.0f;
137 m_modRangedHitChance = 0.0f;
138 m_modSpellHitChance = 0.0f;
139 m_baseSpellCritChance = 5;
141 m_CombatTimer = 0;
142 m_lastManaUse = 0;
144 //m_victimThreat = 0.0f;
145 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
146 m_threatModifier[i] = 1.0f;
147 m_isSorted = true;
148 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
149 m_speed_rate[i] = 1.0f;
151 m_removedAuras = 0;
152 m_charmInfo = NULL;
153 m_unit_movement_flags = 0;
155 // remove aurastates allowing special moves
156 for(int i=0; i < MAX_REACTIVE; ++i)
157 m_reactiveTimer[i] = 0;
160 Unit::~Unit()
162 // set current spells as deletable
163 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
165 if (m_currentSpells[i])
167 m_currentSpells[i]->SetReferencedFromCurrent(false);
168 m_currentSpells[i] = NULL;
172 RemoveAllGameObjects();
173 RemoveAllDynObjects();
175 if(m_charmInfo) delete m_charmInfo;
178 void Unit::Update( uint32 p_time )
180 /*if(p_time > m_AurasCheck)
182 m_AurasCheck = 2000;
183 _UpdateAura();
184 }else
185 m_AurasCheck -= p_time;*/
187 // WARNING! Order of execution here is important, do not change.
188 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
189 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
190 m_Events.Update( p_time );
191 _UpdateSpells( p_time );
193 // update combat timer only for players and pets
194 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
196 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
197 // targets without stopping half way there and running off.
198 // These flags are reset after target dies or another command is given.
199 if( m_HostilRefManager.isEmpty() )
201 // m_CombatTimer set at aura start and it will be freeze until aura removing
202 if ( m_CombatTimer <= p_time )
203 ClearInCombat();
204 else
205 m_CombatTimer -= p_time;
209 if(uint32 base_att = getAttackTimer(BASE_ATTACK))
211 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
214 // update abilities available only for fraction of time
215 UpdateReactives( p_time );
217 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
218 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
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(PLAYER_STATE_NONE);
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)
802 spell->Delayed();
806 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
808 if (spell->getState() == SPELL_STATE_CASTING)
810 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
811 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
813 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
814 spell->DelayedChannel();
816 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
818 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
819 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
822 else if (spell->getState() == SPELL_STATE_DELAYED)
823 // break channeled spell in delayed state on damage
825 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
826 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
831 // last damage from duel opponent
832 if(duel_hasEnded)
834 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
835 Player *he = (Player*)pVictim;
837 assert(he->duel);
839 he->SetHealth(1);
841 he->duel->opponent->CombatStopWithPets(true);
842 he->CombatStopWithPets(true);
844 he->CastSpell(he, 7267, true); // beg
845 he->DuelComplete(DUEL_WON);
849 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
851 return damage;
854 void Unit::CastStop(uint32 except_spellid)
856 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
857 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
858 InterruptSpell(i,false);
861 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
863 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
865 if(!spellInfo)
867 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
868 return;
871 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
874 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
876 if(!spellInfo)
878 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
879 return;
882 if (castItem)
883 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
885 if(!originalCaster && triggeredByAura)
886 originalCaster = triggeredByAura->GetCasterGUID();
888 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
890 SpellCastTargets targets;
891 targets.setUnitTarget( Victim );
892 spell->m_CastItem = castItem;
893 spell->prepare(&targets, triggeredByAura);
896 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
898 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
900 if(!spellInfo)
902 sLog.outError("CastCustomSpell: unknown spell id %i\n", spellId);
903 return;
906 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
909 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)
911 if(!spellInfo)
913 sLog.outError("CastCustomSpell: unknown spell");
914 return;
917 if (castItem)
918 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
920 if(!originalCaster && triggeredByAura)
921 originalCaster = triggeredByAura->GetCasterGUID();
923 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
925 if(bp0)
926 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
928 if(bp1)
929 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
931 if(bp2)
932 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
934 SpellCastTargets targets;
935 targets.setUnitTarget( Victim );
936 spell->m_CastItem = castItem;
937 spell->prepare(&targets, triggeredByAura);
940 // used for scripting
941 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
943 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
945 if(!spellInfo)
947 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()));
948 return;
951 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
954 // used for scripting
955 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
957 if(!spellInfo)
959 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
960 return;
963 if (castItem)
964 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
966 if(!originalCaster && triggeredByAura)
967 originalCaster = triggeredByAura->GetCasterGUID();
969 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
971 SpellCastTargets targets;
972 targets.setDestination(x, y, z);
973 spell->m_CastItem = castItem;
974 spell->prepare(&targets, triggeredByAura);
977 // Obsolete func need remove, here only for comotability vs another patches
978 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
980 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
981 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
982 CalculateSpellDamage(&damageInfo, damage, spellInfo);
983 SendSpellNonMeleeDamageLog(&damageInfo);
984 DealSpellDamage(&damageInfo, true);
985 return damageInfo.damage;
988 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
990 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
991 Unit *pVictim = damageInfo->target;
993 if (damage < 0)
994 return;
996 if(!this || !pVictim)
997 return;
998 if(!this->isAlive() || !pVictim->isAlive())
999 return;
1001 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1002 // Check spell crit chance
1003 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1004 bool blocked = false;
1005 // Per-school calc
1006 switch (spellInfo->DmgClass)
1008 // Melee and Ranged Spells
1009 case SPELL_DAMAGE_CLASS_RANGED:
1010 case SPELL_DAMAGE_CLASS_MELEE:
1012 // Physical Damage
1013 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1015 //Calculate armor mitigation
1016 damage = CalcArmorReducedDamage(pVictim, damage);
1017 // Get blocked status
1018 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1020 // Magical Damage
1021 else
1023 // Calculate damage bonus
1024 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1026 if (crit)
1028 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1030 // Calculate crit bonus
1031 uint32 crit_bonus = damage;
1032 // Apply crit_damage bonus for melee spells
1033 if(Player* modOwner = GetSpellModOwner())
1034 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1035 damage += crit_bonus;
1037 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1038 int32 critPctDamageMod=0;
1039 if(attackType == RANGED_ATTACK)
1040 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1041 else
1043 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1044 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1046 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1047 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1049 if (critPctDamageMod!=0)
1050 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1052 // Resilience - reduce crit damage
1053 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1054 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1056 // Spell weapon based damage CAN BE crit & blocked at same time
1057 if (blocked)
1059 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1060 if (damage < damageInfo->blocked)
1061 damageInfo->blocked = damage;
1062 damage-=damageInfo->blocked;
1065 break;
1066 // Magical Attacks
1067 case SPELL_DAMAGE_CLASS_NONE:
1068 case SPELL_DAMAGE_CLASS_MAGIC:
1070 // Calculate damage bonus
1071 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1072 // If crit add critical bonus
1073 if (crit)
1075 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1076 damage = SpellCriticalBonus(spellInfo, damage, pVictim);
1077 // Resilience - reduce crit damage
1078 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1079 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1082 break;
1085 // Calculate absorb resist
1086 if(damage > 0)
1088 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1089 damage-= damageInfo->absorb + damageInfo->resist;
1091 else
1092 damage = 0;
1093 damageInfo->damage = damage;
1096 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1098 if (damageInfo==0)
1099 return;
1101 Unit *pVictim = damageInfo->target;
1103 if(!this || !pVictim)
1104 return;
1106 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1107 return;
1109 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1110 if (spellProto == NULL)
1112 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1113 return;
1116 //You don't lose health from damage taken from another player while in a sanctuary
1117 //You still see it in the combat log though
1118 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1120 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1121 if(area && area->flags & 0x800) //sanctuary
1122 return;
1125 // update at damage Judgement aura duration that applied by attacker at victim
1126 if(damageInfo->damage && spellProto->Id == 35395)
1128 AuraMap& vAuras = pVictim->GetAuras();
1129 for(AuraMap::iterator itr = vAuras.begin(); itr != vAuras.end(); ++itr)
1131 SpellEntry const *spellInfo = (*itr).second->GetSpellProto();
1132 if( spellInfo->AttributesEx3 & 0x40000 && spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && ((*itr).second->GetCasterGUID() == GetGUID()))
1134 (*itr).second->SetAuraDuration((*itr).second->GetAuraMaxDuration());
1135 (*itr).second->SendAuraUpdate(false);
1139 // Call default DealDamage
1140 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1141 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1144 //TODO for melee need create structure as in
1145 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1147 damageInfo->attacker = this;
1148 damageInfo->target = pVictim;
1149 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1150 damageInfo->attackType = attackType;
1151 damageInfo->damage = 0;
1152 damageInfo->cleanDamage = 0;
1153 damageInfo->absorb = 0;
1154 damageInfo->resist = 0;
1155 damageInfo->blocked_amount = 0;
1157 damageInfo->TargetState = 0;
1158 damageInfo->HitInfo = 0;
1159 damageInfo->procAttacker = PROC_FLAG_NONE;
1160 damageInfo->procVictim = PROC_FLAG_NONE;
1161 damageInfo->procEx = PROC_EX_NONE;
1162 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1164 if(!this || !pVictim)
1165 return;
1166 if(!this->isAlive() || !pVictim->isAlive())
1167 return;
1169 // Select HitInfo/procAttacker/procVictim flag based on attack type
1170 switch (attackType)
1172 case BASE_ATTACK:
1173 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1174 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1175 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1176 break;
1177 case OFF_ATTACK:
1178 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1179 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1180 damageInfo->HitInfo = HITINFO_LEFTSWING;
1181 break;
1182 case RANGED_ATTACK:
1183 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1184 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1185 damageInfo->HitInfo = 0x08;// test
1186 break;
1187 default:
1188 break;
1191 // Physical Immune check
1192 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask),true))
1194 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1195 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1197 damageInfo->procEx |=PROC_EX_IMMUNE;
1198 damageInfo->damage = 0;
1199 damageInfo->cleanDamage = 0;
1200 return;
1202 damage += CalculateDamage (damageInfo->attackType, false);
1203 // Add melee damage bonus
1204 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1205 // Calculate armor reduction
1206 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1207 damageInfo->cleanDamage += damage - damageInfo->damage;
1209 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1211 // Disable parry or dodge for ranged attack
1212 if(damageInfo->attackType == RANGED_ATTACK)
1214 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1215 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1218 switch(damageInfo->hitOutCome)
1220 case MELEE_HIT_EVADE:
1222 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1223 damageInfo->TargetState = VICTIMSTATE_EVADES;
1225 damageInfo->procEx|=PROC_EX_EVADE;
1226 damageInfo->damage = 0;
1227 damageInfo->cleanDamage = 0;
1228 return;
1230 case MELEE_HIT_MISS:
1232 damageInfo->HitInfo |= HITINFO_MISS;
1233 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1235 damageInfo->procEx|=PROC_EX_MISS;
1236 damageInfo->damage = 0;
1237 damageInfo->cleanDamage = 0;
1238 break;
1240 case MELEE_HIT_NORMAL:
1241 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1242 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1243 break;
1244 case MELEE_HIT_CRIT:
1246 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1247 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1249 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1250 // Crit bonus calc
1251 damageInfo->damage += damageInfo->damage;
1252 int32 mod=0;
1253 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1254 if(damageInfo->attackType == RANGED_ATTACK)
1255 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1256 else
1258 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1259 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1262 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1264 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1265 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1266 if (mod!=0)
1267 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1269 // Resilience - reduce crit damage
1270 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1272 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1273 damageInfo->damage -= resilienceReduction;
1274 damageInfo->cleanDamage += resilienceReduction;
1276 break;
1278 case MELEE_HIT_PARRY:
1279 damageInfo->TargetState = VICTIMSTATE_PARRY;
1280 damageInfo->procEx|=PROC_EX_PARRY;
1281 damageInfo->cleanDamage += damageInfo->damage;
1282 damageInfo->damage = 0;
1283 break;
1285 case MELEE_HIT_DODGE:
1286 damageInfo->TargetState = VICTIMSTATE_DODGE;
1287 damageInfo->procEx|=PROC_EX_DODGE;
1288 damageInfo->cleanDamage += damageInfo->damage;
1289 damageInfo->damage = 0;
1290 break;
1291 case MELEE_HIT_BLOCK:
1293 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1294 damageInfo->HitInfo |= HITINFO_BLOCK;
1295 damageInfo->procEx|=PROC_EX_BLOCK;
1296 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1297 if (damageInfo->blocked_amount >= damageInfo->damage)
1299 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1300 damageInfo->blocked_amount = damageInfo->damage;
1302 damageInfo->damage -= damageInfo->blocked_amount;
1303 damageInfo->cleanDamage += damageInfo->blocked_amount;
1304 break;
1306 case MELEE_HIT_GLANCING:
1308 damageInfo->HitInfo |= HITINFO_GLANCING;
1309 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1310 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1311 float reducePercent = 1.0f; //damage factor
1312 // calculate base values and mods
1313 float baseLowEnd = 1.3;
1314 float baseHighEnd = 1.2;
1315 switch(getClass()) // lowering base values for casters
1317 case CLASS_SHAMAN:
1318 case CLASS_PRIEST:
1319 case CLASS_MAGE:
1320 case CLASS_WARLOCK:
1321 case CLASS_DRUID:
1322 baseLowEnd -= 0.7;
1323 baseHighEnd -= 0.3;
1324 break;
1327 float maxLowEnd = 0.6;
1328 switch(getClass()) // upper for melee classes
1330 case CLASS_WARRIOR:
1331 case CLASS_ROGUE:
1332 maxLowEnd = 0.91; //If the attacker is a melee class then instead the lower value of 0.91
1335 // calculate values
1336 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1337 float lowEnd = baseLowEnd - ( 0.05f * diff );
1338 float highEnd = baseHighEnd - ( 0.03f * diff );
1340 // apply max/min bounds
1341 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1342 lowEnd = 0.01f;
1343 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1344 lowEnd = maxLowEnd;
1346 if ( highEnd < 0.2f ) //high end limits
1347 highEnd = 0.2f;
1348 if ( highEnd > 0.99f )
1349 highEnd = 0.99f;
1351 if(lowEnd > highEnd) // prevent negative range size
1352 lowEnd = highEnd;
1354 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1356 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1357 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1358 break;
1360 case MELEE_HIT_CRUSHING:
1362 damageInfo->HitInfo |= HITINFO_CRUSHING;
1363 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1364 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1365 // 150% normal damage
1366 damageInfo->damage += (damageInfo->damage / 2);
1367 break;
1369 default:
1371 break;
1374 // Calculate absorb resist
1375 if(int32(damageInfo->damage) > 0)
1377 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1378 // Calculate absorb & resists
1379 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1380 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1381 if (damageInfo->absorb)
1383 damageInfo->HitInfo|=HITINFO_ABSORB;
1384 damageInfo->procEx|=PROC_EX_ABSORB;
1386 if (damageInfo->resist)
1387 damageInfo->HitInfo|=HITINFO_RESIST;
1390 else // Umpossible get negative result but....
1391 damageInfo->damage = 0;
1394 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1396 if (damageInfo==0) return;
1397 Unit *pVictim = damageInfo->target;
1399 if(!this || !pVictim)
1400 return;
1402 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1403 return;
1405 //You don't lose health from damage taken from another player while in a sanctuary
1406 //You still see it in the combat log though
1407 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1409 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1410 if(area && area->flags & 0x800) //sanctuary
1411 return;
1414 // Hmmmm dont like this emotes cloent must by self do all animations
1415 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1416 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1417 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1418 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1420 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1422 // Get attack timers
1423 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1424 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1425 // Reduce attack time
1426 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1428 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20;
1429 float percent60 = 3 * percent20;
1430 if(offtime > percent20 && offtime <= percent60)
1432 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1434 else if(offtime > percent60)
1436 offtime -= 2 * percent20;
1437 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1440 else
1442 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1443 float percent60 = 3 * percent20;
1444 if(basetime > percent20 && basetime <= percent60)
1446 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1448 else if(basetime > percent60)
1450 basetime -= 2 * percent20;
1451 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1456 // Call default DealDamage
1457 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1458 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1460 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1461 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1462 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1464 // -probability is between 0% and 40%
1465 // 20% base chance
1466 float Probability = 20;
1468 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1469 if( pVictim->getLevel() < 30 )
1470 Probability = 0.65f*pVictim->getLevel()+0.5;
1472 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1473 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1475 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1477 if(Probability > 40)
1478 Probability = 40;
1480 if(roll_chance_f(Probability))
1481 CastSpell(pVictim, 1604, true);
1484 // update at damage Judgement aura duration that applied by attacker at victim
1485 if(damageInfo->damage)
1487 AuraMap& vAuras = pVictim->GetAuras();
1488 for(AuraMap::iterator itr = vAuras.begin(); itr != vAuras.end(); ++itr)
1490 SpellEntry const *spellInfo = (*itr).second->GetSpellProto();
1491 if( spellInfo->AttributesEx3 & 0x40000 && spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && ((*itr).second->GetCasterGUID() == GetGUID()))
1493 (*itr).second->SetAuraDuration((*itr).second->GetAuraMaxDuration());
1494 (*itr).second->SendAuraUpdate(false);
1499 // If not miss
1500 if (!(damageInfo->HitInfo & HITINFO_MISS))
1502 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1504 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1505 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1508 // victim's damage shield
1509 std::set<Aura*> alreadyDone;
1510 uint32 removedAuras = pVictim->m_removedAuras;
1511 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1512 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1514 next++;
1515 if (alreadyDone.find(*i) == alreadyDone.end())
1517 alreadyDone.insert(*i);
1518 uint32 damage=(*i)->GetModifier()->m_amount;
1519 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1520 if(!spellProto)
1521 continue;
1522 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1523 //uint32 absorb;
1524 //uint32 resist;
1525 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1526 //damage-=absorb + resist;
1528 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1529 data << uint64(pVictim->GetGUID());
1530 data << uint64(GetGUID());
1531 data << uint32(spellProto->Id);
1532 data << uint32(damage); // Damage
1533 data << uint32(0); // Overkill
1534 data << uint32(spellProto->SchoolMask);
1535 pVictim->SendMessageToSet(&data, true );
1537 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1539 if (pVictim->m_removedAuras > removedAuras)
1541 removedAuras = pVictim->m_removedAuras;
1542 next = vDamageShields.begin();
1550 void Unit::HandleEmoteCommand(uint32 anim_id)
1552 WorldPacket data( SMSG_EMOTE, 12 );
1553 data << uint32(anim_id);
1554 data << uint64(GetGUID());
1555 SendMessageToSet(&data, true);
1558 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1560 uint32 newdamage = 0;
1561 float armor = pVictim->GetArmor();
1562 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1563 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1565 // Apply Player CR_ARMOR_PENETRATION rating
1566 if (GetTypeId()==TYPEID_PLAYER)
1567 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1569 if (armor < 0.0f) armor=0.0f;
1571 float levelModifier = getLevel();
1572 if ( levelModifier > 59 )
1573 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1575 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1576 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1578 if(tmpvalue < 0.0f)
1579 tmpvalue = 0.0f;
1580 if(tmpvalue > 0.75f)
1581 tmpvalue = 0.75f;
1582 newdamage = uint32(damage - (damage * tmpvalue));
1584 return (newdamage > 1) ? newdamage : 1;
1587 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1589 if(!pVictim || !pVictim->isAlive() || !damage)
1590 return;
1592 // Magic damage, check for resists
1593 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1595 // Get base victim resistance for school
1596 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1597 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1598 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1600 tmpvalue2 *= (float)(0.15f / getLevel());
1601 if (tmpvalue2 < 0.0f)
1602 tmpvalue2 = 0.0f;
1603 if (tmpvalue2 > 0.75f)
1604 tmpvalue2 = 0.75f;
1605 uint32 ran = urand(0, 100);
1606 uint32 faq[4] = {24,6,4,6};
1607 uint8 m = 0;
1608 float Binom = 0.0f;
1609 for (uint8 i = 0; i < 4; i++)
1611 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1612 if (ran > Binom )
1613 ++m;
1614 else
1615 break;
1617 if (damagetype == DOT && m == 4)
1618 *resist += uint32(damage - 1);
1619 else
1620 *resist += uint32(damage * m / 4);
1621 if(*resist > damage)
1622 *resist = damage;
1624 else
1625 *resist = 0;
1627 int32 RemainingDamage = damage - *resist;
1629 // absorb without mana cost
1630 int32 reflectDamage = 0;
1631 Aura* reflectAura = NULL;
1632 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1633 for(AuraList::const_iterator i = vSchoolAbsorb.begin(), next; i != vSchoolAbsorb.end() && RemainingDamage > 0; i = next)
1635 next = i; ++next;
1637 if (((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1638 continue;
1640 // Cheat Death
1641 if((*i)->GetSpellProto()->SpellFamilyName==SPELLFAMILY_ROGUE && (*i)->GetSpellProto()->SpellIconID == 2109)
1643 if (((Player*)pVictim)->HasSpellCooldown(31231))
1644 continue;
1645 if (pVictim->GetHealth() <= RemainingDamage)
1647 int32 chance = (*i)->GetModifier()->m_amount;
1648 if (roll_chance_i(chance))
1650 pVictim->CastSpell(pVictim,31231,true);
1651 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1653 // with health > 10% lost health until health==10%, in other case no losses
1654 uint32 health10 = pVictim->GetMaxHealth()/10;
1655 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1658 continue;
1661 int32 currentAbsorb;
1663 // Reflective Shield
1664 if ((pVictim != this) && (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_PRIEST && (*i)->GetSpellProto()->SpellFamilyFlags == 0x1)
1666 if(Unit* caster = (*i)->GetCaster())
1668 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
1669 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1671 switch((*k)->GetModifier()->m_miscvalue)
1673 case 5065: // Rank 1
1674 case 5064: // Rank 2
1675 case 5063: // Rank 3
1676 case 5062: // Rank 4
1677 case 5061: // Rank 5
1679 if(RemainingDamage >= (*i)->GetModifier()->m_amount)
1680 reflectDamage = (*i)->GetModifier()->m_amount * (*k)->GetModifier()->m_amount/100;
1681 else
1682 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1683 reflectAura = *i;
1685 } break;
1686 default: break;
1689 if(reflectDamage)
1690 break;
1695 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1697 currentAbsorb = (*i)->GetModifier()->m_amount;
1698 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1699 next = vSchoolAbsorb.begin();
1701 else
1703 currentAbsorb = RemainingDamage;
1704 (*i)->GetModifier()->m_amount -= RemainingDamage;
1707 RemainingDamage -= currentAbsorb;
1709 // do not cast spells while looping auras; auras can get invalid otherwise
1710 if (reflectDamage)
1711 pVictim->CastCustomSpell(this, 33619, &reflectDamage, NULL, NULL, true, NULL, reflectAura);
1713 // absorb by mana cost
1714 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1715 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1717 next = i; ++next;
1719 // check damage school mask
1720 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1721 continue;
1723 int32 currentAbsorb;
1724 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1725 currentAbsorb = (*i)->GetModifier()->m_amount;
1726 else
1727 currentAbsorb = RemainingDamage;
1729 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1730 if(Player *modOwner = GetSpellModOwner())
1731 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1733 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1734 if (currentAbsorb > maxAbsorb)
1735 currentAbsorb = maxAbsorb;
1737 (*i)->GetModifier()->m_amount -= currentAbsorb;
1738 if((*i)->GetModifier()->m_amount <= 0)
1740 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1741 next = vManaShield.begin();
1744 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1745 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1747 RemainingDamage -= currentAbsorb;
1750 // only split damage if not damaging yourself
1751 if(pVictim != this)
1753 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1754 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1756 next = i; ++next;
1758 // check damage school mask
1759 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1760 continue;
1762 // Damage can be splitted only if aura has an alive caster
1763 Unit *caster = (*i)->GetCaster();
1764 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1765 continue;
1767 int32 currentAbsorb;
1768 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1769 currentAbsorb = (*i)->GetModifier()->m_amount;
1770 else
1771 currentAbsorb = RemainingDamage;
1773 RemainingDamage -= currentAbsorb;
1775 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1777 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1778 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1781 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1782 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1784 next = i; ++next;
1786 // check damage school mask
1787 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1788 continue;
1790 // Damage can be splitted only if aura has an alive caster
1791 Unit *caster = (*i)->GetCaster();
1792 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1793 continue;
1795 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1797 RemainingDamage -= splitted;
1799 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1801 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1802 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1806 *absorb = damage - RemainingDamage - *resist;
1809 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1811 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1812 return;
1814 if (!pVictim->isAlive())
1815 return;
1817 if(IsNonMeleeSpellCasted(false))
1818 return;
1820 uint32 hitInfo;
1821 if (attType == BASE_ATTACK)
1822 hitInfo = HITINFO_NORMALSWING2;
1823 else if (attType == OFF_ATTACK)
1824 hitInfo = HITINFO_LEFTSWING;
1825 else
1826 return; // ignore ranged case
1828 uint32 extraAttacks = m_extraAttacks;
1830 // melee attack spell casted at main hand attack only
1831 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1833 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1835 // not recent extra attack only at any non extra attack (melee spell case)
1836 if(!extra && extraAttacks)
1838 while(m_extraAttacks)
1840 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1841 if(m_extraAttacks > 0)
1842 --m_extraAttacks;
1846 return;
1849 CalcDamageInfo damageInfo;
1850 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1851 // Send log damage message to client
1852 SendAttackStateUpdate(&damageInfo);
1853 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1854 DealMeleeDamage(&damageInfo,true);
1856 if (GetTypeId() == TYPEID_PLAYER)
1857 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1858 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1859 else
1860 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1861 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1863 // extra attack only at any non extra attack (normal case)
1864 if(!extra && extraAttacks)
1866 while(m_extraAttacks)
1868 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1869 if(m_extraAttacks > 0)
1870 --m_extraAttacks;
1875 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
1877 // This is only wrapper
1879 // Miss chance based on melee
1880 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
1882 // Critical hit chance
1883 float crit_chance = GetUnitCriticalChance(attType, pVictim);
1885 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
1886 float dodge_chance = pVictim->GetUnitDodgeChance();
1887 float block_chance = pVictim->GetUnitBlockChance();
1888 float parry_chance = pVictim->GetUnitParryChance();
1890 // Useful if want to specify crit & miss chances for melee, else it could be removed
1891 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
1893 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
1896 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
1898 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1899 return MELEE_HIT_EVADE;
1901 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
1902 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
1904 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
1905 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
1907 // bonus from skills is 0.04%
1908 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
1909 int32 sum = 0, tmp = 0;
1910 int32 roll = urand (0, 10000);
1912 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
1913 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
1914 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
1916 tmp = miss_chance;
1918 if (tmp > 0 && roll < (sum += tmp ))
1920 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
1921 return MELEE_HIT_MISS;
1924 // always crit against a sitting target (except 0 crit chance)
1925 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
1927 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
1928 return MELEE_HIT_CRIT;
1931 // Dodge chance
1933 // only players can't dodge if attacker is behind
1934 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
1936 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
1938 else
1940 // Reduce dodge chance by attacker expertise rating
1941 if (GetTypeId() == TYPEID_PLAYER)
1942 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
1944 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
1945 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
1947 tmp = dodge_chance;
1948 if ( (tmp > 0) // check if unit _can_ dodge
1949 && ((tmp -= skillBonus) > 0)
1950 && roll < (sum += tmp))
1952 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
1953 return MELEE_HIT_DODGE;
1957 // parry & block chances
1959 // check if attack comes from behind, nobody can parry or block if attacker is behind
1960 if (!pVictim->HasInArc(M_PI,this))
1962 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
1964 else
1966 // Reduce parry chance by attacker expertise rating
1967 if (GetTypeId() == TYPEID_PLAYER)
1968 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
1970 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
1972 int32 tmp = int32(parry_chance);
1973 if ( (tmp > 0) // check if unit _can_ parry
1974 && ((tmp -= skillBonus) > 0)
1975 && (roll < (sum += tmp)))
1977 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
1978 return MELEE_HIT_PARRY;
1982 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
1984 tmp = block_chance;
1985 if ( (tmp > 0) // check if unit _can_ block
1986 && ((tmp -= skillBonus) > 0)
1987 && (roll < (sum += tmp)))
1989 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
1990 return MELEE_HIT_BLOCK;
1995 // Critical chance
1996 tmp = crit_chance;
1998 if (tmp > 0 && roll < (sum += tmp))
2000 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2001 return MELEE_HIT_CRIT;
2004 // 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)
2005 if( attType != RANGED_ATTACK &&
2006 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2007 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2008 getLevel() < pVictim->getLevelForTarget(this) )
2010 // cap possible value (with bonuses > max skill)
2011 int32 skill = attackerWeaponSkill;
2012 int32 maxskill = attackerMaxSkillValueForLevel;
2013 skill = (skill > maxskill) ? maxskill : skill;
2015 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2016 tmp = tmp > 4000 ? 4000 : tmp;
2017 if (roll < (sum += tmp))
2019 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2020 return MELEE_HIT_GLANCING;
2024 // mobs can score crushing blows if they're 4 or more levels above victim
2025 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2026 // can be from by creature (if can) or from controlled player that considered as creature
2027 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2028 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2029 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2031 // when their weapon skill is 15 or more above victim's defense skill
2032 tmp = victimDefenseSkill;
2033 int32 tmpmax = victimMaxSkillValueForLevel;
2034 // having defense above your maximum (from items, talents etc.) has no effect
2035 tmp = tmp > tmpmax ? tmpmax : tmp;
2036 // tmp = mob's level * 5 - player's current defense skill
2037 tmp = attackerMaxSkillValueForLevel - tmp;
2038 if(tmp >= 15)
2040 // add 2% chance per lacking skill point, min. is 15%
2041 tmp = tmp * 200 - 1500;
2042 if (roll < (sum += tmp))
2044 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2045 return MELEE_HIT_CRUSHING;
2050 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2051 return MELEE_HIT_NORMAL;
2054 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2056 float min_damage, max_damage;
2058 if (normalized && GetTypeId()==TYPEID_PLAYER)
2059 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2060 else
2062 switch (attType)
2064 case RANGED_ATTACK:
2065 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2066 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2067 break;
2068 case BASE_ATTACK:
2069 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2070 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2071 break;
2072 case OFF_ATTACK:
2073 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2074 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2075 break;
2076 // Just for good manner
2077 default:
2078 min_damage = 0.0f;
2079 max_damage = 0.0f;
2080 break;
2084 if (min_damage > max_damage)
2086 std::swap(min_damage,max_damage);
2089 if(max_damage == 0.0f)
2090 max_damage = 5.0f;
2092 return urand((uint32)min_damage, (uint32)max_damage);
2095 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2097 if(spellProto->spellLevel <= 0)
2098 return 1.0f;
2100 float LvlPenalty = 0.0f;
2102 if(spellProto->spellLevel < 20)
2103 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2104 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2105 if(LvlFactor > 1.0f)
2106 LvlFactor = 1.0f;
2108 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2111 void Unit::SendAttackStart(Unit* pVictim)
2113 WorldPacket data( SMSG_ATTACKSTART, 16 );
2114 data << uint64(GetGUID());
2115 data << uint64(pVictim->GetGUID());
2117 SendMessageToSet(&data, true);
2118 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2121 void Unit::SendAttackStop(Unit* victim)
2123 if(!victim)
2124 return;
2126 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2127 data.append(GetPackGUID());
2128 data.append(victim->GetPackGUID()); // can be 0x00...
2129 data << uint32(0); // can be 0x1
2130 SendMessageToSet(&data, true);
2131 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2133 /*if(victim->GetTypeId() == TYPEID_UNIT)
2134 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2137 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2139 if (pVictim->HasInArc(M_PI,this))
2141 /* Currently not exist spells with ignore block
2142 // Ignore combat result aura (parry/dodge check on prepare)
2143 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2144 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2146 if (!(*i)->isAffectedOnSpell(spellProto))
2147 continue;
2148 if ((*i)->GetModifier()->m_miscvalue == )
2149 return false;
2153 // Check creatures flags_extra for disable block
2154 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2155 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2156 return false;
2158 float blockChance = GetUnitBlockChance();
2159 blockChance += (GetWeaponSkillValue(attackType) - pVictim->GetMaxSkillValueForLevel() )*0.04;
2160 if (roll_chance_f(blockChance))
2161 return true;
2163 return false;
2166 // Melee based spells can be miss, parry or dodge on this step
2167 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2168 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2170 // Calculate hit chance (more correct for chance mod)
2171 int32 HitChance;
2173 // PvP - PvE melee chances
2174 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2175 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2176 if(leveldif < 3)
2177 HitChance = 95 - leveldif;
2178 else
2179 HitChance = 93 - (leveldif - 2) * lchance;
2181 // Hit chance depends from victim auras
2182 if(attType == RANGED_ATTACK)
2183 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2184 else
2185 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2187 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2188 if(Player *modOwner = GetSpellModOwner())
2189 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2191 // Miss = 100 - hit
2192 float miss_chance= 100.0f - HitChance;
2194 // Bonuses from attacker aura and ratings
2195 if (attType == RANGED_ATTACK)
2196 miss_chance -= m_modRangedHitChance;
2197 else
2198 miss_chance -= m_modMeleeHitChance;
2200 // bonus from skills is 0.04%
2201 miss_chance -= skillDiff * 0.04f;
2203 // Limit miss chance from 0 to 60%
2204 if (miss_chance < 0.0f)
2205 return 0.0f;
2206 if (miss_chance > 60.0f)
2207 return 60.0f;
2208 return miss_chance;
2211 // Melee based spells hit result calculations
2212 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2214 WeaponAttackType attType = BASE_ATTACK;
2216 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2217 attType = RANGED_ATTACK;
2219 // bonus from skills is 0.04% per skill Diff
2220 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2221 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2222 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2224 uint32 roll = urand (0, 10000);
2226 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2227 // Roll miss
2228 uint32 tmp = missChance;
2229 if (roll < tmp)
2230 return SPELL_MISS_MISS;
2232 bool canDodge = true;
2233 bool canParry = true;
2235 // Same spells cannot be parry/dodge
2236 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2237 return SPELL_MISS_NONE;
2239 // Ranged attack cannot be parry/dodge
2240 if (attType == RANGED_ATTACK)
2241 return SPELL_MISS_NONE;
2243 // Check for attack from behind
2244 if (!pVictim->HasInArc(M_PI,this))
2246 // Can`t dodge from behind in PvP (but its possible in PvE)
2247 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2248 canDodge = false;
2249 // Can`t parry
2250 canParry = false;
2252 // Check creatures flags_extra for disable parry
2253 if(pVictim->GetTypeId()==TYPEID_UNIT)
2255 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2256 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2257 canParry = false;
2259 // Ignore combat result aura
2260 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2261 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2263 if (!(*i)->isAffectedOnSpell(spell))
2264 continue;
2265 switch((*i)->GetModifier()->m_miscvalue)
2267 case MELEE_HIT_DODGE: canDodge = false; break;
2268 case MELEE_HIT_BLOCK: break; // Block check in hit step
2269 case MELEE_HIT_PARRY: canParry = false; break;
2270 default:
2271 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2272 break;
2276 if (canDodge)
2278 // Roll dodge
2279 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2280 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2281 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2282 // Reduce dodge chance by attacker expertise rating
2283 if (GetTypeId() == TYPEID_PLAYER)
2284 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2285 if (dodgeChance < 0)
2286 dodgeChance = 0;
2288 tmp += dodgeChance;
2289 if (roll < tmp)
2290 return SPELL_MISS_DODGE;
2293 if (canParry)
2295 // Roll parry
2296 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2297 // Reduce parry chance by attacker expertise rating
2298 if (GetTypeId() == TYPEID_PLAYER)
2299 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2300 if (parryChance < 0)
2301 parryChance = 0;
2303 tmp += parryChance;
2304 if (roll < tmp)
2305 return SPELL_MISS_PARRY;
2308 return SPELL_MISS_NONE;
2311 // TODO need use unit spell resistances in calculations
2312 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2314 // Can`t miss on dead target (on skinning for example)
2315 if (!pVictim->isAlive())
2316 return SPELL_MISS_NONE;
2318 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2319 // PvP - PvE spell misschances per leveldif > 2
2320 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2321 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2323 // Base hit chance from attacker and victim levels
2324 int32 modHitChance;
2325 if(leveldif < 3)
2326 modHitChance = 96 - leveldif;
2327 else
2328 modHitChance = 94 - (leveldif - 2) * lchance;
2330 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2331 if(Player *modOwner = GetSpellModOwner())
2332 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2333 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2334 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2335 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2336 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2337 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2338 if (IsAreaOfEffectSpell(spell))
2339 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2340 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2341 if (IsDispelSpell(spell))
2342 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2343 // Chance resist mechanic (select max value from every mechanic spell effect)
2344 int32 resist_mech = 0;
2345 // Get effects mechanic and chance
2346 for(int eff = 0; eff < 3; ++eff)
2348 int32 effect_mech = GetEffectMechanic(spell, eff);
2349 if (effect_mech)
2351 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2352 if (resist_mech < temp)
2353 resist_mech = temp;
2356 // Apply mod
2357 modHitChance-=resist_mech;
2359 // Chance resist debuff
2360 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2362 int32 HitChance = modHitChance * 100;
2363 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2364 HitChance += int32(m_modSpellHitChance*100.0f);
2366 // Decrease hit chance from victim rating bonus
2367 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2368 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2370 if (HitChance < 100) HitChance = 100;
2371 if (HitChance > 9900) HitChance = 9900;
2373 uint32 rand = urand(0,10000);
2374 if (rand > HitChance)
2375 return SPELL_MISS_RESIST;
2376 return SPELL_MISS_NONE;
2379 // Calculate spell hit result can be:
2380 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2381 // For melee based spells:
2382 // Miss
2383 // Dodge
2384 // Parry
2385 // For spells
2386 // Resist
2387 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2389 // Return evade for units in evade mode
2390 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2391 return SPELL_MISS_EVADE;
2393 // Check for immune (use charges)
2394 if (pVictim->IsImmunedToSpell(spell,true))
2395 return SPELL_MISS_IMMUNE;
2397 // All positive spells can`t miss
2398 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2399 if (IsPositiveSpell(spell->Id))
2400 return SPELL_MISS_NONE;
2402 // Check for immune (use charges)
2403 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell),true))
2404 return SPELL_MISS_IMMUNE;
2406 // Try victim reflect spell
2407 if (CanReflect)
2409 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2410 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2411 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2412 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2413 reflectchance += (*i)->GetModifier()->m_amount;
2414 if (reflectchance > 0 && roll_chance_i(reflectchance))
2416 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2417 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2418 return SPELL_MISS_REFLECT;
2422 switch (spell->DmgClass)
2424 case SPELL_DAMAGE_CLASS_RANGED:
2425 case SPELL_DAMAGE_CLASS_MELEE:
2426 return MeleeSpellHitResult(pVictim, spell);
2427 case SPELL_DAMAGE_CLASS_NONE:
2428 case SPELL_DAMAGE_CLASS_MAGIC:
2429 return MagicSpellHitResult(pVictim, spell);
2431 return SPELL_MISS_NONE;
2434 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2436 if(!pVictim)
2437 return 0.0f;
2439 // Base misschance 5%
2440 float misschance = 5.0f;
2442 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2443 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2445 bool isNormal = false;
2446 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2448 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2450 isNormal = true;
2451 break;
2454 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2456 misschance = 5.0f;
2458 else
2460 misschance = 24.0f;
2464 // PvP : PvE melee misschances per leveldif > 2
2465 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2467 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2468 if(leveldif < 0)
2469 leveldif = 0;
2471 // Hit chance from attacker based on ratings and auras
2472 float m_modHitChance;
2473 if (attType == RANGED_ATTACK)
2474 m_modHitChance = m_modRangedHitChance;
2475 else
2476 m_modHitChance = m_modMeleeHitChance;
2478 if(leveldif < 3)
2479 misschance += (leveldif - m_modHitChance);
2480 else
2481 misschance += ((leveldif - 2) * chance - m_modHitChance);
2483 // Hit chance for victim based on ratings
2484 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2486 if (attType == RANGED_ATTACK)
2487 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2488 else
2489 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2492 // Modify miss chance by victim auras
2493 if(attType == RANGED_ATTACK)
2494 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2495 else
2496 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2498 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2499 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2500 misschance -= skillBonus * 0.04f;
2502 // Limit miss chance from 0 to 60%
2503 if ( misschance < 0.0f)
2504 return 0.0f;
2505 if ( misschance > 60.0f)
2506 return 60.0f;
2508 return misschance;
2511 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2513 if(GetTypeId() == TYPEID_PLAYER)
2515 // in PvP use full skill instead current skill value
2516 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2517 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2518 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2519 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2520 return value;
2522 else
2523 return GetUnitMeleeSkill(target);
2526 float Unit::GetUnitDodgeChance() const
2528 if(hasUnitState(UNIT_STAT_STUNNED))
2529 return 0.0f;
2530 if( GetTypeId() == TYPEID_PLAYER )
2531 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2532 else
2534 if(((Creature const*)this)->isTotem())
2535 return 0.0f;
2536 else
2538 float dodge = 5.0f;
2539 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2540 return dodge > 0.0f ? dodge : 0.0f;
2545 float Unit::GetUnitParryChance() const
2547 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2548 return 0.0f;
2550 float chance = 0.0f;
2552 if(GetTypeId() == TYPEID_PLAYER)
2554 Player const* player = (Player const*)this;
2555 if(player->CanParry() )
2557 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2558 if(!tmpitem)
2559 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2561 if(tmpitem)
2562 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2565 else if(GetTypeId() == TYPEID_UNIT)
2567 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2569 chance = 5.0f;
2570 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2574 return chance > 0.0f ? chance : 0.0f;
2577 float Unit::GetUnitBlockChance() const
2579 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2580 return 0.0f;
2582 if(GetTypeId() == TYPEID_PLAYER)
2584 Player const* player = (Player const*)this;
2585 if(player->CanBlock() )
2587 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2588 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2589 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2591 // is player but has no block ability or no not broken shield equipped
2592 return 0.0f;
2594 else
2596 if(((Creature const*)this)->isTotem())
2597 return 0.0f;
2598 else
2600 float block = 5.0f;
2601 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2602 return block > 0.0f ? block : 0.0f;
2607 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2609 float crit;
2611 if(GetTypeId() == TYPEID_PLAYER)
2613 switch(attackType)
2615 case BASE_ATTACK:
2616 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2617 break;
2618 case OFF_ATTACK:
2619 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2620 break;
2621 case RANGED_ATTACK:
2622 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2623 break;
2624 // Just for good manner
2625 default:
2626 crit = 0.0f;
2627 break;
2630 else
2632 crit = 5.0f;
2633 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2636 // flat aura mods
2637 if(attackType == RANGED_ATTACK)
2638 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2639 else
2640 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2642 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2644 // reduce crit chance from Rating for players
2645 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2647 if (attackType==RANGED_ATTACK)
2648 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2649 else
2650 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2653 // Apply crit chance from defence skill
2654 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2656 if (crit < 0.0f)
2657 crit = 0.0f;
2658 return crit;
2661 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2663 uint32 value = 0;
2664 if(GetTypeId() == TYPEID_PLAYER)
2666 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2668 // feral or unarmed skill only for base attack
2669 if(attType != BASE_ATTACK && !item )
2670 return 0;
2672 if(((Player*)this)->IsInFeralForm())
2673 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2675 // weapon skill or (unarmed for base attack)
2676 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2678 // in PvP use full skill instead current skill value
2679 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2680 ? ((Player*)this)->GetMaxSkillValue(skill)
2681 : ((Player*)this)->GetSkillValue(skill);
2682 // Modify value from ratings
2683 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2684 switch (attType)
2686 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2687 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2688 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2691 else
2692 value = GetUnitMeleeSkill(target);
2693 return value;
2696 void Unit::_UpdateSpells( uint32 time )
2698 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2699 _UpdateAutoRepeatSpell();
2701 // remove finished spells from current pointers
2702 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2704 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2706 m_currentSpells[i]->SetReferencedFromCurrent(false);
2707 m_currentSpells[i] = NULL; // remove pointer
2711 // TODO: Find a better way to prevent crash when multiple auras are removed.
2712 m_removedAuras = 0;
2713 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2714 if ((*i).second)
2715 (*i).second->SetUpdated(false);
2717 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2719 next = i;
2720 ++next;
2721 if ((*i).second)
2723 // prevent double update
2724 if ((*i).second->IsUpdated())
2725 continue;
2726 (*i).second->SetUpdated(true);
2727 (*i).second->Update( time );
2728 // several auras can be deleted due to update
2729 if (m_removedAuras)
2731 if (m_Auras.empty()) break;
2732 next = m_Auras.begin();
2733 m_removedAuras = 0;
2738 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2740 if ((*i).second)
2742 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2744 RemoveAura(i);
2746 else
2748 ++i;
2751 else
2753 ++i;
2757 if(!m_gameObj.empty())
2759 std::list<GameObject*>::iterator ite1, dnext1;
2760 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2762 dnext1 = ite1;
2763 //(*i)->Update( difftime );
2764 if( !(*ite1)->isSpawned() )
2766 (*ite1)->SetOwnerGUID(0);
2767 (*ite1)->SetRespawnTime(0);
2768 (*ite1)->Delete();
2769 dnext1 = m_gameObj.erase(ite1);
2771 else
2772 ++dnext1;
2777 void Unit::_UpdateAutoRepeatSpell()
2779 //check "realtime" interrupts
2780 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2782 // cancel wand shoot
2783 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2784 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2785 m_AutoRepeatFirstCast = true;
2786 return;
2789 //apply delay
2790 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2791 setAttackTimer(RANGED_ATTACK,500);
2792 m_AutoRepeatFirstCast = false;
2794 //castroutine
2795 if (isAttackReady(RANGED_ATTACK))
2797 // Check if able to cast
2798 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CanCast(true))
2800 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2801 return;
2804 // we want to shoot
2805 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2806 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2808 // all went good, reset attack
2809 resetAttackTimer(RANGED_ATTACK);
2813 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2815 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2817 uint32 CSpellType = pSpell->GetCurrentContainer();
2819 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
2821 // break same type spell if it is not delayed
2822 InterruptSpell(CSpellType,false);
2824 // special breakage effects:
2825 switch (CSpellType)
2827 case CURRENT_GENERIC_SPELL:
2829 // generic spells always break channeled not delayed spells
2830 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
2832 // autorepeat breaking
2833 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
2835 // break autorepeat if not Auto Shot
2836 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2837 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2838 m_AutoRepeatFirstCast = true;
2840 } break;
2842 case CURRENT_CHANNELED_SPELL:
2844 // channel spells always break generic non-delayed and any channeled spells
2845 InterruptSpell(CURRENT_GENERIC_SPELL,false);
2846 InterruptSpell(CURRENT_CHANNELED_SPELL);
2848 // it also does break autorepeat if not Auto Shot
2849 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
2850 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
2851 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2852 } break;
2854 case CURRENT_AUTOREPEAT_SPELL:
2856 // only Auto Shoot does not break anything
2857 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2859 // generic autorepeats break generic non-delayed and channeled non-delayed spells
2860 InterruptSpell(CURRENT_GENERIC_SPELL,false);
2861 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
2863 // special action: set first cast flag
2864 m_AutoRepeatFirstCast = true;
2865 } break;
2867 default:
2869 // other spell types don't break anything now
2870 } break;
2873 // current spell (if it is still here) may be safely deleted now
2874 if (m_currentSpells[CSpellType])
2875 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
2877 // set new current spell
2878 m_currentSpells[CSpellType] = pSpell;
2879 pSpell->SetReferencedFromCurrent(true);
2882 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
2884 assert(spellType < CURRENT_MAX_SPELL);
2886 if(m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
2888 // send autorepeat cancel message for autorepeat spells
2889 if (spellType == CURRENT_AUTOREPEAT_SPELL)
2891 if(GetTypeId()==TYPEID_PLAYER)
2892 ((Player*)this)->SendAutoRepeatCancel();
2895 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
2896 m_currentSpells[spellType]->cancel();
2897 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
2898 m_currentSpells[spellType] = NULL;
2902 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
2904 // We don't do loop here to explicitly show that melee spell is excluded.
2905 // Maybe later some special spells will be excluded too.
2907 // generic spells are casted when they are not finished and not delayed
2908 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
2909 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
2910 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
2911 return(true);
2913 // channeled spells may be delayed, but they are still considered casted
2914 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
2915 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
2916 return(true);
2918 // autorepeat spells may be finished or delayed, but they are still considered casted
2919 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
2920 return(true);
2922 return(false);
2925 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
2927 // generic spells are interrupted if they are not finished or delayed
2928 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
2930 if ( (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
2931 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
2932 m_currentSpells[CURRENT_GENERIC_SPELL]->cancel();
2933 m_currentSpells[CURRENT_GENERIC_SPELL]->SetReferencedFromCurrent(false);
2934 m_currentSpells[CURRENT_GENERIC_SPELL] = NULL;
2937 // autorepeat spells are interrupted if they are not finished or delayed
2938 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
2940 // send disable autorepeat packet in any case
2941 if(GetTypeId()==TYPEID_PLAYER)
2942 ((Player*)this)->SendAutoRepeatCancel();
2944 if ( (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_FINISHED) &&
2945 (withDelayed || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_DELAYED) )
2946 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->cancel();
2947 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->SetReferencedFromCurrent(false);
2948 m_currentSpells[CURRENT_AUTOREPEAT_SPELL] = NULL;
2951 // channeled spells are interrupted if they are not finished, even if they are delayed
2952 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
2954 if (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)
2955 m_currentSpells[CURRENT_CHANNELED_SPELL]->cancel();
2956 m_currentSpells[CURRENT_CHANNELED_SPELL]->SetReferencedFromCurrent(false);
2957 m_currentSpells[CURRENT_CHANNELED_SPELL] = NULL;
2961 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
2963 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2964 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
2965 return m_currentSpells[i];
2966 return NULL;
2969 bool Unit::isInFront(Unit const* target, float distance, float arc) const
2971 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
2974 void Unit::SetInFront(Unit const* target)
2976 SetOrientation(GetAngle(target));
2979 bool Unit::isInBack(Unit const* target, float distance, float arc) const
2981 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
2984 bool Unit::isInAccessablePlaceFor(Creature const* c) const
2986 if(IsInWater())
2987 return c->canSwim();
2988 else
2989 return c->canWalk() || c->canFly();
2992 bool Unit::IsInWater() const
2994 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
2997 bool Unit::IsUnderWater() const
2999 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3002 void Unit::DeMorph()
3004 SetDisplayId(GetNativeDisplayId());
3007 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3009 int32 modifier = 0;
3011 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3012 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3013 modifier += (*i)->GetModifier()->m_amount;
3015 return modifier;
3018 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3020 float multiplier = 1.0f;
3022 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3023 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3024 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3026 return multiplier;
3029 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3031 int32 modifier = 0;
3033 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3034 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3035 if ((*i)->GetModifier()->m_amount > modifier)
3036 modifier = (*i)->GetModifier()->m_amount;
3038 return modifier;
3041 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3043 int32 modifier = 0;
3045 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3046 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3047 if ((*i)->GetModifier()->m_amount < modifier)
3048 modifier = (*i)->GetModifier()->m_amount;
3050 return modifier;
3053 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3055 int32 modifier = 0;
3057 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3058 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3060 Modifier* mod = (*i)->GetModifier();
3061 if (mod->m_miscvalue & misc_mask)
3062 modifier += mod->m_amount;
3064 return modifier;
3067 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3069 float multiplier = 1.0f;
3071 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3072 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3074 Modifier* mod = (*i)->GetModifier();
3075 if (mod->m_miscvalue & misc_mask)
3076 multiplier *= (100.0f + mod->m_amount)/100.0f;
3078 return multiplier;
3081 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3083 int32 modifier = 0;
3085 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3086 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3088 Modifier* mod = (*i)->GetModifier();
3089 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3090 modifier = mod->m_amount;
3093 return modifier;
3096 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3098 int32 modifier = 0;
3100 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3101 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3103 Modifier* mod = (*i)->GetModifier();
3104 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3105 modifier = mod->m_amount;
3108 return modifier;
3111 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3113 int32 modifier = 0;
3115 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3116 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3118 Modifier* mod = (*i)->GetModifier();
3119 if (mod->m_miscvalue == misc_value)
3120 modifier += mod->m_amount;
3122 return modifier;
3125 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3127 float multiplier = 1.0f;
3129 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3130 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3132 Modifier* mod = (*i)->GetModifier();
3133 if (mod->m_miscvalue == misc_value)
3134 multiplier *= (100.0f + mod->m_amount)/100.0f;
3136 return multiplier;
3139 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3141 int32 modifier = 0;
3143 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3144 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3146 Modifier* mod = (*i)->GetModifier();
3147 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3148 modifier = mod->m_amount;
3151 return modifier;
3154 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3156 int32 modifier = 0;
3158 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3159 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3161 Modifier* mod = (*i)->GetModifier();
3162 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3163 modifier = mod->m_amount;
3166 return modifier;
3169 bool Unit::AddAura(Aura *Aur)
3171 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3172 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3173 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3175 delete Aur;
3176 return false;
3179 if(Aur->GetTarget() != this)
3181 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3182 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3183 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3184 delete Aur;
3185 return false;
3188 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3190 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3191 AuraMap::iterator i = m_Auras.find( spair );
3193 // take out same spell
3194 if (i != m_Auras.end())
3196 // passive and persistent auras can stack with themselves any number of times
3197 if (!Aur->IsPassive() && !Aur->IsPersistent())
3199 // replace aura if next will > spell StackAmount
3200 if(aurSpellInfo->StackAmount)
3202 if(m_Auras.count(spair) >= aurSpellInfo->StackAmount)
3203 RemoveAura(i,AURA_REMOVE_BY_STACK);
3205 // if StackAmount==0 not allow auras from same caster
3206 else
3208 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3210 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3212 // can be only single (this check done at _each_ aura add
3213 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3214 break;
3217 bool stop = false;
3218 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3220 // DoT/HoT/etc
3221 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3222 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3223 case SPELL_AURA_PERIODIC_LEECH:
3224 case SPELL_AURA_PERIODIC_HEAL:
3225 case SPELL_AURA_OBS_MOD_HEALTH:
3226 case SPELL_AURA_PERIODIC_MANA_LEECH:
3227 case SPELL_AURA_PERIODIC_ENERGIZE:
3228 case SPELL_AURA_OBS_MOD_MANA:
3229 case SPELL_AURA_POWER_BURN_MANA:
3230 break;
3231 default: // not allow
3232 // can be only single (this check done at _each_ aura add
3233 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3234 stop = true;
3235 break;
3238 if(stop)
3239 break;
3245 // passive auras not stacable with other ranks
3246 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3248 if (!RemoveNoStackAurasDueToAura(Aur))
3250 delete Aur;
3251 return false; // couldn't remove conflicting aura with higher rank
3255 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3256 if (IsSingleTargetSpell(aurSpellInfo) && Aur->GetTarget())
3258 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3259 for(;;)
3261 Unit* caster = Aur->GetCaster();
3262 if(!caster) // caster deleted and not required adding scAura
3263 break;
3265 bool restart = false;
3266 AuraList& scAuras = caster->GetSingleCastAuras();
3267 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3269 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3270 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3272 if ((*itr)->IsInUse())
3274 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());
3275 continue;
3277 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3278 restart = true;
3279 break;
3283 if(!restart)
3285 // done
3286 scAuras.push_back(Aur);
3287 break;
3292 // add aura, register in lists and arrays
3293 Aur->_AddAura();
3294 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3295 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3297 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3300 Aur->ApplyModifier(true,true);
3301 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3302 return true;
3305 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3307 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3308 if(!spellInfo)
3309 return;
3310 AuraMap::iterator i,next;
3311 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3313 next = i;
3314 ++next;
3315 uint32 i_spellId = (*i).second->GetId();
3316 if((*i).second && i_spellId && i_spellId != spellId)
3318 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3320 RemoveAurasDueToSpell(i_spellId);
3322 if( m_Auras.empty() )
3323 break;
3324 else
3325 next = m_Auras.begin();
3331 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3333 if (!Aur)
3334 return false;
3336 SpellEntry const* spellProto = Aur->GetSpellProto();
3337 if (!spellProto)
3338 return false;
3340 uint32 spellId = Aur->GetId();
3342 // passive spell special case (only non stackable with ranks)
3343 if(IsPassiveSpell(spellId))
3345 if(IsPassiveSpellStackableWithRanks(spellProto))
3346 return true;
3349 uint32 effIndex = Aur->GetEffIndex();
3351 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3353 AuraMap::iterator i,next;
3354 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3356 next = i;
3357 ++next;
3358 if (!(*i).second) continue;
3360 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3362 if (!i_spellProto)
3363 continue;
3365 uint32 i_spellId = i_spellProto->Id;
3367 // early checks that spellId is passive non stackable spell
3368 if(IsPassiveSpell(i_spellId))
3370 // passive non-stackable spells not stackable only for same caster
3371 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3372 continue;
3374 // passive non-stackable spells not stackable only with another rank of same spell
3375 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3376 continue;
3379 uint32 i_effIndex = (*i).second->GetEffIndex();
3381 if(i_spellId == spellId) continue;
3383 bool is_triggered_by_spell = false;
3384 // prevent triggered aura of removing aura that triggered it
3385 for(int j = 0; j < 3; ++j)
3386 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3387 is_triggered_by_spell = true;
3388 if (is_triggered_by_spell) continue;
3390 for(int j = 0; j < 3; ++j)
3392 // prevent remove dummy triggered spells at next effect aura add
3393 switch(spellProto->Effect[j]) // main spell auras added added after triggered spell
3395 case SPELL_EFFECT_DUMMY:
3396 switch(spellId)
3398 case 5420: if(i_spellId==34123) is_triggered_by_spell = true; break;
3400 break;
3403 if(is_triggered_by_spell)
3404 break;
3406 // prevent remove form main spell by triggered passive spells
3407 switch(i_spellProto->EffectApplyAuraName[j]) // main aura added before triggered spell
3409 case SPELL_AURA_MOD_SHAPESHIFT:
3410 switch(i_spellId)
3412 case 24858: if(spellId==24905) is_triggered_by_spell = true; break;
3413 case 33891: if(spellId==5420 || spellId==34123) is_triggered_by_spell = true; break;
3414 case 34551: if(spellId==22688) is_triggered_by_spell = true; break;
3416 break;
3420 if(!is_triggered_by_spell)
3422 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3424 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3426 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3428 // cannot remove higher rank
3429 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3430 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3431 return false;
3433 // Its a parent aura (create this aura in ApplyModifier)
3434 if ((*i).second->IsInUse())
3436 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());
3437 continue;
3439 RemoveAurasDueToSpell(i_spellId);
3441 if( m_Auras.empty() )
3442 break;
3443 else
3444 next = m_Auras.begin();
3446 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3448 // Its a parent aura (create this aura in ApplyModifier)
3449 if ((*i).second->IsInUse())
3451 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());
3452 continue;
3454 RemoveAurasDueToSpell(i_spellId);
3456 if( m_Auras.empty() )
3457 break;
3458 else
3459 next = m_Auras.begin();
3461 // Potions stack aura by aura (elixirs/flask already checked)
3462 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3464 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3466 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3467 return false; // cannot remove higher rank
3469 // Its a parent aura (create this aura in ApplyModifier)
3470 if ((*i).second->IsInUse())
3472 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());
3473 continue;
3475 RemoveAura(i);
3476 next = i;
3481 return true;
3484 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3486 spellEffectPair spair = spellEffectPair(spellId, effindex);
3487 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3489 if(iter->second!=except)
3491 RemoveAura(iter);
3492 iter = m_Auras.lower_bound(spair);
3494 else
3495 ++iter;
3499 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3501 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3503 Aura *aur = iter->second;
3504 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3506 // Custom dispel case
3507 // Unstable Affliction
3508 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3510 int32 damage = aur->GetModifier()->m_amount*9;
3511 uint64 caster_guid = aur->GetCasterGUID();
3513 // Remove aura
3514 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3516 // backfire damage and silence
3517 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3519 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3521 else
3522 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3524 else
3525 ++iter;
3529 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3531 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3533 Aura *aur = iter->second;
3534 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3536 int32 basePoints = aur->GetBasePoints();
3537 // construct the new aura for the attacker
3538 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer);
3539 if(!new_aur)
3540 continue;
3542 // set its duration and maximum duration
3543 // max duration 2 minutes (in msecs)
3544 int32 dur = aur->GetAuraDuration();
3545 const int32 max_dur = 2*MINUTE*1000;
3546 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3547 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3549 // add the new aura to stealer
3550 stealer->AddAura(new_aur);
3552 // Remove aura as dispel
3553 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3555 else
3556 ++iter;
3560 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3562 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3564 if (iter->second->GetId() == spellId)
3565 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3566 else
3567 ++iter;
3571 void Unit::RemoveAurasWithDispelType( DispelType type )
3573 // Create dispel mask by dispel type
3574 uint32 dispelMask = GetDispellMask(type);
3575 // Dispel all existing auras vs current dispel type
3576 AuraMap& auras = GetAuras();
3577 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3579 SpellEntry const* spell = itr->second->GetSpellProto();
3580 if( (1<<spell->Dispel) & dispelMask )
3582 // Dispel aura
3583 RemoveAurasDueToSpell(spell->Id);
3584 itr = auras.begin();
3586 else
3587 ++itr;
3591 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3593 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3594 if(iter != m_Auras.end())
3595 RemoveAura(iter);
3598 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3600 for (int i = 0; i < 3; ++i)
3601 RemoveAura(spellId,i,except);
3604 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3606 for (int k=0; k < 3; ++k)
3608 spellEffectPair spair = spellEffectPair(spellId, k);
3609 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3611 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3613 RemoveAura(iter);
3614 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3616 else
3617 ++iter;
3622 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3624 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3626 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3627 RemoveAura(iter);
3628 else
3629 ++iter;
3633 void Unit::RemoveNotOwnSingleTargetAuras()
3635 // single target auras from other casters
3636 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3638 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3639 RemoveAura(iter);
3640 else
3641 ++iter;
3644 // single target auras at other targets
3645 AuraList& scAuras = GetSingleCastAuras();
3646 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3648 Aura* aura = *iter;
3649 if (aura->GetTarget()!=this)
3651 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3652 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3653 iter = scAuras.begin();
3655 else
3656 ++iter;
3661 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3663 Aura* Aur = i->second;
3664 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3666 Unit* caster = NULL;
3667 if (IsSingleTargetSpell(AurSpellInfo))
3669 caster = Aur->GetCaster();
3670 if(caster)
3672 AuraList& scAuras = caster->GetSingleCastAuras();
3673 scAuras.remove(Aur);
3675 else
3677 sLog.outError("Couldn't find the caster of the single target aura, may crash later!");
3678 assert(false);
3682 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3683 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3685 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3688 // Set remove mode
3689 Aur->SetRemoveMode(mode);
3690 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3691 // remove aura from list before to prevent deleting it before
3692 m_Auras.erase(i);
3693 ++m_removedAuras; // internal count used by unit update
3695 // Statue unsummoned at aura remove
3696 Totem* statue = NULL;
3697 bool caster_channeled = false;
3698 if(IsChanneledSpell(AurSpellInfo))
3700 if(!caster) // can be already located for IsSingleTargetSpell case
3701 caster = Aur->GetCaster();
3703 if(caster)
3705 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3706 statue = ((Totem*)caster);
3707 else
3708 caster_channeled = caster==this;
3712 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3713 Aur->ApplyModifier(false,true);
3714 Aur->_RemoveAura();
3715 delete Aur;
3717 if(caster_channeled)
3718 RemoveAurasAtChanneledTarget (AurSpellInfo);
3720 if(statue)
3721 statue->UnSummon();
3723 // only way correctly remove all auras from list
3724 if( m_Auras.empty() )
3725 i = m_Auras.end();
3726 else
3727 i = m_Auras.begin();
3730 void Unit::RemoveAllAuras()
3732 while (!m_Auras.empty())
3734 AuraMap::iterator iter = m_Auras.begin();
3735 RemoveAura(iter);
3739 void Unit::RemoveArenaAuras(bool onleave)
3741 // in join, remove positive buffs, on end, remove negative
3742 // used to remove positive visible auras in arenas
3743 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3745 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3746 && !iter->second->IsPassive() // don't remove passive auras
3747 && (!(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)
3748 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3749 RemoveAura(iter);
3750 else
3751 ++iter;
3755 void Unit::RemoveAllAurasOnDeath()
3757 // used just after dieing to remove all visible auras
3758 // and disable the mods for the passive ones
3759 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3761 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3762 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3763 else
3764 ++iter;
3768 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3770 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3771 if (iter != m_Auras.end())
3773 if (iter->second->GetAuraDuration() < delaytime)
3774 iter->second->SetAuraDuration(0);
3775 else
3776 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3777 iter->second->SendAuraUpdate(false);
3778 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3782 void Unit::_RemoveAllAuraMods()
3784 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3786 (*i).second->ApplyModifier(false);
3790 void Unit::_ApplyAllAuraMods()
3792 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3794 (*i).second->ApplyModifier(true);
3798 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3800 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3801 if (iter != m_Auras.end())
3802 return iter->second;
3803 return NULL;
3806 bool Unit::HasAura(uint32 spellId) const
3808 for (int i = 0; i < 3 ; ++i)
3810 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3811 if (iter != m_Auras.end())
3812 return true;
3814 return false;
3817 void Unit::AddDynObject(DynamicObject* dynObj)
3819 m_dynObjGUIDs.push_back(dynObj->GetGUID());
3822 void Unit::RemoveDynObject(uint32 spellid)
3824 if(m_dynObjGUIDs.empty())
3825 return;
3826 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3828 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3829 if(!dynObj)
3831 i = m_dynObjGUIDs.erase(i);
3833 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
3835 dynObj->Delete();
3836 i = m_dynObjGUIDs.erase(i);
3838 else
3839 ++i;
3843 void Unit::RemoveAllDynObjects()
3845 while(!m_dynObjGUIDs.empty())
3847 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3848 if(dynObj)
3849 dynObj->Delete();
3850 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
3854 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
3856 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3858 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3859 if(!dynObj)
3861 i = m_dynObjGUIDs.erase(i);
3862 continue;
3865 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
3866 return dynObj;
3867 ++i;
3869 return NULL;
3872 DynamicObject * Unit::GetDynObject(uint32 spellId)
3874 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3876 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3877 if(!dynObj)
3879 i = m_dynObjGUIDs.erase(i);
3880 continue;
3883 if (dynObj->GetSpellId() == spellId)
3884 return dynObj;
3885 ++i;
3887 return NULL;
3890 void Unit::AddGameObject(GameObject* gameObj)
3892 assert(gameObj && gameObj->GetOwnerGUID()==0);
3893 m_gameObj.push_back(gameObj);
3894 gameObj->SetOwnerGUID(GetGUID());
3897 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
3899 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
3901 // GO created by some spell
3902 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
3904 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
3905 // Need activate spell use for owner
3906 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
3907 ((Player*)this)->SendCooldownEvent(createBySpell);
3909 gameObj->SetOwnerGUID(0);
3910 m_gameObj.remove(gameObj);
3911 if(del)
3913 gameObj->SetRespawnTime(0);
3914 gameObj->Delete();
3918 void Unit::RemoveGameObject(uint32 spellid, bool del)
3920 if(m_gameObj.empty())
3921 return;
3922 std::list<GameObject*>::iterator i, next;
3923 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
3925 next = i;
3926 if(spellid == 0 || (*i)->GetSpellId() == spellid)
3928 (*i)->SetOwnerGUID(0);
3929 if(del)
3931 (*i)->SetRespawnTime(0);
3932 (*i)->Delete();
3935 next = m_gameObj.erase(i);
3937 else
3938 ++next;
3942 void Unit::RemoveAllGameObjects()
3944 // remove references to unit
3945 for(std::list<GameObject*>::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
3947 (*i)->SetOwnerGUID(0);
3948 (*i)->SetRespawnTime(0);
3949 (*i)->Delete();
3950 i = m_gameObj.erase(i);
3954 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
3956 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
3957 data.append(log->target->GetPackGUID());
3958 data.append(log->attacker->GetPackGUID());
3959 data << uint32(log->SpellID);
3960 data << uint32(log->damage); //damage amount
3961 data << uint32(0);
3962 data << uint8 (log->schoolMask); //damage school
3963 data << uint32(log->absorb); //AbsorbedDamage
3964 data << uint32(log->resist); //resist
3965 data << uint8 (log->phusicalLog); // damsge type? flag
3966 data << uint8 (log->unused); //unused
3967 data << uint32(log->blocked); //blocked
3968 data << uint32(log->HitInfo);
3969 data << uint8 (0); // flag to use extend data
3970 SendMessageToSet( &data, true );
3973 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
3975 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
3976 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
3977 data.append(target->GetPackGUID());
3978 data.append(GetPackGUID());
3979 data << uint32(SpellID);
3980 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
3981 data << uint32(0); // wotlk
3982 data << uint8(damageSchoolMask); // spell school
3983 data << uint32(AbsorbedDamage); // AbsorbedDamage
3984 data << uint32(Resist); // resist
3985 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
3986 data << uint8(0); // unk isFromAura
3987 data << uint32(Blocked); // blocked
3988 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
3989 data << uint8(0); // isDebug?
3990 SendMessageToSet( &data, true );
3993 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
3995 // Not much to do if no flags are set.
3996 if (procAttacker)
3997 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
3998 // Now go on with a victim's events'n'auras
3999 // Not much to do if no flags are set or there is no victim
4000 if(pVictim && pVictim->isAlive() && procVictim)
4001 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4004 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4006 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4007 data << uint32(spellID);
4008 data << uint64(GetGUID());
4009 data << uint8(0); // can be 0 or 1
4010 data << uint32(1); // target count
4011 // for(i = 0; i < target count; ++i)
4012 data << uint64(target->GetGUID()); // target GUID
4013 data << uint8(missInfo);
4014 // end loop
4015 SendMessageToSet(&data, true);
4018 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4020 uint32 count = 1;
4021 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4022 data << (uint32)damageInfo->HitInfo;
4023 data.append(GetPackGUID());
4024 data.append(damageInfo->target->GetPackGUID());
4025 data << (uint32)(damageInfo->damage); // Full damage
4026 data << uint32(0); // overkill value
4028 data << (uint8)count; // Sub damage count
4030 for(int i = 0; i < count; ++i)
4032 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4033 data << (float)damageInfo->damage; // sub damage
4034 data << (uint32)damageInfo->damage; // Sub Damage
4037 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4039 for(int i = 0; i < count; ++i)
4040 data << (uint32)damageInfo->absorb; // Absorb
4043 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4045 for(int i = 0; i < count; ++i)
4046 data << (uint32)damageInfo->resist; // Resist
4049 data << (uint32)damageInfo->TargetState;
4050 data << (uint32)0;
4051 data << (uint32)0;
4053 if(damageInfo->HitInfo & HITINFO_BLOCK)
4054 data << (uint32)damageInfo->blocked_amount;
4056 if(damageInfo->HitInfo & HITINFO_UNK3)
4057 data << uint32(0);
4059 if(damageInfo->HitInfo & HITINFO_UNK1)
4061 data << uint32(0);
4062 data << float(0);
4063 data << float(0);
4064 data << float(0);
4065 data << float(0);
4066 data << float(0);
4067 data << float(0);
4068 data << float(0);
4069 data << float(0);
4070 for(uint8 i = 0; i < 5; ++i)
4072 data << float(0);
4073 data << float(0);
4075 data << uint32(0);
4078 SendMessageToSet( &data, true );
4081 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4083 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4085 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4086 data << uint32(HitInfo); // flags
4087 data.append(GetPackGUID());
4088 data.append(target->GetPackGUID());
4089 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4090 data << uint32(0); // overkill value
4092 data << (uint8)SwingType; // count?
4094 // for(i = 0; i < SwingType; ++i)
4095 data << (uint32)damageSchoolMask;
4096 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4097 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4098 // end loop
4100 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4102 // for(i = 0; i < SwingType; ++i)
4103 data << uint32(AbsorbDamage);
4104 // end loop
4107 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4109 // for(i = 0; i < SwingType; ++i)
4110 data << uint32(Resist);
4111 // end loop
4114 data << (uint8)TargetState;
4115 data << (uint32)0;
4116 data << (uint32)0;
4118 if(HitInfo & HITINFO_BLOCK)
4120 data << uint32(BlockedAmount);
4123 if(HitInfo & HITINFO_UNK3)
4125 data << uint32(0);
4128 if(HitInfo & HITINFO_UNK1)
4130 data << uint32(0);
4131 data << float(0);
4132 data << float(0);
4133 data << float(0);
4134 data << float(0);
4135 data << float(0);
4136 data << float(0);
4137 data << float(0);
4138 data << float(0);
4139 for(uint8 i = 0; i < 5; ++i)
4141 data << float(0);
4142 data << float(0);
4144 data << uint32(0);
4147 SendMessageToSet( &data, true );
4150 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4152 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4154 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4155 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4157 uint32 triggered_spell_id = 0;
4158 Unit* target = pVictim;
4159 int32 basepoints0 = 0;
4161 switch(hasteSpell->SpellFamilyName)
4163 case SPELLFAMILY_ROGUE:
4165 switch(hasteSpell->Id)
4167 // Blade Flurry
4168 case 13877:
4169 case 33735:
4171 target = SelectNearbyTarget();
4172 if(!target)
4173 return false;
4174 basepoints0 = damage;
4175 triggered_spell_id = 22482;
4176 break;
4179 break;
4183 // processed charge only counting case
4184 if(!triggered_spell_id)
4185 return true;
4187 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4189 if(!triggerEntry)
4191 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4192 return false;
4195 // default case
4196 if(!target || target!=this && !target->isAlive())
4197 return false;
4199 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4200 return false;
4202 if(basepoints0)
4203 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4204 else
4205 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4207 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4208 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4210 return true;
4213 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4215 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4216 uint32 effIndex = triggeredByAura->GetEffIndex ();
4218 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4219 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4221 uint32 triggered_spell_id = 0;
4222 Unit* target = pVictim;
4223 int32 basepoints0 = 0;
4225 switch(dummySpell->SpellFamilyName)
4227 case SPELLFAMILY_GENERIC:
4229 switch (dummySpell->Id)
4231 // Eye for an Eye
4232 case 9799:
4233 case 25988:
4235 // prevent damage back from weapon special attacks
4236 if (!procSpell || procSpell->DmgClass != SPELL_DAMAGE_CLASS_MAGIC )
4237 return false;
4239 // return damage % to attacker but < 50% own total health
4240 basepoints0 = triggeredByAura->GetModifier()->m_amount*int32(damage)/100;
4241 if(basepoints0 > GetMaxHealth()/2)
4242 basepoints0 = GetMaxHealth()/2;
4244 triggered_spell_id = 25997;
4245 break;
4247 // Sweeping Strikes
4248 case 12328:
4249 case 18765:
4250 case 35429:
4252 // prevent chain of triggered spell from same triggered spell
4253 if(procSpell && procSpell->Id==26654)
4254 return false;
4256 target = SelectNearbyTarget();
4257 if(!target)
4258 return false;
4260 triggered_spell_id = 26654;
4261 break;
4263 // Unstable Power
4264 case 24658:
4266 if (!procSpell || procSpell->Id == 24659)
4267 return false;
4268 // Need remove one 24659 aura
4269 RemoveSingleAuraFromStack(24659, 0);
4270 RemoveSingleAuraFromStack(24659, 1);
4271 return true;
4273 // Restless Strength
4274 case 24661:
4276 // Need remove one 24662 aura
4277 RemoveSingleAuraFromStack(24662, 0);
4278 return true;
4280 // Adaptive Warding (Frostfire Regalia set)
4281 case 28764:
4283 if(!procSpell)
4284 return false;
4286 // find Mage Armor
4287 bool found = false;
4288 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4289 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4291 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4293 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4295 found=true;
4296 break;
4300 if(!found)
4301 return false;
4303 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4305 case SPELL_SCHOOL_NORMAL:
4306 case SPELL_SCHOOL_HOLY:
4307 return false; // ignored
4308 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4309 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4310 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4311 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4312 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4313 default:
4314 return false;
4317 target = this;
4318 break;
4320 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4321 case 27539:
4323 if(!procSpell)
4324 return false;
4326 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4328 case SPELL_SCHOOL_NORMAL:
4329 return false; // ignore
4330 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4331 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4332 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4333 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4334 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4335 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4336 default:
4337 return false;
4340 target = this;
4341 break;
4343 // Mana Leech (Passive) (Priest Pet Aura)
4344 case 28305:
4346 // Cast on owner
4347 target = GetOwner();
4348 if(!target)
4349 return false;
4351 basepoints0 = int32(damage * 2.5f); // manaregen
4352 triggered_spell_id = 34650;
4353 break;
4355 // Mark of Malice
4356 case 33493:
4358 // Cast finish spell at last charge
4359 if (triggeredByAura->m_procCharges > 1)
4360 return false;
4362 target = this;
4363 triggered_spell_id = 33494;
4364 break;
4366 // Twisted Reflection (boss spell)
4367 case 21063:
4368 triggered_spell_id = 21064;
4369 break;
4370 // Vampiric Aura (boss spell)
4371 case 38196:
4373 basepoints0 = 3 * damage; // 300%
4374 if (basepoints0 < 0)
4375 return false;
4377 triggered_spell_id = 31285;
4378 target = this;
4379 break;
4381 // Aura of Madness (Darkmoon Card: Madness trinket)
4382 //=====================================================
4383 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4384 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4385 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4386 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4387 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4388 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4389 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4390 // 41011 Martyr Complex: +35 stamina (All classes)
4391 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4392 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4393 case 39446:
4395 if(GetTypeId() != TYPEID_PLAYER)
4396 return false;
4398 // Select class defined buff
4399 switch (getClass())
4401 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4402 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4404 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4405 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4406 break;
4408 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4409 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4411 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4412 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4413 break;
4415 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4416 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4417 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4418 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4420 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4421 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4422 break;
4424 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4426 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4427 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4428 break;
4430 default:
4431 return false;
4434 target = this;
4435 if (roll_chance_i(10))
4436 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4437 break;
4440 // TODO: need find item for aura and triggered spells
4441 // Sunwell Exalted Caster Neck (??? neck)
4442 // cast ??? Light's Wrath if Exalted by Aldor
4443 // cast ??? Arcane Bolt if Exalted by Scryers*/
4444 case 46569:
4445 return false; // disable for while
4448 if(GetTypeId() != TYPEID_PLAYER)
4449 return false;
4451 // Get Aldor reputation rank
4452 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4454 target = this;
4455 triggered_spell_id = ???
4456 break;
4458 // Get Scryers reputation rank
4459 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4461 triggered_spell_id = ???
4462 break;
4464 return false;
4465 }/**/
4466 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4467 // cast 45479 Light's Wrath if Exalted by Aldor
4468 // cast 45429 Arcane Bolt if Exalted by Scryers
4469 case 45481:
4471 if(GetTypeId() != TYPEID_PLAYER)
4472 return false;
4474 // Get Aldor reputation rank
4475 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4477 target = this;
4478 triggered_spell_id = 45479;
4479 break;
4481 // Get Scryers reputation rank
4482 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4484 triggered_spell_id = 45429;
4485 break;
4487 return false;
4489 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4490 // cast 45480 Light's Strength if Exalted by Aldor
4491 // cast 45428 Arcane Strike if Exalted by Scryers
4492 case 45482:
4494 if(GetTypeId() != TYPEID_PLAYER)
4495 return false;
4497 // Get Aldor reputation rank
4498 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4500 target = this;
4501 triggered_spell_id = 45480;
4502 break;
4504 // Get Scryers reputation rank
4505 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4507 triggered_spell_id = 45428;
4508 break;
4510 return false;
4512 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4513 // cast 45431 Arcane Insight if Exalted by Aldor
4514 // cast 45432 Light's Ward if Exalted by Scryers
4515 case 45483:
4517 if(GetTypeId() != TYPEID_PLAYER)
4518 return false;
4520 // Get Aldor reputation rank
4521 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4523 target = this;
4524 triggered_spell_id = 45432;
4525 break;
4527 // Get Scryers reputation rank
4528 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4530 target = this;
4531 triggered_spell_id = 45431;
4532 break;
4534 return false;
4536 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4537 // cast 45478 Light's Salvation if Exalted by Aldor
4538 // cast 45430 Arcane Surge if Exalted by Scryers
4539 case 45484:
4541 if(GetTypeId() != TYPEID_PLAYER)
4542 return false;
4544 // Get Aldor reputation rank
4545 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4547 target = this;
4548 triggered_spell_id = 45478;
4549 break;
4551 // Get Scryers reputation rank
4552 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4554 triggered_spell_id = 45430;
4555 break;
4557 return false;
4560 break;
4562 case SPELLFAMILY_MAGE:
4564 // Magic Absorption
4565 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4567 if (getPowerType() != POWER_MANA)
4568 return false;
4570 // mana reward
4571 basepoints0 = (triggeredByAura->GetModifier()->m_amount * GetMaxPower(POWER_MANA) / 100);
4572 target = this;
4573 triggered_spell_id = 29442;
4574 break;
4576 // Master of Elements
4577 if (dummySpell->SpellIconID == 1920)
4579 if(!procSpell)
4580 return false;
4582 // mana cost save
4583 basepoints0 = procSpell->manaCost * triggeredByAura->GetModifier()->m_amount/100;
4584 if( basepoints0 <=0 )
4585 return false;
4587 target = this;
4588 triggered_spell_id = 29077;
4589 break;
4591 // Incanter's Regalia set (add trigger chance to Mana Shield)
4592 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4594 if(GetTypeId() != TYPEID_PLAYER)
4595 return false;
4597 target = this;
4598 triggered_spell_id = 37436;
4599 break;
4601 switch(dummySpell->Id)
4603 // Ignite
4604 case 11119:
4605 case 11120:
4606 case 12846:
4607 case 12847:
4608 case 12848:
4610 switch (dummySpell->Id)
4612 case 11119: basepoints0 = int32(0.04f*damage); break;
4613 case 11120: basepoints0 = int32(0.08f*damage); break;
4614 case 12846: basepoints0 = int32(0.12f*damage); break;
4615 case 12847: basepoints0 = int32(0.16f*damage); break;
4616 case 12848: basepoints0 = int32(0.20f*damage); break;
4617 default:
4618 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4619 return false;
4622 triggered_spell_id = 12654;
4623 break;
4625 // Combustion
4626 case 11129:
4628 //last charge and crit
4629 if (triggeredByAura->m_procCharges <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4631 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4632 return true; // charge counting (will removed)
4635 CastSpell(this, 28682, true, castItem, triggeredByAura);
4636 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4639 break;
4641 case SPELLFAMILY_WARRIOR:
4643 // Retaliation
4644 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4646 // check attack comes not from behind
4647 if (!HasInArc(M_PI, pVictim))
4648 return false;
4650 triggered_spell_id = 22858;
4651 break;
4653 else if (dummySpell->SpellIconID == 1697) // Second Wind
4655 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4656 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4657 return false;
4658 // Need stun or root mechanic
4659 if (procSpell->Mechanic != MECHANIC_ROOT && procSpell->Mechanic != MECHANIC_STUN)
4661 int32 i;
4662 for (i=0; i<3; i++)
4663 if (procSpell->EffectMechanic[i] == MECHANIC_ROOT || procSpell->EffectMechanic[i] == MECHANIC_STUN)
4664 break;
4665 if (i == 3)
4666 return false;
4669 switch (dummySpell->Id)
4671 case 29838: triggered_spell_id=29842; break;
4672 case 29834: triggered_spell_id=29841; break;
4673 default:
4674 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4675 return false;
4678 target = this;
4679 break;
4681 break;
4683 case SPELLFAMILY_WARLOCK:
4685 // Seed of Corruption
4686 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4688 Modifier* mod = triggeredByAura->GetModifier();
4689 // if damage is more than need or target die from damage deal finish spell
4690 if( mod->m_amount <= damage || GetHealth() <= damage )
4692 // remember guid before aura delete
4693 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4695 // Remove aura (before cast for prevent infinite loop handlers)
4696 RemoveAurasDueToSpell(triggeredByAura->GetId());
4698 // Cast finish spell (triggeredByAura already not exist!)
4699 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4700 return true; // no hidden cooldown
4703 // Damage counting
4704 mod->m_amount-=damage;
4705 return true;
4707 // Seed of Corruption (Mobs cast) - no die req
4708 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4710 Modifier* mod = triggeredByAura->GetModifier();
4711 // if damage is more than need deal finish spell
4712 if( mod->m_amount <= damage )
4714 // remember guid before aura delete
4715 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4717 // Remove aura (before cast for prevent infinite loop handlers)
4718 RemoveAurasDueToSpell(triggeredByAura->GetId());
4720 // Cast finish spell (triggeredByAura already not exist!)
4721 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
4722 return true; // no hidden cooldown
4724 // Damage counting
4725 mod->m_amount-=damage;
4726 return true;
4728 switch(dummySpell->Id)
4730 // Nightfall
4731 case 18094:
4732 case 18095:
4734 target = this;
4735 triggered_spell_id = 17941;
4736 break;
4738 //Soul Leech
4739 case 30293:
4740 case 30295:
4741 case 30296:
4743 // health
4744 basepoints0 = int32(damage*triggeredByAura->GetModifier()->m_amount/100);
4745 target = this;
4746 triggered_spell_id = 30294;
4747 break;
4749 // Shadowflame (Voidheart Raiment set bonus)
4750 case 37377:
4752 triggered_spell_id = 37379;
4753 break;
4755 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
4756 case 37381:
4758 target = GetPet();
4759 if(!target)
4760 return false;
4762 // heal amount
4763 basepoints0 = damage * triggeredByAura->GetModifier()->m_amount/100;
4764 triggered_spell_id = 37382;
4765 break;
4767 // Shadowflame Hellfire (Voidheart Raiment set bonus)
4768 case 39437:
4770 triggered_spell_id = 37378;
4771 break;
4774 break;
4776 case SPELLFAMILY_PRIEST:
4778 // Vampiric Touch
4779 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
4781 if(!pVictim || !pVictim->isAlive())
4782 return false;
4784 // pVictim is caster of aura
4785 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
4786 return false;
4788 // energize amount
4789 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
4790 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4791 return true; // no hidden cooldown
4793 switch(dummySpell->Id)
4795 // Vampiric Embrace
4796 case 15286:
4798 if(!pVictim || !pVictim->isAlive())
4799 return false;
4801 // pVictim is caster of aura
4802 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
4803 return false;
4805 // heal amount
4806 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
4807 pVictim->CastCustomSpell(pVictim,15290,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4808 return true; // no hidden cooldown
4810 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
4811 case 40438:
4813 // Shadow Word: Pain
4814 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
4815 triggered_spell_id = 40441;
4816 // Renew
4817 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
4818 triggered_spell_id = 40440;
4819 else
4820 return false;
4822 target = this;
4823 break;
4825 // Oracle Healing Bonus ("Garments of the Oracle" set)
4826 case 26169:
4828 // heal amount
4829 basepoints0 = int32(damage * 10/100);
4830 target = this;
4831 triggered_spell_id = 26170;
4832 break;
4834 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
4835 case 39372:
4837 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
4838 return false;
4840 // heal amount
4841 basepoints0 = int32(damage * 2 / 100);
4842 target = this;
4843 triggered_spell_id = 39373;
4844 break;
4846 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
4847 case 28809:
4849 triggered_spell_id = 28810;
4850 break;
4853 break;
4855 case SPELLFAMILY_DRUID:
4857 switch(dummySpell->Id)
4859 // Healing Touch (Dreamwalker Raiment set)
4860 case 28719:
4862 // mana back
4863 basepoints0 = int32(procSpell->manaCost * 30 / 100);
4864 target = this;
4865 triggered_spell_id = 28742;
4866 break;
4868 // Healing Touch Refund (Idol of Longevity trinket)
4869 case 28847:
4871 target = this;
4872 triggered_spell_id = 28848;
4873 break;
4875 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
4876 case 37288:
4877 case 37295:
4879 target = this;
4880 triggered_spell_id = 37238;
4881 break;
4883 // Druid Tier 6 Trinket
4884 case 40442:
4886 float chance;
4888 // Starfire
4889 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
4891 triggered_spell_id = 40445;
4892 chance = 25.f;
4894 // Rejuvenation
4895 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
4897 triggered_spell_id = 40446;
4898 chance = 25.f;
4900 // Mangle (cat/bear)
4901 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
4903 triggered_spell_id = 40452;
4904 chance = 40.f;
4906 else
4907 return false;
4909 if (!roll_chance_f(chance))
4910 return false;
4912 target = this;
4913 break;
4915 // Maim Interrupt
4916 case 44835:
4918 // Deadly Interrupt Effect
4919 triggered_spell_id = 32747;
4920 break;
4923 break;
4925 case SPELLFAMILY_ROGUE:
4927 switch(dummySpell->Id)
4929 // Deadly Throw Interrupt
4930 case 32748:
4932 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
4933 if(this == pVictim)
4934 return false;
4936 triggered_spell_id = 32747;
4937 break;
4940 // Quick Recovery
4941 if( dummySpell->SpellIconID == 2116 )
4943 if(!procSpell)
4944 return false;
4946 // only rogue's finishing moves (maybe need additional checks)
4947 if( procSpell->SpellFamilyName!=SPELLFAMILY_ROGUE ||
4948 (procSpell->SpellFamilyFlags & SPELLFAMILYFLAG_ROGUE__FINISHING_MOVE) == 0)
4949 return false;
4951 // energy cost save
4952 basepoints0 = procSpell->manaCost * triggeredByAura->GetModifier()->m_amount/100;
4953 if(basepoints0 <= 0)
4954 return false;
4956 target = this;
4957 triggered_spell_id = 31663;
4958 break;
4960 break;
4962 case SPELLFAMILY_HUNTER:
4964 // Thrill of the Hunt
4965 if ( dummySpell->SpellIconID == 2236 )
4967 if(!procSpell)
4968 return false;
4970 // mana cost save
4971 basepoints0 = procSpell->manaCost * 40/100;
4972 if(basepoints0 <= 0)
4973 return false;
4975 target = this;
4976 triggered_spell_id = 34720;
4977 break;
4979 break;
4981 case SPELLFAMILY_PALADIN:
4983 // TODO: spell list, formula change in 3.0.3
4984 // Seal of Righteousness - melee proc dummy
4985 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && triggeredByAura->GetEffIndex()==0)
4987 if(GetTypeId() != TYPEID_PLAYER)
4988 return false;
4990 uint32 spellId;
4991 switch (triggeredByAura->GetId())
4993 case 21084: spellId = 25742; break; // Rank 1
4994 case 20287: spellId = 25740; break; // Rank 2
4995 case 20288: spellId = 25739; break; // Rank 3
4996 case 20289: spellId = 25738; break; // Rank 4
4997 case 20290: spellId = 25737; break; // Rank 5
4998 case 20291: spellId = 25736; break; // Rank 6
4999 case 20292: spellId = 25735; break; // Rank 7
5000 case 20293: spellId = 25713; break; // Rank 8
5001 case 27155: spellId = 27156; break; // Rank 9
5002 default:
5003 sLog.outError("Unit::HandleDummyAuraProc: non handled possibly SoR (Id = %u)", triggeredByAura->GetId());
5004 return false;
5006 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
5007 float speed = (item ? item->GetProto()->Delay : BASE_ATTACK_TIME)/1000.0f;
5009 float damageBasePoints;
5010 if(item && item->GetProto()->InventoryType == INVTYPE_2HWEAPON)
5011 // two hand weapon
5012 damageBasePoints=1.20f*triggeredByAura->GetModifier()->m_amount * 1.2f * 1.03f * speed/100.0f + 1;
5013 else
5014 // one hand weapon/no weapon
5015 damageBasePoints=0.85f*ceil(triggeredByAura->GetModifier()->m_amount * 1.2f * 1.03f * speed/100.0f) - 1;
5017 int32 damagePoint = int32(damageBasePoints + 0.03f * (GetWeaponDamageRange(BASE_ATTACK,MINDAMAGE)+GetWeaponDamageRange(BASE_ATTACK,MAXDAMAGE))/2.0f) + 1;
5019 // apply damage bonuses manually
5020 if(damagePoint >= 0)
5021 damagePoint = SpellDamageBonus(pVictim, dummySpell, damagePoint, SPELL_DIRECT_DAMAGE);
5023 CastCustomSpell(pVictim,spellId,&damagePoint,NULL,NULL,true,NULL, triggeredByAura);
5024 return true; // no hidden cooldown
5026 // Seal of Blood do damage trigger
5027 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5029 switch(triggeredByAura->GetEffIndex())
5031 case 0:
5032 triggered_spell_id = 31893;
5033 break;
5034 case 1:
5036 // damage
5037 damage += CalculateDamage(BASE_ATTACK, false) * 35 / 100; // add spell damage from prev effect (35%)
5038 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5040 target = this;
5041 triggered_spell_id = 32221;
5042 break;
5047 switch(dummySpell->Id)
5049 // Holy Power (Redemption Armor set)
5050 case 28789:
5052 if(!pVictim)
5053 return false;
5055 // Set class defined buff
5056 switch (pVictim->getClass())
5058 case CLASS_PALADIN:
5059 case CLASS_PRIEST:
5060 case CLASS_SHAMAN:
5061 case CLASS_DRUID:
5062 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5063 break;
5064 case CLASS_MAGE:
5065 case CLASS_WARLOCK:
5066 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5067 break;
5068 case CLASS_HUNTER:
5069 case CLASS_ROGUE:
5070 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5071 break;
5072 case CLASS_WARRIOR:
5073 triggered_spell_id = 28790; // Increases the friendly target's armor
5074 break;
5075 default:
5076 return false;
5078 break;
5080 // TODO: fix basepoint calculation (changed in 3.0.3)
5081 // Seal of Vengeance
5082 case 31801:
5084 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5085 return false;
5087 triggered_spell_id = 31803;
5088 break;
5090 // Spiritual Attunement
5091 case 31785:
5092 case 33776:
5094 // if healed by another unit (pVictim)
5095 if(this == pVictim)
5096 return false;
5098 // heal amount
5099 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5100 target = this;
5101 triggered_spell_id = 31786;
5102 break;
5104 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5105 case 40470:
5107 if( !procSpell )
5108 return false;
5110 float chance;
5112 // Flash of light/Holy light
5113 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5115 triggered_spell_id = 40471;
5116 chance = 15.f;
5118 // Judgement
5119 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5121 triggered_spell_id = 40472;
5122 chance = 50.f;
5124 else
5125 return false;
5127 if (!roll_chance_f(chance))
5128 return false;
5130 break;
5133 break;
5135 case SPELLFAMILY_SHAMAN:
5137 switch(dummySpell->Id)
5139 // Totemic Power (The Earthshatterer set)
5140 case 28823:
5142 if( !pVictim )
5143 return false;
5145 // Set class defined buff
5146 switch (pVictim->getClass())
5148 case CLASS_PALADIN:
5149 case CLASS_PRIEST:
5150 case CLASS_SHAMAN:
5151 case CLASS_DRUID:
5152 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5153 break;
5154 case CLASS_MAGE:
5155 case CLASS_WARLOCK:
5156 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5157 break;
5158 case CLASS_HUNTER:
5159 case CLASS_ROGUE:
5160 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5161 break;
5162 case CLASS_WARRIOR:
5163 triggered_spell_id = 28827; // Increases the friendly target's armor
5164 break;
5165 default:
5166 return false;
5168 break;
5170 // Lesser Healing Wave (Totem of Flowing Water Relic)
5171 case 28849:
5173 target = this;
5174 triggered_spell_id = 28850;
5175 break;
5177 // Windfury Weapon (Passive) 1-5 Ranks
5178 case 33757:
5180 if(GetTypeId()!=TYPEID_PLAYER)
5181 return false;
5183 if(!castItem || !castItem->IsEquipped())
5184 return false;
5186 // custom cooldown processing case
5187 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5188 return false;
5190 uint32 spellId;
5191 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5193 case 283: spellId = 33757; break; //1 Rank
5194 case 284: spellId = 33756; break; //2 Rank
5195 case 525: spellId = 33755; break; //3 Rank
5196 case 1669:spellId = 33754; break; //4 Rank
5197 case 2636:spellId = 33727; break; //5 Rank
5198 default:
5200 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5201 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5202 return false;
5206 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5207 if(!windfurySpellEntry)
5209 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5210 return false;
5213 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry,0,windfurySpellEntry->EffectBasePoints[0],pVictim);
5215 // Off-Hand case
5216 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5218 // Value gained from additional AP
5219 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5220 triggered_spell_id = 33750;
5222 // Main-Hand case
5223 else
5225 // Value gained from additional AP
5226 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5227 triggered_spell_id = 25504;
5230 // apply cooldown before cast to prevent processing itself
5231 if( cooldown )
5232 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5234 // Attack Twice
5235 for ( uint32 i = 0; i<2; ++i )
5236 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5238 return true;
5240 // Shaman Tier 6 Trinket
5241 case 40463:
5243 if( !procSpell )
5244 return false;
5246 float chance;
5247 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5249 triggered_spell_id = 40465; // Lightning Bolt
5250 chance = 15.f;
5252 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5254 triggered_spell_id = 40465; // Lesser Healing Wave
5255 chance = 10.f;
5257 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5259 triggered_spell_id = 40466; // Stormstrike
5260 chance = 50.f;
5262 else
5263 return false;
5265 if (!roll_chance_f(chance))
5266 return false;
5268 target = this;
5269 break;
5273 // Earth Shield
5274 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5276 if(GetTypeId() != TYPEID_PLAYER)
5277 return false;
5279 // heal
5280 basepoints0 = triggeredByAura->GetModifier()->m_amount;
5281 target = this;
5282 triggered_spell_id = 379;
5283 break;
5285 // Lightning Overload
5286 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5288 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5289 return false;
5291 // custom cooldown processing case
5292 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5293 return false;
5295 uint32 spellId = 0;
5296 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5297 switch (procSpell->Id)
5299 // Lightning Bolt
5300 case 403: spellId = 45284; break; // Rank 1
5301 case 529: spellId = 45286; break; // Rank 2
5302 case 548: spellId = 45287; break; // Rank 3
5303 case 915: spellId = 45288; break; // Rank 4
5304 case 943: spellId = 45289; break; // Rank 5
5305 case 6041: spellId = 45290; break; // Rank 6
5306 case 10391: spellId = 45291; break; // Rank 7
5307 case 10392: spellId = 45292; break; // Rank 8
5308 case 15207: spellId = 45293; break; // Rank 9
5309 case 15208: spellId = 45294; break; // Rank 10
5310 case 25448: spellId = 45295; break; // Rank 11
5311 case 25449: spellId = 45296; break; // Rank 12
5312 case 49237: spellId = 49239; break; // Rank 13
5313 case 49238: spellId = 49240; break; // Rank 14
5314 // Chain Lightning
5315 case 421: spellId = 45297; break; // Rank 1
5316 case 930: spellId = 45298; break; // Rank 2
5317 case 2860: spellId = 45299; break; // Rank 3
5318 case 10605: spellId = 45300; break; // Rank 4
5319 case 25439: spellId = 45301; break; // Rank 5
5320 case 25442: spellId = 45302; break; // Rank 6
5321 case 49268: spellId = 49270; break; // Rank 7
5322 case 49269: spellId = 49271; break; // Rank 8
5323 default:
5324 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5325 return false;
5327 // No thread generated mod
5328 SpellModifier *mod = new SpellModifier;
5329 mod->op = SPELLMOD_THREAT;
5330 mod->value = -100;
5331 mod->type = SPELLMOD_PCT;
5332 mod->spellId = dummySpell->Id;
5333 mod->mask = 0x0000000000000003LL;
5334 mod->mask2= 0LL;
5335 ((Player*)this)->AddSpellMod(mod, true);
5337 // Remove cooldown (Chain Lightning - have Category Recovery time)
5338 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5339 ((Player*)this)->RemoveSpellCooldown(spellId);
5341 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5343 ((Player*)this)->AddSpellMod(mod, false);
5345 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5346 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5348 return true;
5350 break;
5352 default:
5353 break;
5356 // processed charge only counting case
5357 if(!triggered_spell_id)
5358 return true;
5360 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5362 if(!triggerEntry)
5364 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5365 return false;
5368 // default case
5369 if(!target || target!=this && !target->isAlive())
5370 return false;
5372 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5373 return false;
5375 if(basepoints0)
5376 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5377 else
5378 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5380 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5381 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5383 return true;
5386 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5388 // Get triggered aura spell info
5389 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5391 // Basepoints of trigger aura
5392 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5394 // Set trigger spell id, target, custom basepoints
5395 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
5396 Unit* target = NULL;
5397 int32 basepoints0 = 0;
5399 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
5400 basepoints0 = triggerAmount;
5402 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5403 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5405 // Try handle uncnown trigger spells
5406 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
5408 switch (auraSpellInfo->SpellFamilyName)
5410 case SPELLFAMILY_GENERIC:
5411 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
5412 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
5413 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
5414 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
5415 trigger_spell_id = 23781;
5416 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
5417 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
5419 // trigger_spell_id = 48877;
5421 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
5423 // trigger_spell_id = 59233;
5425 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
5427 // trigger_spell_id = 29471; // gain mana
5428 // 27526; // drain mana if possible
5430 //else if (auraSpellInfo->Id==50844) // Blood Mirror
5431 //else if (auraSpellInfo->Id==54476) // Blood Presence
5432 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
5433 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
5434 //else if (auraSpellInfo->Id==52856) // Charge
5435 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
5437 // Pct value stored in dummy
5438 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
5439 target = pVictim;
5440 break;
5442 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
5443 // trigger_spell_id = 41249;
5444 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
5445 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
5446 //else if (auraSpellInfo->Id==41054) // Copy Weapon
5447 // trigger_spell_id = 41055;
5448 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
5449 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
5450 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
5452 uint32 stat = 0;
5453 // strength
5454 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
5455 // agility
5456 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
5457 // intellect
5458 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
5459 // spirit
5460 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
5462 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
5463 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
5464 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
5465 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
5466 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
5467 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
5468 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
5469 trigger_spell_id = 33898;
5470 //else if (auraSpellInfo->Id==18943) // Double Attack
5471 //else if (auraSpellInfo->Id==19194) // Double Attack
5472 //else if (auraSpellInfo->Id==19817) // Double Attack
5473 //else if (auraSpellInfo->Id==19818) // Double Attack
5474 //else if (auraSpellInfo->Id==22835) // Drunken Rage
5475 // trigger_spell_id = 14822;
5477 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
5479 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
5481 case 34191:
5482 case 34329:
5483 case 34524:
5484 case 34582:
5485 case 36733:
5486 break;
5487 default:
5488 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
5489 return false;
5491 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
5492 switch (procSpell->School)
5494 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
5495 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
5496 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
5497 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
5498 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
5499 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
5500 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
5501 default:
5502 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
5503 return false;
5507 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
5508 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
5509 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
5510 //else if (auraSpellInfo->Id==35321) // Gushing Wound
5511 //else if (auraSpellInfo->Id==38363) // Gushing Wound
5512 //else if (auraSpellInfo->Id==39215) // Gushing Wound
5513 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
5514 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
5515 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
5516 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
5517 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
5518 //else if (auraSpellInfo->Id==40250) // Improved Duration
5519 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
5520 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
5521 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
5522 // Mana Drain Trigger
5524 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
5525 if (this && this->isAlive())
5526 CastSpell(this, 29471, true, castItem, triggeredByAura);
5527 if (pVictim && pVictim->isAlive())
5528 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
5529 return true;
5531 //else if (auraSpellInfo->Id==55580) // Mana Link
5532 //else if (auraSpellInfo->Id==45903) // Offensive State
5533 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
5534 //else if (auraSpellInfo->Id==43453) // Rune Ward
5535 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
5536 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
5537 //else if (auraSpellInfo->Id==34783) // Spell Reflection
5538 //else if (auraSpellInfo->Id==36096) // Spell Reflection
5539 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
5540 //else if (auraSpellInfo->Id==36207) // Steal Weapon
5541 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
5542 //else if (auraSpellInfo->Id==35205) // Vanish
5543 //else if (auraSpellInfo->Id==42730) // Woe Strike
5544 //else if (auraSpellInfo->Id==59735) // Woe Strike
5545 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
5546 break;
5547 case SPELLFAMILY_MAGE:
5548 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
5550 switch (auraSpellInfo->Id)
5552 case 31641: // Rank 1
5553 case 31642: // Rank 2
5554 trigger_spell_id = 31643;
5555 break;
5556 default:
5557 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
5558 return false;
5561 break;
5562 case SPELLFAMILY_WARRIOR:
5563 if (auraSpellInfo->Id == 50421) // Scent of Blood
5564 trigger_spell_id = 50422;
5565 break;
5566 case SPELLFAMILY_WARLOCK:
5568 // Pyroclasm
5569 if (auraSpellInfo->SpellIconID == 1137)
5571 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
5572 return false;
5573 // Calculate spell tick count for spells
5574 uint32 tick = 1; // Default tick = 1
5576 // Hellfire have 15 tick
5577 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
5578 tick = 15;
5579 // Rain of Fire have 4 tick
5580 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
5581 tick = 4;
5582 else
5583 return false;
5585 // Calculate chance = baseChance / tick
5586 float chance = 0;
5587 switch (auraSpellInfo->Id)
5589 case 18096: chance = 13.0f / tick; break;
5590 case 18073: chance = 26.0f / tick; break;
5592 // Roll chance
5593 if (!roll_chance_f(chance))
5594 return false;
5596 trigger_spell_id = 18093;
5598 // Drain Soul
5599 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
5601 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
5602 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
5604 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
5606 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
5607 // Drain Soul
5608 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
5609 break;
5612 // Not remove charge (aura removed on death in any cases)
5613 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
5614 return false;
5616 // Nether Protection
5617 else if (auraSpellInfo->SpellIconID == 1985)
5619 if (!procSpell)
5620 return false;
5621 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5623 case SPELL_SCHOOL_NORMAL:
5624 case SPELL_SCHOOL_HOLY:
5625 return false; // ignore
5626 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
5627 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
5628 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
5629 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
5630 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
5631 default:
5632 return false;
5635 break;
5637 case SPELLFAMILY_PRIEST:
5639 // Greater Heal Refund
5640 if (auraSpellInfo->Id==37594)
5641 trigger_spell_id = 37595;
5642 // Blessed Recovery
5643 else if (auraSpellInfo->SpellIconID == 1875)
5645 switch (auraSpellInfo->Id)
5647 case 27811: trigger_spell_id = 27813; break;
5648 case 27815: trigger_spell_id = 27817; break;
5649 case 27816: trigger_spell_id = 27818; break;
5650 default:
5651 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
5652 return false;
5654 basepoints0 = damage * triggerAmount / 100 / 3;
5655 target = this;
5657 break;
5659 case SPELLFAMILY_DRUID:
5661 // Druid Forms Trinket
5662 if (auraSpellInfo->Id==37336)
5664 switch(m_form)
5666 case FORM_NONE: trigger_spell_id = 37344;break;
5667 case FORM_CAT: trigger_spell_id = 37341;break;
5668 case FORM_BEAR:
5669 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
5670 case FORM_TREE: trigger_spell_id = 37342;break;
5671 case FORM_MOONKIN: trigger_spell_id = 37343;break;
5672 default:
5673 return false;
5676 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
5677 // trigger_spell_id = ????;
5678 // Leader of the Pack
5679 else if (auraSpellInfo->Id == 24932)
5681 if (triggerAmount == 0)
5682 return false;
5683 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5684 trigger_spell_id = 34299;
5686 break;
5688 case SPELLFAMILY_HUNTER:
5689 break;
5690 case SPELLFAMILY_PALADIN:
5693 // Blessed Life
5694 if (auraSpellInfo->SpellIconID == 2137)
5696 switch (auraSpellInfo->Id)
5698 case 31828: // Rank 1
5699 case 31829: // Rank 2
5700 case 31830: // Rank 3
5701 break;
5702 default:
5703 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
5704 return false;
5708 // Healing Discount
5709 if (auraSpellInfo->Id==37705)
5711 trigger_spell_id = 37706;
5712 target = this;
5714 // Soul Preserver
5715 if (auraSpellInfo->Id==60510)
5717 trigger_spell_id = 60515;
5718 target = this;
5720 // Illumination
5721 else if (auraSpellInfo->SpellIconID==241)
5723 if(!procSpell)
5724 return false;
5725 // procspell is triggered spell but we need mana cost of original casted spell
5726 uint32 originalSpellId = procSpell->Id;
5727 // Holy Shock
5728 if(procSpell->SpellFamilyFlags & 0x00200000)
5730 switch(procSpell->Id)
5732 case 25914: originalSpellId = 20473; break;
5733 case 25913: originalSpellId = 20929; break;
5734 case 25903: originalSpellId = 20930; break;
5735 case 27175: originalSpellId = 27174; break;
5736 case 33074: originalSpellId = 33072; break;
5737 default:
5738 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
5739 return false;
5742 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
5743 if(!originalSpell)
5745 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
5746 return false;
5748 // percent stored in effect 1 (class scripts) base points
5749 basepoints0 = originalSpell->manaCost*(auraSpellInfo->EffectBasePoints[1]+1)/100;
5750 trigger_spell_id = 20272;
5751 target = this;
5753 // Lightning Capacitor
5754 else if (auraSpellInfo->Id==37657)
5756 if(!pVictim || !pVictim->isAlive())
5757 return false;
5758 // stacking
5759 CastSpell(this, 37658, true, NULL, triggeredByAura);
5760 // counting
5761 uint32 count = 0;
5762 AuraList const& dummyAura = GetAurasByType(SPELL_AURA_DUMMY);
5763 for(AuraList::const_iterator itr = dummyAura.begin(); itr != dummyAura.end(); ++itr)
5764 if((*itr)->GetId()==37658)
5765 ++count;
5766 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
5767 if(count < triggerAmount)
5768 return false;
5770 RemoveAurasDueToSpell(37658);
5771 trigger_spell_id = 37661;
5772 target = pVictim;
5774 // Thunder Capacitor
5775 else if (auraSpellInfo->Id == 54841)
5777 if(!pVictim || !pVictim->isAlive())
5778 return false;
5779 // stacking
5780 CastSpell(this, 54842, true, NULL, triggeredByAura);
5781 // counting
5782 uint32 count = 0;
5783 AuraList const& dummyAura = GetAurasByType(SPELL_AURA_DUMMY);
5784 for(AuraList::const_iterator itr = dummyAura.begin(); itr != dummyAura.end(); ++itr)
5785 if((*itr)->GetId()==54842)
5786 ++count;
5787 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
5788 if(count < triggerAmount)
5789 return false;
5791 RemoveAurasDueToSpell(54842);
5792 trigger_spell_id = 54843;
5793 target = pVictim;
5795 break;
5797 case SPELLFAMILY_SHAMAN:
5799 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
5800 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
5802 switch(auraSpellInfo->Id)
5804 case 324: // Rank 1
5805 trigger_spell_id = 26364; break;
5806 case 325: // Rank 2
5807 trigger_spell_id = 26365; break;
5808 case 905: // Rank 3
5809 trigger_spell_id = 26366; break;
5810 case 945: // Rank 4
5811 trigger_spell_id = 26367; break;
5812 case 8134: // Rank 5
5813 trigger_spell_id = 26369; break;
5814 case 10431: // Rank 6
5815 trigger_spell_id = 26370; break;
5816 case 10432: // Rank 7
5817 trigger_spell_id = 26363; break;
5818 case 25469: // Rank 8
5819 trigger_spell_id = 26371; break;
5820 case 25472: // Rank 9
5821 trigger_spell_id = 26372; break;
5822 case 49280: // Rank 10
5823 trigger_spell_id = 49278; break;
5824 case 49281: // Rank 11
5825 trigger_spell_id = 49279; break;
5826 default:
5827 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
5828 return false;
5831 // Lightning Shield (The Ten Storms set)
5832 else if (auraSpellInfo->Id == 23551)
5834 trigger_spell_id = 23552;
5835 target = pVictim;
5837 // Damage from Lightning Shield (The Ten Storms set)
5838 else if (auraSpellInfo->Id == 23552)
5839 trigger_spell_id = 27635;
5840 // Mana Surge (The Earthfury set)
5841 else if (auraSpellInfo->Id == 23572)
5843 if(!procSpell)
5844 return false;
5845 basepoints0 = procSpell->manaCost * 35 / 100;
5846 trigger_spell_id = 23571;
5847 target = this;
5849 // Nature's Guardian
5850 else if (auraSpellInfo->SpellIconID == 2013)
5852 // Check health condition - should drop to less 30% (damage deal after this!)
5853 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
5854 return false;
5856 if(pVictim && pVictim->isAlive())
5857 pVictim->getThreatManager().modifyThreatPercent(this,-10);
5859 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5860 trigger_spell_id = 31616;
5861 target = this;
5863 break;
5865 case SPELLFAMILY_DEATHKNIGHT:
5867 // Acclimation
5868 if (auraSpellInfo->SpellIconID == 1930)
5870 if (!procSpell)
5871 return false;
5872 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5874 case SPELL_SCHOOL_NORMAL:
5875 return false; // ignore
5876 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
5877 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
5878 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
5879 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
5880 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
5881 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
5882 default:
5883 return false;
5886 // Blood Presence
5887 else if (auraSpellInfo->Id == 48266)
5889 if (GetTypeId() != TYPEID_PLAYER)
5890 return false;
5891 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
5892 return false;
5893 trigger_spell_id = 50475;
5894 basepoints0 = damage * triggerAmount / 100;
5896 break;
5898 default:
5899 break;
5903 // All ok. Check current trigger spell
5904 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
5905 if ( triggerEntry == NULL )
5907 // Not cast unknown spell
5908 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
5909 return false;
5912 // not allow proc extra attack spell at extra attack
5913 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
5914 return false;
5916 // Costum requirements (not listed in procEx) Warning! damage dealing after this
5917 // Custom triggered spells
5918 switch (auraSpellInfo->Id)
5920 // Persistent Shield (Scarab Brooch trinket)
5921 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
5922 case 26467:
5924 basepoints0 = damage * 15 / 100;
5925 target = pVictim;
5926 trigger_spell_id = 26470;
5927 break;
5929 // Cheat Death
5930 case 28845:
5932 // When your health drops below 20% ....
5933 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
5934 return false;
5935 break;
5937 // Deadly Swiftness (Rank 1)
5938 case 31255:
5940 // whenever you deal damage to a target who is below 20% health.
5941 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
5942 return false;
5944 target = this;
5945 trigger_spell_id = 22588;
5947 // Greater Heal Refund (Avatar Raiment set)
5948 case 37594:
5950 // Not give if target alredy have full health
5951 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
5952 return false;
5953 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
5954 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
5955 return false;
5956 break;
5958 // Bonus Healing (Crystal Spire of Karabor mace)
5959 case 40971:
5961 // If your target is below $s1% health
5962 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
5963 return false;
5964 break;
5966 // Evasive Maneuvers (Commendation of Kael`thas trinket)
5967 case 45057:
5969 // reduce you below $s1% health
5970 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
5971 return false;
5972 break;
5976 // Costum basepoints/target for exist spell
5977 // dummy basepoints or other customs
5978 switch(trigger_spell_id)
5980 // Cast positive spell on enemy target
5981 case 7099: // Curse of Mending
5982 case 39647: // Curse of Mending
5983 case 29494: // Temptation
5984 case 20233: // Improved Lay on Hands (cast on target)
5986 target = pVictim;
5987 break;
5989 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
5990 case 15250: // Rogue Setup
5992 if(!pVictim || pVictim != getVictim()) // applied only for main target
5993 return false;
5994 break; // continue normal case
5996 // Finish movies that add combo
5997 case 14189: // Seal Fate (Netherblade set)
5998 case 14157: // Ruthlessness
6000 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6001 break;
6003 // Shamanistic Rage triggered spell
6004 case 30824:
6006 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6007 trigger_spell_id = 30824;
6008 break;
6010 // Enlightenment (trigger only from mana cost spells)
6011 case 35095:
6013 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6014 return false;
6015 break;
6019 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6020 return false;
6022 // try detect target manually if not set
6023 if ( target == NULL )
6024 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6026 // default case
6027 if(!target || target!=this && !target->isAlive())
6028 return false;
6030 if(basepoints0)
6031 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6032 else
6033 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6035 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6036 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6038 return true;
6041 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6043 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6045 if(!pVictim || !pVictim->isAlive())
6046 return false;
6048 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6049 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6051 uint32 triggered_spell_id = 0;
6053 switch(scriptId)
6055 case 836: // Improved Blizzard (Rank 1)
6057 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6058 return false;
6059 triggered_spell_id = 12484;
6060 break;
6062 case 988: // Improved Blizzard (Rank 2)
6064 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6065 return false;
6066 triggered_spell_id = 12485;
6067 break;
6069 case 989: // Improved Blizzard (Rank 3)
6071 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6072 return false;
6073 triggered_spell_id = 12486;
6074 break;
6076 case 4086: // Improved Mend Pet (Rank 1)
6077 case 4087: // Improved Mend Pet (Rank 2)
6079 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6080 if(!roll_chance_i(chance))
6081 return false;
6083 triggered_spell_id = 24406;
6084 break;
6086 case 4533: // Dreamwalker Raiment 2 pieces bonus
6088 // Chance 50%
6089 if (!roll_chance_i(50))
6090 return false;
6092 switch (pVictim->getPowerType())
6094 case POWER_MANA: triggered_spell_id = 28722; break;
6095 case POWER_RAGE: triggered_spell_id = 28723; break;
6096 case POWER_ENERGY: triggered_spell_id = 28724; break;
6097 default:
6098 return false;
6100 break;
6102 case 4537: // Dreamwalker Raiment 6 pieces bonus
6103 triggered_spell_id = 28750; // Blessing of the Claw
6104 break;
6105 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6106 triggered_spell_id = 37445; // Mana Surge
6107 break;
6110 // not processed
6111 if(!triggered_spell_id)
6112 return false;
6114 // standard non-dummy case
6115 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6117 if(!triggerEntry)
6119 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6120 return false;
6123 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6124 return false;
6126 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6128 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6129 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6131 return true;
6134 void Unit::setPowerType(Powers new_powertype)
6136 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6138 if(GetTypeId() == TYPEID_PLAYER)
6140 if(((Player*)this)->GetGroup())
6141 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6143 else if(((Creature*)this)->isPet())
6145 Pet *pet = ((Pet*)this);
6146 if(pet->isControlled())
6148 Unit *owner = GetOwner();
6149 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6150 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6154 switch(new_powertype)
6156 default:
6157 case POWER_MANA:
6158 break;
6159 case POWER_RAGE:
6160 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6161 SetPower( POWER_RAGE,0);
6162 break;
6163 case POWER_FOCUS:
6164 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6165 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6166 break;
6167 case POWER_ENERGY:
6168 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6169 SetPower( POWER_ENERGY,0);
6170 break;
6171 case POWER_HAPPINESS:
6172 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6173 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6174 break;
6178 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6180 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6181 if(!entry)
6183 static uint64 guid = 0; // prevent repeating spam same faction problem
6185 if(GetGUID() != guid)
6187 if(GetTypeId() == TYPEID_PLAYER)
6188 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6189 else
6190 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6191 guid = GetGUID();
6194 return entry;
6197 bool Unit::IsHostileTo(Unit const* unit) const
6199 // always non-hostile to self
6200 if(unit==this)
6201 return false;
6203 // always non-hostile to GM in GM mode
6204 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6205 return false;
6207 // always hostile to enemy
6208 if(getVictim()==unit || unit->getVictim()==this)
6209 return true;
6211 // test pet/charm masters instead pers/charmeds
6212 Unit const* testerOwner = GetCharmerOrOwner();
6213 Unit const* targetOwner = unit->GetCharmerOrOwner();
6215 // always hostile to owner's enemy
6216 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6217 return true;
6219 // always hostile to enemy owner
6220 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6221 return true;
6223 // always hostile to owner of owner's enemy
6224 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6225 return true;
6227 Unit const* tester = testerOwner ? testerOwner : this;
6228 Unit const* target = targetOwner ? targetOwner : unit;
6230 // always non-hostile to target with common owner, or to owner/pet
6231 if(tester==target)
6232 return false;
6234 // special cases (Duel, etc)
6235 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6237 Player const* pTester = (Player const*)tester;
6238 Player const* pTarget = (Player const*)target;
6240 // Duel
6241 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6242 return true;
6244 // Group
6245 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6246 return false;
6248 // Sanctuary
6249 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6250 return false;
6252 // PvP FFA state
6253 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))
6254 return true;
6256 //= PvP states
6257 // Green/Blue (can't attack)
6258 if(pTester->GetTeam()==pTarget->GetTeam())
6259 return false;
6261 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6262 return pTester->IsPvP() && pTarget->IsPvP();
6265 // faction base cases
6266 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6267 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6268 if(!tester_faction || !target_faction)
6269 return false;
6271 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6272 return true;
6274 // PvC forced reaction and reputation case
6275 if(tester->GetTypeId()==TYPEID_PLAYER)
6277 // forced reaction
6278 ForcedReactions::const_iterator forceItr = ((Player*)tester)->m_forcedReactions.find(target_faction->faction);
6279 if(forceItr!=((Player*)tester)->m_forcedReactions.end())
6280 return forceItr->second <= REP_HOSTILE;
6282 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6283 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6284 if(raw_target_faction->reputationListID >=0)
6285 if(FactionState const* factionState = ((Player*)tester)->GetFactionState(raw_target_faction))
6286 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6288 // CvP forced reaction and reputation case
6289 else if(target->GetTypeId()==TYPEID_PLAYER)
6291 // forced reaction
6292 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
6293 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
6294 return forceItr->second <= REP_HOSTILE;
6296 // apply reputation state
6297 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6298 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6299 return ((Player const*)target)->GetReputationRank(raw_tester_faction) <= REP_HOSTILE;
6302 // common faction based case (CvC,PvC,CvP)
6303 return tester_faction->IsHostileTo(*target_faction);
6306 bool Unit::IsFriendlyTo(Unit const* unit) const
6308 // always friendly to self
6309 if(unit==this)
6310 return true;
6312 // always friendly to GM in GM mode
6313 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6314 return true;
6316 // always non-friendly to enemy
6317 if(getVictim()==unit || unit->getVictim()==this)
6318 return false;
6320 // test pet/charm masters instead pers/charmeds
6321 Unit const* testerOwner = GetCharmerOrOwner();
6322 Unit const* targetOwner = unit->GetCharmerOrOwner();
6324 // always non-friendly to owner's enemy
6325 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6326 return false;
6328 // always non-friendly to enemy owner
6329 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6330 return false;
6332 // always non-friendly to owner of owner's enemy
6333 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6334 return false;
6336 Unit const* tester = testerOwner ? testerOwner : this;
6337 Unit const* target = targetOwner ? targetOwner : unit;
6339 // always friendly to target with common owner, or to owner/pet
6340 if(tester==target)
6341 return true;
6343 // special cases (Duel)
6344 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6346 Player const* pTester = (Player const*)tester;
6347 Player const* pTarget = (Player const*)target;
6349 // Duel
6350 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
6351 return false;
6353 // Group
6354 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6355 return true;
6357 // Sanctuary
6358 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6359 return true;
6361 // PvP FFA state
6362 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))
6363 return false;
6365 //= PvP states
6366 // Green/Blue (non-attackable)
6367 if(pTester->GetTeam()==pTarget->GetTeam())
6368 return true;
6370 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
6371 return !pTarget->IsPvP();
6374 // faction base cases
6375 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6376 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6377 if(!tester_faction || !target_faction)
6378 return false;
6380 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6381 return false;
6383 // PvC forced reaction and reputation case
6384 if(tester->GetTypeId()==TYPEID_PLAYER)
6386 // forced reaction
6387 ForcedReactions::const_iterator forceItr = ((Player const*)tester)->m_forcedReactions.find(target_faction->faction);
6388 if(forceItr!=((Player const*)tester)->m_forcedReactions.end())
6389 return forceItr->second >= REP_FRIENDLY;
6391 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
6392 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6393 if(raw_target_faction->reputationListID >=0)
6394 if(FactionState const* FactionState = ((Player*)tester)->GetFactionState(raw_target_faction))
6395 return !(FactionState->Flags & FACTION_FLAG_AT_WAR);
6397 // CvP forced reaction and reputation case
6398 else if(target->GetTypeId()==TYPEID_PLAYER)
6400 // forced reaction
6401 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
6402 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
6403 return forceItr->second >= REP_FRIENDLY;
6405 // apply reputation state
6406 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
6407 if(raw_tester_faction->reputationListID >=0 )
6408 return ((Player const*)target)->GetReputationRank(raw_tester_faction) >= REP_FRIENDLY;
6411 // common faction based case (CvC,PvC,CvP)
6412 return tester_faction->IsFriendlyTo(*target_faction);
6415 bool Unit::IsHostileToPlayers() const
6417 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
6418 if(!my_faction)
6419 return false;
6421 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
6422 if(raw_faction && raw_faction->reputationListID >=0 )
6423 return false;
6425 return my_faction->IsHostileToPlayers();
6428 bool Unit::IsNeutralToAll() const
6430 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
6431 if(!my_faction)
6432 return true;
6434 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
6435 if(raw_faction && raw_faction->reputationListID >=0 )
6436 return false;
6438 return my_faction->IsNeutralToAll();
6441 bool Unit::Attack(Unit *victim, bool meleeAttack)
6443 if(!victim || victim == this)
6444 return false;
6446 // dead units can neither attack nor be attacked
6447 if(!isAlive() || !victim->isAlive())
6448 return false;
6450 // player cannot attack in mount state
6451 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
6452 return false;
6454 // nobody can attack GM in GM-mode
6455 if(victim->GetTypeId()==TYPEID_PLAYER)
6457 if(((Player*)victim)->isGameMaster())
6458 return false;
6460 else
6462 if(((Creature*)victim)->IsInEvadeMode())
6463 return false;
6466 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
6467 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
6468 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
6470 if (m_attacking)
6472 if (m_attacking == victim)
6474 // switch to melee attack from ranged/magic
6475 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
6477 addUnitState(UNIT_STAT_MELEE_ATTACKING);
6478 SendAttackStart(victim);
6479 return true;
6481 return false;
6483 AttackStop();
6486 //Set our target
6487 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
6489 if(meleeAttack)
6490 addUnitState(UNIT_STAT_MELEE_ATTACKING);
6491 m_attacking = victim;
6492 m_attacking->_addAttacker(this);
6494 if(m_attacking->GetTypeId()==TYPEID_UNIT && ((Creature*)m_attacking)->AI())
6495 ((Creature*)m_attacking)->AI()->AttackedBy(this);
6497 if(GetTypeId()==TYPEID_UNIT)
6499 WorldPacket data(SMSG_AI_REACTION, 12);
6500 data << uint64(GetGUID());
6501 data << uint32(AI_REACTION_AGGRO); // Aggro sound
6502 ((WorldObject*)this)->SendMessageToSet(&data, true);
6504 ((Creature*)this)->CallAssistance();
6505 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
6508 // delay offhand weapon attack to next attack time
6509 if(haveOffhandWeapon())
6510 resetAttackTimer(OFF_ATTACK);
6512 if(meleeAttack)
6513 SendAttackStart(victim);
6515 return true;
6518 bool Unit::AttackStop()
6520 if (!m_attacking)
6521 return false;
6523 Unit* victim = m_attacking;
6525 m_attacking->_removeAttacker(this);
6526 m_attacking = NULL;
6528 //Clear our target
6529 SetUInt64Value(UNIT_FIELD_TARGET, 0);
6531 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
6533 InterruptSpell(CURRENT_MELEE_SPELL);
6535 if( GetTypeId()==TYPEID_UNIT )
6537 // reset call assistance
6538 ((Creature*)this)->SetNoCallAssistance(false);
6541 SendAttackStop(victim);
6543 return true;
6546 void Unit::CombatStop(bool cast)
6548 if(cast& IsNonMeleeSpellCasted(false))
6549 InterruptNonMeleeSpells(false);
6551 AttackStop();
6552 RemoveAllAttackers();
6553 if( GetTypeId()==TYPEID_PLAYER )
6554 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
6555 ClearInCombat();
6558 void Unit::CombatStopWithPets(bool cast)
6560 CombatStop(cast);
6561 if(Pet* pet = GetPet())
6562 pet->CombatStop(cast);
6563 if(Unit* charm = GetCharm())
6564 charm->CombatStop(cast);
6565 if(GetTypeId()==TYPEID_PLAYER)
6567 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
6568 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
6569 if(Unit* guardian = Unit::GetUnit(*this,*itr))
6570 guardian->CombatStop(cast);
6574 bool Unit::isAttackingPlayer() const
6576 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
6577 return true;
6579 Pet* pet = GetPet();
6580 if(pet && pet->isAttackingPlayer())
6581 return true;
6583 Unit* charmed = GetCharm();
6584 if(charmed && charmed->isAttackingPlayer())
6585 return true;
6587 for (int8 i = 0; i < MAX_TOTEM; i++)
6589 if(m_TotemSlot[i])
6591 Creature *totem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
6592 if(totem && totem->isAttackingPlayer())
6593 return true;
6597 return false;
6600 void Unit::RemoveAllAttackers()
6602 while (!m_attackers.empty())
6604 AttackerSet::iterator iter = m_attackers.begin();
6605 if(!(*iter)->AttackStop())
6607 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
6608 m_attackers.erase(iter);
6613 void Unit::ModifyAuraState(AuraState flag, bool apply)
6615 if (apply)
6617 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
6619 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
6620 if(GetTypeId() == TYPEID_PLAYER)
6622 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
6623 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
6625 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
6626 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
6627 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
6628 if (spellInfo->CasterAuraState == flag)
6629 CastSpell(this, itr->first, true, NULL);
6634 else
6636 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
6638 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
6639 Unit::AuraMap& tAuras = GetAuras();
6640 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
6642 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
6643 if (spellProto->CasterAuraState == flag)
6645 // exceptions (applied at state but not removed at state change)
6646 // Rampage
6647 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
6649 ++itr;
6650 continue;
6653 RemoveAura(itr);
6655 else
6656 ++itr;
6662 Unit *Unit::GetOwner() const
6664 uint64 ownerid = GetOwnerGUID();
6665 if(!ownerid)
6666 return NULL;
6667 return ObjectAccessor::GetUnit(*this, ownerid);
6670 Unit *Unit::GetCharmer() const
6672 if(uint64 charmerid = GetCharmerGUID())
6673 return ObjectAccessor::GetUnit(*this, charmerid);
6674 return NULL;
6677 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
6679 uint64 guid = GetCharmerOrOwnerGUID();
6680 if(IS_PLAYER_GUID(guid))
6681 return ObjectAccessor::GetPlayer(*this, guid);
6683 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
6686 Pet* Unit::GetPet() const
6688 if(uint64 pet_guid = GetPetGUID())
6690 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
6691 return pet;
6693 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
6694 const_cast<Unit*>(this)->SetPet(0);
6697 return NULL;
6700 Unit* Unit::GetCharm() const
6702 if(uint64 charm_guid = GetCharmGUID())
6704 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
6705 return pet;
6707 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
6708 const_cast<Unit*>(this)->SetCharm(0);
6711 return NULL;
6714 void Unit::SetPet(Pet* pet)
6716 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
6718 // FIXME: hack, speed must be set only at follow
6719 if(pet)
6720 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
6721 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
6724 void Unit::SetCharm(Unit* pet)
6726 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
6728 if(GetTypeId() == TYPEID_PLAYER)
6729 ((Player*)this)->m_mover = pet ? pet : this;
6732 void Unit::UnsummonAllTotems()
6734 for (int8 i = 0; i < MAX_TOTEM; ++i)
6736 if(!m_TotemSlot[i])
6737 continue;
6739 Creature *OldTotem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
6740 if (OldTotem && OldTotem->isTotem())
6741 ((Totem*)OldTotem)->UnSummon();
6745 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
6747 // we guess size
6748 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
6749 data.append(pVictim->GetPackGUID());
6750 data.append(GetPackGUID());
6751 data << uint32(SpellID);
6752 data << uint32(Damage);
6753 data << uint32(0); // over healing?
6754 data << uint8(critical ? 1 : 0);
6755 data << uint8(0); // unused in client?
6756 SendMessageToSet(&data, true);
6759 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
6761 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
6762 data.append(pVictim->GetPackGUID());
6763 data.append(GetPackGUID());
6764 data << uint32(SpellID);
6765 data << uint32(powertype);
6766 data << uint32(Damage);
6767 SendMessageToSet(&data, true);
6770 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype)
6772 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
6773 return pdamage;
6775 int32 BonusDamage = 0;
6776 if( GetTypeId()==TYPEID_UNIT )
6778 // Pets just add their bonus damage to their spell damage
6779 // note that their spell damage is just gain of their own auras
6780 if (((Creature*)this)->isPet())
6782 BonusDamage = ((Pet*)this)->GetBonusDamage();
6784 // For totems get damage bonus from owner (statue isn't totem in fact)
6785 else if (((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
6787 if(Unit* owner = GetOwner())
6788 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
6792 // Damage Done
6793 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
6795 // Taken/Done fixed damage bonus auras
6796 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto))+BonusDamage;
6797 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
6799 // Damage over Time spells bonus calculation
6800 float DotFactor = 1.0f;
6801 if(damagetype == DOT)
6803 int32 DotDuration = GetSpellDuration(spellProto);
6804 // 200% limit
6805 if(DotDuration > 0)
6807 if(DotDuration > 30000) DotDuration = 30000;
6808 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
6809 int x = 0;
6810 for(int j = 0; j < 3; j++)
6812 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
6813 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
6814 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
6816 x = j;
6817 break;
6820 int DotTicks = 6;
6821 if(spellProto->EffectAmplitude[x] != 0)
6822 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
6823 if(DotTicks)
6825 DoneAdvertisedBenefit /= DotTicks;
6826 TakenAdvertisedBenefit /= DotTicks;
6831 // Taken/Done total percent damage auras
6832 float DoneTotalMod = 1.0f;
6833 float TakenTotalMod = 1.0f;
6835 // ..done
6836 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6837 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
6839 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
6840 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
6841 // -1 == any item class (not wand then)
6842 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
6843 // 0 == any inventory type (not wand then)
6845 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
6849 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
6850 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
6851 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
6852 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
6853 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
6855 // ..taken
6856 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
6857 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
6858 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
6859 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
6861 // .. taken pct: scripted (increases damage of * against targets *)
6862 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6863 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6865 switch((*i)->GetModifier()->m_miscvalue)
6867 //Molten Fury
6868 case 4920: case 4919:
6869 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
6870 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f; break;
6874 // .. taken pct: dummy auras
6875 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
6876 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
6878 switch((*i)->GetSpellProto()->SpellIconID)
6880 //Cheat Death
6881 case 2109:
6882 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) )
6884 if(pVictim->GetTypeId() != TYPEID_PLAYER)
6885 continue;
6886 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
6887 if (mod < (*i)->GetModifier()->m_amount)
6888 mod = (*i)->GetModifier()->m_amount;
6889 TakenTotalMod *= (mod+100.0f)/100.0f;
6891 break;
6892 //Mangle
6893 case 2312:
6894 for(int j=0;j<3;j++)
6896 if(GetEffectMechanic(spellProto, j)==MECHANIC_BLEED)
6898 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
6899 break;
6902 break;
6906 // Distribute Damage over multiple effects, reduce by AoE
6907 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
6909 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
6910 for(int j = 0; j < 3; ++j)
6912 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
6913 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
6915 CastingTime /= 2;
6916 break;
6920 switch(spellProto->SpellFamilyName)
6922 case SPELLFAMILY_MAGE:
6923 // Ignite - do not modify, it is (8*Rank)% damage of procing Spell
6924 if(spellProto->Id==12654)
6926 return pdamage;
6928 // Ice Lance
6929 else if((spellProto->SpellFamilyFlags & 0x20000LL) && spellProto->SpellIconID == 186)
6931 CastingTime /= 3; // applied 1/3 bonuses in case generic target
6932 if(pVictim->isFrozen()) // and compensate this for frozen target.
6933 TakenTotalMod *= 3.0f;
6935 // Pyroblast - 115% of Fire Damage, DoT - 20% of Fire Damage
6936 else if((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 184 )
6938 DotFactor = damagetype == DOT ? 0.2f : 1.0f;
6939 CastingTime = damagetype == DOT ? 3500 : 4025;
6941 // Fireball - 100% of Fire Damage, DoT - 0% of Fire Damage
6942 else if((spellProto->SpellFamilyFlags & 0x1LL) && spellProto->SpellIconID == 185)
6944 CastingTime = 3500;
6945 DotFactor = damagetype == DOT ? 0.0f : 1.0f;
6947 // Molten armor
6948 else if (spellProto->SpellFamilyFlags & 0x0000000800000000LL)
6950 CastingTime = 0;
6952 // Arcane Missiles triggered spell
6953 else if ((spellProto->SpellFamilyFlags & 0x200000LL) && spellProto->SpellIconID == 225)
6955 CastingTime = 1000;
6957 // Blizzard triggered spell
6958 else if ((spellProto->SpellFamilyFlags & 0x80080LL) && spellProto->SpellIconID == 285)
6960 CastingTime = 500;
6962 break;
6963 case SPELLFAMILY_WARLOCK:
6964 // Life Tap
6965 if((spellProto->SpellFamilyFlags & 0x40000LL) && spellProto->SpellIconID == 208)
6967 CastingTime = 2800; // 80% from +shadow damage
6968 DoneTotalMod = 1.0f;
6969 TakenTotalMod = 1.0f;
6971 // Dark Pact
6972 else if((spellProto->SpellFamilyFlags & 0x80000000LL) && spellProto->SpellIconID == 154 && GetPetGUID())
6974 CastingTime = 3360; // 96% from +shadow damage
6975 DoneTotalMod = 1.0f;
6976 TakenTotalMod = 1.0f;
6978 // Soul Fire - 115% of Fire Damage
6979 else if((spellProto->SpellFamilyFlags & 0x8000000000LL) && spellProto->SpellIconID == 184)
6981 CastingTime = 4025;
6983 // Curse of Agony - 120% of Shadow Damage
6984 else if((spellProto->SpellFamilyFlags & 0x0000000400LL) && spellProto->SpellIconID == 544)
6986 DotFactor = 1.2f;
6988 // Drain Mana - 0% of Shadow Damage
6989 else if((spellProto->SpellFamilyFlags & 0x10LL) && spellProto->SpellIconID == 548)
6991 CastingTime = 0;
6993 // Drain Soul 214.3%
6994 else if ((spellProto->SpellFamilyFlags & 0x4000LL) && spellProto->SpellIconID == 113 )
6996 CastingTime = 7500;
6998 // Hellfire
6999 else if ((spellProto->SpellFamilyFlags & 0x40LL) && spellProto->SpellIconID == 937)
7001 CastingTime = damagetype == DOT ? 5000 : 500; // self damage seems to be so
7003 // Unstable Affliction - 180%
7004 else if (spellProto->Id == 31117 && spellProto->SpellIconID == 232)
7006 CastingTime = 6300;
7008 // Corruption 93%
7009 else if ((spellProto->SpellFamilyFlags & 0x2LL) && spellProto->SpellIconID == 313)
7011 DotFactor = 0.93f;
7013 break;
7014 case SPELLFAMILY_PALADIN:
7015 // Consecration - 95% of Holy Damage
7016 if((spellProto->SpellFamilyFlags & 0x20LL) && spellProto->SpellIconID == 51)
7018 DotFactor = 0.95f;
7019 CastingTime = 3500;
7021 // Seal of Righteousness - 10.2%/9.8% ( based on weapon type ) of Holy Damage, multiplied by weapon speed
7022 else if((spellProto->SpellFamilyFlags & 0x8000000LL) && spellProto->SpellIconID == 25)
7024 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
7025 float wspeed = GetAttackTime(BASE_ATTACK)/1000.0f;
7027 if( item && item->GetProto()->InventoryType == INVTYPE_2HWEAPON)
7028 CastingTime = uint32(wspeed*3500*0.102f);
7029 else
7030 CastingTime = uint32(wspeed*3500*0.098f);
7032 // Judgement of Righteousness - 73%
7033 else if ((spellProto->SpellFamilyFlags & 1024) && spellProto->SpellIconID == 25)
7035 CastingTime = 2555;
7037 // Seal of Vengeance - 17% per Fully Stacked Tick - 5 Applications
7038 else if ((spellProto->SpellFamilyFlags & 0x80000000000LL) && spellProto->SpellIconID == 2292)
7040 DotFactor = 0.17f;
7041 CastingTime = 3500;
7043 // Holy shield - 5% of Holy Damage
7044 else if ((spellProto->SpellFamilyFlags & 0x4000000000LL) && spellProto->SpellIconID == 453)
7046 CastingTime = 175;
7048 // Blessing of Sanctuary - 0%
7049 else if ((spellProto->SpellFamilyFlags & 0x10000000LL) && spellProto->SpellIconID == 29)
7051 CastingTime = 0;
7053 // Seal of Righteousness trigger - already computed for parent spell
7054 else if ( spellProto->SpellFamilyName==SPELLFAMILY_PALADIN && spellProto->SpellIconID==25 && spellProto->AttributesEx4 & 0x00800000LL )
7056 return pdamage;
7058 break;
7059 case SPELLFAMILY_SHAMAN:
7060 // totem attack
7061 if (spellProto->SpellFamilyFlags & 0x000040000000LL)
7063 if (spellProto->SpellIconID == 33) // Fire Nova totem attack must be 21.4%(untested)
7064 CastingTime = 749; // ignore CastingTime and use as modifier
7065 else if (spellProto->SpellIconID == 680) // Searing Totem attack 8%
7066 CastingTime = 280; // ignore CastingTime and use as modifier
7067 else if (spellProto->SpellIconID == 37) // Magma totem attack must be 6.67%(untested)
7068 CastingTime = 234; // ignore CastingTimePenalty and use as modifier
7070 // Lightning Shield (and proc shield from T2 8 pieces bonus ) 33% per charge
7071 else if( (spellProto->SpellFamilyFlags & 0x00000000400LL) || spellProto->Id == 23552)
7072 CastingTime = 1155; // ignore CastingTimePenalty and use as modifier
7073 break;
7074 case SPELLFAMILY_PRIEST:
7075 // Mana Burn - 0% of Shadow Damage
7076 if((spellProto->SpellFamilyFlags & 0x10LL) && spellProto->SpellIconID == 212)
7078 CastingTime = 0;
7080 // Mind Flay - 59% of Shadow Damage
7081 else if((spellProto->SpellFamilyFlags & 0x800000LL) && spellProto->SpellIconID == 548)
7083 CastingTime = 2065;
7085 // Holy Fire - 86.71%, DoT - 16.5%
7086 else if ((spellProto->SpellFamilyFlags & 0x100000LL) && spellProto->SpellIconID == 156)
7088 DotFactor = damagetype == DOT ? 0.165f : 1.0f;
7089 CastingTime = damagetype == DOT ? 3500 : 3035;
7091 // Shadowguard - 28% per charge
7092 else if ((spellProto->SpellFamilyFlags & 0x2000000LL) && spellProto->SpellIconID == 19)
7094 CastingTime = 980;
7096 // Touch of Weakeness - 10%
7097 else if ((spellProto->SpellFamilyFlags & 0x80000LL) && spellProto->SpellIconID == 1591)
7099 CastingTime = 350;
7101 // Reflective Shield (back damage) - 0% (other spells fit to check not have damage effects/auras)
7102 else if (spellProto->SpellFamilyFlags == 0 && spellProto->SpellIconID == 566)
7104 CastingTime = 0;
7106 // Holy Nova - 14%
7107 else if ((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 1874)
7109 CastingTime = 500;
7111 break;
7112 case SPELLFAMILY_DRUID:
7113 // Hurricane triggered spell
7114 if((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 220)
7116 CastingTime = 500;
7118 break;
7119 case SPELLFAMILY_WARRIOR:
7120 case SPELLFAMILY_HUNTER:
7121 case SPELLFAMILY_ROGUE:
7122 CastingTime = 0;
7123 break;
7124 default:
7125 break;
7128 float LvlPenalty = CalculateLevelPenalty(spellProto);
7130 // Spellmod SpellDamage
7131 float SpellModSpellDamage = 100.0f;
7133 if(Player* modOwner = GetSpellModOwner())
7134 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7136 SpellModSpellDamage /= 100.0f;
7138 float DoneActualBenefit = DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * SpellModSpellDamage * LvlPenalty;
7139 float TakenActualBenefit = TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
7141 float tmpDamage = (float(pdamage)+DoneActualBenefit)*DoneTotalMod;
7143 // Add flat bonus from spell damage versus
7144 tmpDamage += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7146 // apply spellmod to Done damage
7147 if(Player* modOwner = GetSpellModOwner())
7148 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7150 tmpDamage = (tmpDamage+TakenActualBenefit)*TakenTotalMod;
7152 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7153 tmpDamage *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7155 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7158 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7160 int32 DoneAdvertisedBenefit = 0;
7162 // ..done
7163 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7164 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7165 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7166 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7167 // -1 == any item class (not wand then)
7168 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7169 // 0 == any inventory type (not wand then)
7170 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7172 if (GetTypeId() == TYPEID_PLAYER)
7174 // Damage bonus from stats
7175 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7176 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7178 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7180 // stat used stored in miscValueB for this aura
7181 Stats usedStat = Stats((*i)->GetMiscBValue());
7182 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7185 // ... and attack power
7186 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7187 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7188 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7189 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7192 return DoneAdvertisedBenefit;
7195 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7197 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7199 int32 TakenAdvertisedBenefit = 0;
7200 // ..done (for creature type by mask) in taken
7201 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7202 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7203 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7204 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7206 // ..taken
7207 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7208 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7209 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7210 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7212 return TakenAdvertisedBenefit;
7215 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7217 // not critting spell
7218 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7219 return false;
7221 float crit_chance = 0.0f;
7222 switch(spellProto->DmgClass)
7224 case SPELL_DAMAGE_CLASS_NONE:
7225 return false;
7226 case SPELL_DAMAGE_CLASS_MAGIC:
7228 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7229 crit_chance = 0.0f;
7230 // For other schools
7231 else if (GetTypeId() == TYPEID_PLAYER)
7232 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7233 else
7235 crit_chance = m_baseSpellCritChance;
7236 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7238 // taken
7239 if (pVictim && !IsPositiveSpell(spellProto->Id))
7241 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7242 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7243 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7244 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7245 // Modify by player victim resilience
7246 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7247 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7248 // scripted (increase crit chance ... against ... target by x%
7249 if(pVictim->isFrozen()) // Shatter
7251 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7252 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7254 switch((*i)->GetModifier()->m_miscvalue)
7256 case 849: crit_chance+= 10.0f; break; //Shatter Rank 1
7257 case 910: crit_chance+= 20.0f; break; //Shatter Rank 2
7258 case 911: crit_chance+= 30.0f; break; //Shatter Rank 3
7259 case 912: crit_chance+= 40.0f; break; //Shatter Rank 4
7260 case 913: crit_chance+= 50.0f; break; //Shatter Rank 5
7265 break;
7267 case SPELL_DAMAGE_CLASS_MELEE:
7268 case SPELL_DAMAGE_CLASS_RANGED:
7270 if (pVictim)
7272 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7273 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7275 break;
7277 default:
7278 return false;
7280 // percent done
7281 // only players use intelligence for critical chance computations
7282 if(Player* modOwner = GetSpellModOwner())
7283 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7285 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7286 if (roll_chance_f(crit_chance))
7287 return true;
7288 return false;
7291 uint32 Unit::SpellCriticalBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7293 // Calculate critical bonus
7294 int32 crit_bonus;
7295 switch(spellProto->DmgClass)
7297 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7298 case SPELL_DAMAGE_CLASS_RANGED:
7299 // TODO: write here full calculation for melee/ranged spells
7300 crit_bonus = damage;
7301 break;
7302 default:
7303 crit_bonus = damage / 2; // for spells is 50%
7304 break;
7307 // adds additional damage to crit_bonus (from talents)
7308 if(Player* modOwner = GetSpellModOwner())
7309 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
7311 if(pVictim)
7313 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7314 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7317 if(crit_bonus > 0)
7318 damage += crit_bonus;
7320 return damage;
7323 uint32 Unit::SpellHealingBonus(SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, Unit *pVictim)
7325 // For totems get healing bonus from owner (statue isn't totem in fact)
7326 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7327 if(Unit* owner = GetOwner())
7328 return owner->SpellHealingBonus(spellProto, healamount, damagetype, pVictim);
7330 // Healing Done
7332 // These Spells are doing fixed amount of healing (TODO found less hack-like check)
7333 if (spellProto->Id == 15290 || spellProto->Id == 39373 ||
7334 spellProto->Id == 33778 || spellProto->Id == 379 ||
7335 spellProto->Id == 38395 || spellProto->Id == 40972)
7336 return healamount;
7338 int32 AdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
7339 uint32 CastingTime = GetSpellCastTime(spellProto);
7341 // Healing Taken
7342 AdvertisedBenefit += SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7344 // Blessing of Light dummy effects healing taken from Holy Light and Flash of Light
7345 if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && (spellProto->SpellFamilyFlags & 0x00000000C0000000LL))
7347 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7348 for(AuraList::const_iterator i = mDummyAuras.begin();i != mDummyAuras.end(); ++i)
7350 if((*i)->GetSpellProto()->SpellVisual[0] == 9180)
7352 // Flash of Light
7353 if ((spellProto->SpellFamilyFlags & 0x0000000040000000LL) && (*i)->GetEffIndex() == 1)
7354 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7355 // Holy Light
7356 else if ((spellProto->SpellFamilyFlags & 0x0000000080000000LL) && (*i)->GetEffIndex() == 0)
7357 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7362 float ActualBenefit = 0.0f;
7364 if (AdvertisedBenefit != 0)
7366 // Healing over Time spells
7367 float DotFactor = 1.0f;
7368 if(damagetype == DOT)
7370 int32 DotDuration = GetSpellDuration(spellProto);
7371 if(DotDuration > 0)
7373 // 200% limit
7374 if(DotDuration > 30000) DotDuration = 30000;
7375 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7376 int x = 0;
7377 for(int j = 0; j < 3; j++)
7379 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7380 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_HEAL ||
7381 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7383 x = j;
7384 break;
7387 int DotTicks = 6;
7388 if(spellProto->EffectAmplitude[x] != 0)
7389 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7390 if(DotTicks)
7391 AdvertisedBenefit /= DotTicks;
7395 // distribute healing to all effects, reduce AoE damage
7396 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7398 // 0% bonus for damage and healing spells for leech spells from healing bonus
7399 for(int j = 0; j < 3; ++j)
7401 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7402 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7404 CastingTime = 0;
7405 break;
7409 // Exception
7410 switch (spellProto->SpellFamilyName)
7412 case SPELLFAMILY_SHAMAN:
7413 // Healing stream from totem (add 6% per tick from hill bonus owner)
7414 if (spellProto->SpellFamilyFlags & 0x000000002000LL)
7415 CastingTime = 210;
7416 // Earth Shield 30% per charge
7417 else if (spellProto->SpellFamilyFlags & 0x40000000000LL)
7418 CastingTime = 1050;
7419 break;
7420 case SPELLFAMILY_DRUID:
7421 // Lifebloom
7422 if (spellProto->SpellFamilyFlags & 0x1000000000LL)
7424 CastingTime = damagetype == DOT ? 3500 : 1200;
7425 DotFactor = damagetype == DOT ? 0.519f : 1.0f;
7427 // Tranquility triggered spell
7428 else if (spellProto->SpellFamilyFlags & 0x80LL)
7429 CastingTime = 667;
7430 // Rejuvenation
7431 else if (spellProto->SpellFamilyFlags & 0x10LL)
7432 DotFactor = 0.845f;
7433 // Regrowth
7434 else if (spellProto->SpellFamilyFlags & 0x40LL)
7436 DotFactor = damagetype == DOT ? 0.705f : 1.0f;
7437 CastingTime = damagetype == DOT ? 3500 : 1010;
7439 break;
7440 case SPELLFAMILY_PRIEST:
7441 // Holy Nova - 14%
7442 if ((spellProto->SpellFamilyFlags & 0x8000000LL) && spellProto->SpellIconID == 1874)
7443 CastingTime = 500;
7444 break;
7445 case SPELLFAMILY_PALADIN:
7446 // Seal and Judgement of Light
7447 if ( spellProto->SpellFamilyFlags & 0x100040000LL )
7448 CastingTime = 0;
7449 break;
7450 case SPELLFAMILY_WARRIOR:
7451 case SPELLFAMILY_ROGUE:
7452 case SPELLFAMILY_HUNTER:
7453 CastingTime = 0;
7454 break;
7457 float LvlPenalty = CalculateLevelPenalty(spellProto);
7459 // Spellmod SpellDamage
7460 float SpellModSpellDamage = 100.0f;
7462 if(Player* modOwner = GetSpellModOwner())
7463 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7465 SpellModSpellDamage /= 100.0f;
7467 ActualBenefit = (float)AdvertisedBenefit * ((float)CastingTime / 3500.0f) * DotFactor * SpellModSpellDamage * LvlPenalty;
7470 // use float as more appropriate for negative values and percent applying
7471 float heal = healamount + ActualBenefit;
7473 // TODO: check for ALL/SPELLS type
7474 // Healing done percent
7475 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
7476 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
7477 heal *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
7479 // apply spellmod to Done amount
7480 if(Player* modOwner = GetSpellModOwner())
7481 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
7483 // Healing Wave cast
7484 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
7486 // Search for Healing Way on Victim (stack up to 3 time)
7487 int32 pctMod = 0;
7488 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7489 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
7490 if((*itr)->GetId() == 29203)
7491 pctMod += (*itr)->GetModifier()->m_amount;
7492 // Apply bonus
7493 if (pctMod)
7494 heal = heal * (100 + pctMod) / 100;
7497 // Healing taken percent
7498 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
7499 if(minval)
7500 heal *= (100.0f + minval) / 100.0f;
7502 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
7503 if(maxval)
7504 heal *= (100.0f + maxval) / 100.0f;
7506 if (heal < 0) heal = 0;
7508 return uint32(heal);
7511 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
7513 int32 AdvertisedBenefit = 0;
7515 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
7516 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
7517 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7518 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7520 // Healing bonus of spirit, intellect and strength
7521 if (GetTypeId() == TYPEID_PLAYER)
7523 // Healing bonus from stats
7524 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
7525 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
7527 // stat used dependent from misc value (stat index)
7528 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
7529 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7532 // ... and attack power
7533 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
7534 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
7535 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7536 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7538 return AdvertisedBenefit;
7541 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7543 int32 AdvertisedBenefit = 0;
7544 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
7545 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7546 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7547 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7548 return AdvertisedBenefit;
7551 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask, bool useCharges)
7553 //If m_immuneToSchool type contain this school type, IMMUNE damage.
7554 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
7555 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
7556 if(itr->type & shoolMask)
7557 return true;
7559 //If m_immuneToDamage type contain magic, IMMUNE damage.
7560 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
7561 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
7562 if(itr->type & shoolMask)
7563 return true;
7565 return false;
7568 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
7570 if (!spellInfo)
7571 return false;
7573 //FIX ME this hack: don't get feared if stunned
7574 if (spellInfo->Mechanic == MECHANIC_FEAR )
7576 if ( hasUnitState(UNIT_STAT_STUNNED) )
7577 return true;
7580 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
7581 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
7582 if(itr->type == spellInfo->Dispel)
7583 return true;
7585 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
7586 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
7588 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
7589 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
7590 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
7591 (itr->type & GetSpellSchoolMask(spellInfo)) )
7592 return true;
7595 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
7596 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
7598 if(itr->type == spellInfo->Mechanic)
7600 return true;
7604 return false;
7607 bool Unit::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
7609 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
7610 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
7611 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
7612 if(itr->type == effect)
7613 return true;
7615 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
7616 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
7617 if(itr->type == mechanic)
7618 return true;
7620 return false;
7623 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
7625 if(!spellInfo)
7626 return false;
7628 uint32 family = spellInfo->SpellFamilyName;
7629 uint64 flags = spellInfo->SpellFamilyFlags;
7631 if((family == 5 && flags == 256) || //Searing Pain
7632 (family == 6 && flags == 8192) || //Mind Blast
7633 (family == 11 && flags == 1048576)) //Earth Shock
7634 return true;
7636 return false;
7639 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
7641 if(!pVictim)
7642 return;
7644 if(*pdamage == 0)
7645 return;
7647 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7649 // Taken/Done fixed damage bonus auras
7650 int32 DoneFlatBenefit = 0;
7651 int32 TakenFlatBenefit = 0;
7653 // ..done (for creature type by mask) in taken
7654 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7655 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7656 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7657 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
7659 // ..done
7660 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
7662 // ..done (base at attack power for marked target and base at attack power for creature type)
7663 int32 APbonus = 0;
7664 if(attType == RANGED_ATTACK)
7666 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
7668 // ..done (base at attack power and creature type)
7669 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
7670 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
7671 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7672 APbonus += (*i)->GetModifier()->m_amount;
7674 else
7676 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
7678 // ..done (base at attack power and creature type)
7679 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
7680 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
7681 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7682 APbonus += (*i)->GetModifier()->m_amount;
7685 if (APbonus!=0) // Can be negative
7687 bool normalized = false;
7688 if(spellProto)
7690 for (uint8 i = 0; i<3;i++)
7692 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
7694 normalized = true;
7695 break;
7700 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
7703 // ..taken
7704 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7705 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7706 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
7707 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
7709 if(attType!=RANGED_ATTACK)
7710 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
7711 else
7712 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
7714 // Done/Taken total percent damage auras
7715 float DoneTotalMod = 1;
7716 float TakenTotalMod = 1;
7718 // ..done
7719 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
7720 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
7722 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7723 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7724 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7725 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7727 // ..taken
7728 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7729 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7730 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
7731 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7733 // .. taken pct: dummy auras
7734 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7735 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
7737 switch((*i)->GetSpellProto()->SpellIconID)
7739 //Cheat Death
7740 case 2109:
7741 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
7743 if(pVictim->GetTypeId() != TYPEID_PLAYER)
7744 continue;
7745 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
7746 if (mod < (*i)->GetModifier()->m_amount)
7747 mod = (*i)->GetModifier()->m_amount;
7748 TakenTotalMod *= (mod+100.0f)/100.0f;
7750 break;
7751 //Mangle
7752 case 2312:
7753 if(spellProto==NULL)
7754 break;
7755 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
7756 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
7757 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7758 break;
7762 // .. taken pct: class scripts
7763 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7764 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
7766 switch((*i)->GetMiscValue())
7768 case 6427: case 6428: // Dirty Deeds
7769 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7771 Aura* eff0 = GetAura((*i)->GetId(),0);
7772 if(!eff0 || (*i)->GetEffIndex()!=1)
7774 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
7775 continue;
7778 // effect 0 have expected value but in negative state
7779 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
7781 break;
7785 if(attType != RANGED_ATTACK)
7787 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
7788 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
7789 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7791 else
7793 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
7794 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
7795 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7798 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
7800 // apply spellmod to Done damage
7801 if(spellProto)
7803 if(Player* modOwner = GetSpellModOwner())
7804 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
7807 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
7809 // bonus result can be negative
7810 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
7813 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
7815 if (apply)
7817 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
7819 next = itr; ++next;
7820 if(itr->type == type)
7822 m_spellImmune[op].erase(itr);
7823 next = m_spellImmune[op].begin();
7826 SpellImmune Immune;
7827 Immune.spellId = spellId;
7828 Immune.type = type;
7829 m_spellImmune[op].push_back(Immune);
7831 else
7833 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
7835 if(itr->spellId == spellId)
7837 m_spellImmune[op].erase(itr);
7838 break;
7845 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
7847 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
7849 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
7850 RemoveAurasWithDispelType(type);
7853 float Unit::GetWeaponProcChance() const
7855 // normalized proc chance for weapon attack speed
7856 // (odd formula...)
7857 if(isAttackReady(BASE_ATTACK))
7858 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
7859 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
7860 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
7861 return 0;
7864 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
7866 // proc per minute chance calculation
7867 if (PPM <= 0) return 0.0f;
7868 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
7869 return result;
7872 void Unit::Mount(uint32 mount)
7874 if(!mount)
7875 return;
7877 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
7879 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
7881 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
7883 // unsummon pet
7884 if(GetTypeId() == TYPEID_PLAYER)
7886 Pet* pet = GetPet();
7887 if(pet)
7889 if(pet->isControlled())
7891 ((Player*)this)->SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
7892 ((Player*)this)->SetOldPetSpell(pet->GetUInt32Value(UNIT_CREATED_BY_SPELL));
7895 ((Player*)this)->RemovePet(NULL,PET_SAVE_NOT_IN_SLOT);
7897 else
7898 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
7902 void Unit::Unmount()
7904 if(!IsMounted())
7905 return;
7907 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
7909 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
7910 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
7912 // only resummon old pet if the player is already added to a map
7913 // this prevents adding a pet to a not created map which would otherwise cause a crash
7914 // (it could probably happen when logging in after a previous crash)
7915 if(GetTypeId() == TYPEID_PLAYER && IsInWorld() && ((Player*)this)->GetTemporaryUnsummonedPetNumber() && isAlive())
7917 Pet* NewPet = new Pet;
7918 if(!NewPet->LoadPetFromDB((Player*)this, 0, ((Player*)this)->GetTemporaryUnsummonedPetNumber(), true))
7919 delete NewPet;
7921 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
7925 void Unit::SetInCombatWith(Unit* enemy)
7927 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
7928 if(eOwner->IsPvP())
7930 SetInCombatState(true);
7931 return;
7934 //check for duel
7935 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
7937 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
7938 if(((Player const*)eOwner)->duel->opponent == myOwner)
7940 SetInCombatState(true);
7941 return;
7944 SetInCombatState(false);
7947 void Unit::SetInCombatState(bool PvP)
7949 // only alive units can be in combat
7950 if(!isAlive())
7951 return;
7953 if(PvP)
7954 m_CombatTimer = 5000;
7955 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
7957 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
7958 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
7961 void Unit::ClearInCombat()
7963 m_CombatTimer = 0;
7964 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
7966 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
7967 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
7969 // Player's state will be cleared in Player::UpdateContestedPvP
7970 if(GetTypeId()!=TYPEID_PLAYER)
7971 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
7974 bool Unit::isTargetableForAttack() const
7976 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
7977 return false;
7979 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
7980 return false;
7982 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
7985 int32 Unit::ModifyHealth(int32 dVal)
7987 int32 gain = 0;
7989 if(dVal==0)
7990 return 0;
7992 int32 curHealth = (int32)GetHealth();
7994 int32 val = dVal + curHealth;
7995 if(val <= 0)
7997 SetHealth(0);
7998 return -curHealth;
8001 int32 maxHealth = (int32)GetMaxHealth();
8003 if(val < maxHealth)
8005 SetHealth(val);
8006 gain = val - curHealth;
8008 else if(curHealth != maxHealth)
8010 SetHealth(maxHealth);
8011 gain = maxHealth - curHealth;
8014 return gain;
8017 int32 Unit::ModifyPower(Powers power, int32 dVal)
8019 int32 gain = 0;
8021 if(dVal==0)
8022 return 0;
8024 int32 curPower = (int32)GetPower(power);
8026 int32 val = dVal + curPower;
8027 if(val <= 0)
8029 SetPower(power,0);
8030 return -curPower;
8033 int32 maxPower = (int32)GetMaxPower(power);
8035 if(val < maxPower)
8037 SetPower(power,val);
8038 gain = val - curPower;
8040 else if(curPower != maxPower)
8042 SetPower(power,maxPower);
8043 gain = maxPower - curPower;
8046 return gain;
8049 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8051 if(!u)
8052 return false;
8054 // Always can see self
8055 if (u==this)
8056 return true;
8058 // player visible for other player if not logout and at same transport
8059 // including case when player is out of world
8060 bool at_same_transport =
8061 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8062 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8063 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8064 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8066 // not in world
8067 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8068 return false;
8070 // forbidden to seen (at GM respawn command)
8071 if(m_Visibility==VISIBILITY_RESPAWN)
8072 return false;
8074 // always seen by owner
8075 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8076 return true;
8078 // Grid dead/alive checks
8079 if( u->GetTypeId()==TYPEID_PLAYER)
8081 // non visible at grid for any stealth state
8082 if(!IsVisibleInGridForPlayer((Player *)u))
8083 return false;
8085 // if player is dead then he can't detect anyone in any cases
8086 if(!u->isAlive())
8087 detect = false;
8089 else
8091 // all dead creatures/players not visible for any creatures
8092 if(!u->isAlive() || !isAlive())
8093 return false;
8096 // different visible distance checks
8097 if(u->isInFlight()) // what see player in flight
8099 // use object grey distance for all (only see objects any way)
8100 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8101 return false;
8103 else if(!isAlive()) // distance for show body
8105 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8106 return false;
8108 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8110 if(u->GetTypeId()==TYPEID_PLAYER)
8112 // Players far than max visible distance for player or not in our map are not visible too
8113 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8114 return false;
8116 else
8118 // Units far than max visible distance for creature or not in our map are not visible too
8119 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8120 return false;
8123 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8125 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8126 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8127 return false;
8129 else // distance for show creature
8131 // Units far than max visible distance for creature or not in our map are not visible too
8132 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8133 return false;
8136 // Visible units, always are visible for all units, except for units under invisibility
8137 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0)
8138 return true;
8140 // GMs see any players, not higher GMs and all units
8141 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8143 if(GetTypeId() == TYPEID_PLAYER)
8144 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8145 else
8146 return true;
8149 // non faction visibility non-breakable for non-GMs
8150 if (m_Visibility == VISIBILITY_OFF)
8151 return false;
8153 // raw invisibility
8154 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8156 // detectable invisibility case
8157 if( invisible && (
8158 // Invisible units, always are visible for units under same invisibility type
8159 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8160 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8161 u->canDetectInvisibilityOf(this) ||
8162 // Units that can detect invisibility always are visible for units that can be detected
8163 canDetectInvisibilityOf(u) ))
8165 invisible = false;
8168 // special cases for always overwrite invisibility/stealth
8169 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8171 // non-hostile case
8172 if (!u->IsHostileTo(this))
8174 // 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)
8175 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8177 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8178 return true;
8180 // else apply same rules as for hostile case (detecting check for stealth)
8183 // hostile case
8184 else
8186 // Hunter mark functionality
8187 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8188 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8189 if((*iter)->GetCasterGUID()==u->GetGUID())
8190 return true;
8192 // else apply detecting check for stealth
8195 // none other cases for detect invisibility, so invisible
8196 if(invisible)
8197 return false;
8199 // else apply stealth detecting check
8202 // unit got in stealth in this moment and must ignore old detected state
8203 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8204 return false;
8206 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8207 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8208 return true;
8210 // NOW ONLY STEALTH CASE
8212 // stealth and detected and visible for some seconds
8213 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8214 return true;
8216 //if in non-detect mode then invisible for unit
8217 if (!detect)
8218 return false;
8220 // Special cases
8222 // If is attacked then stealth is lost, some creature can use stealth too
8223 if( !getAttackers().empty() )
8224 return true;
8226 // If there is collision rogue is seen regardless of level difference
8227 // TODO: check sizes in DB
8228 float distance = GetDistance(u);
8229 if (distance < 0.24f)
8230 return true;
8232 //If a mob or player is stunned he will not be able to detect stealth
8233 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8234 return false;
8236 // Creature can detect target only in aggro radius
8237 if(u->GetTypeId() != TYPEID_PLAYER)
8239 //Always invisible from back and out of aggro range
8240 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
8241 if(!isInFront)
8242 return false;
8244 else
8246 //Always invisible from back
8247 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
8248 if(!isInFront)
8249 return false;
8252 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
8253 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
8255 //Calculation if target is in front
8257 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
8258 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
8260 //Visible distance is modified by
8261 //-Level Diff (every level diff = 1.0f in visible distance)
8262 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
8264 //This allows to check talent tree and will add addition stealth dependent on used points)
8265 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
8266 if(stealthMod < 0)
8267 stealthMod = 0;
8269 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
8270 //based on wowwiki every 5 mod we have 1 more level diff in calculation
8271 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
8273 if(distance > visibleDistance)
8274 return false;
8277 // Now check is target visible with LoS
8278 float ox,oy,oz;
8279 u->GetPosition(ox,oy,oz);
8280 return IsWithinLOS(ox,oy,oz);
8283 void Unit::SetVisibility(UnitVisibility x)
8285 m_Visibility = x;
8287 if(IsInWorld())
8289 Map *m = GetMap();
8291 if(GetTypeId()==TYPEID_PLAYER)
8292 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8293 else
8294 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8298 bool Unit::canDetectInvisibilityOf(Unit const* u) const
8300 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
8302 for(uint32 i = 0; i < 10; ++i)
8304 if(((1 << i) & mask)==0)
8305 continue;
8307 // find invisibility level
8308 uint32 invLevel = 0;
8309 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
8310 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
8311 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
8312 invLevel = (*itr)->GetModifier()->m_amount;
8314 // find invisibility detect level
8315 uint32 detectLevel = 0;
8316 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
8317 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
8318 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
8319 detectLevel = (*itr)->GetModifier()->m_amount;
8321 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
8323 detectLevel = ((Player*)this)->GetDrunkValue();
8326 if(invLevel <= detectLevel)
8327 return true;
8331 return false;
8334 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
8336 int32 main_speed_mod = 0;
8337 float stack_bonus = 1.0f;
8338 float non_stack_bonus = 1.0f;
8340 switch(mtype)
8342 case MOVE_WALK:
8343 return;
8344 case MOVE_RUN:
8346 if (IsMounted()) // Use on mount auras
8348 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
8349 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
8350 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
8352 else
8354 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
8355 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
8356 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
8358 break;
8360 case MOVE_RUN_BACK:
8361 return;
8362 case MOVE_SWIM:
8364 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
8365 break;
8367 case MOVE_SWIM_BACK:
8368 return;
8369 case MOVE_FLIGHT:
8371 if (IsMounted()) // Use on mount auras
8372 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
8373 else // Use not mount (shapeshift for example) auras (should stack)
8374 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
8375 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
8376 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
8377 break;
8379 case MOVE_FLIGHT_BACK:
8380 return;
8381 default:
8382 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
8383 return;
8386 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
8387 // now we ready for speed calculation
8388 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
8390 switch(mtype)
8392 case MOVE_RUN:
8393 case MOVE_SWIM:
8394 case MOVE_FLIGHT:
8396 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
8397 // TODO: possible affect only on MOVE_RUN
8398 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
8400 // Use speed from aura
8401 float max_speed = normalization / baseMoveSpeed[mtype];
8402 if (speed > max_speed)
8403 speed = max_speed;
8405 break;
8407 default:
8408 break;
8411 // Apply strongest slow aura mod to speed
8412 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
8413 if (slow)
8414 speed *=(100.0f + slow)/100.0f;
8415 SetSpeed(mtype, speed, forced);
8418 float Unit::GetSpeed( UnitMoveType mtype ) const
8420 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
8423 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
8425 if (rate < 0)
8426 rate = 0.0f;
8428 // Update speed only on change
8429 if (m_speed_rate[mtype] == rate)
8430 return;
8432 m_speed_rate[mtype] = rate;
8434 propagateSpeedChange();
8436 WorldPacket data;
8437 if(!forced)
8439 switch(mtype)
8441 case MOVE_WALK:
8442 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8443 break;
8444 case MOVE_RUN:
8445 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
8446 break;
8447 case MOVE_RUN_BACK:
8448 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8449 break;
8450 case MOVE_SWIM:
8451 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
8452 break;
8453 case MOVE_SWIM_BACK:
8454 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8455 break;
8456 case MOVE_TURN_RATE:
8457 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
8458 break;
8459 case MOVE_FLIGHT:
8460 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
8461 break;
8462 case MOVE_FLIGHT_BACK:
8463 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8464 break;
8465 case MOVE_PITCH_RATE:
8466 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
8467 break;
8468 default:
8469 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
8470 return;
8473 data.append(GetPackGUID());
8474 data << uint32(0); // movement flags
8475 data << uint16(0); // unk flags
8476 data << uint32(getMSTime());
8477 data << float(GetPositionX());
8478 data << float(GetPositionY());
8479 data << float(GetPositionZ());
8480 data << float(GetOrientation());
8481 data << uint32(0); // fall time
8482 data << float(GetSpeed(mtype));
8483 SendMessageToSet( &data, true );
8485 else
8487 if(GetTypeId() == TYPEID_PLAYER)
8489 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
8490 // and do it only for real sent packets and use run for run/mounted as client expected
8491 ++((Player*)this)->m_forced_speed_changes[mtype];
8494 switch(mtype)
8496 case MOVE_WALK:
8497 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
8498 break;
8499 case MOVE_RUN:
8500 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
8501 break;
8502 case MOVE_RUN_BACK:
8503 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
8504 break;
8505 case MOVE_SWIM:
8506 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
8507 break;
8508 case MOVE_SWIM_BACK:
8509 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
8510 break;
8511 case MOVE_TURN_RATE:
8512 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
8513 break;
8514 case MOVE_FLIGHT:
8515 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
8516 break;
8517 case MOVE_FLIGHT_BACK:
8518 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
8519 break;
8520 case MOVE_PITCH_RATE:
8521 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
8522 break;
8523 default:
8524 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
8525 return;
8527 data.append(GetPackGUID());
8528 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
8529 if (mtype == MOVE_RUN)
8530 data << uint8(0); // new 2.1.0
8531 data << float(GetSpeed(mtype));
8532 SendMessageToSet( &data, true );
8534 if(Pet* pet = GetPet())
8535 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
8538 void Unit::SetHover(bool on)
8540 if(on)
8541 CastSpell(this,11010,true);
8542 else
8543 RemoveAurasDueToSpell(11010);
8546 void Unit::setDeathState(DeathState s)
8548 if (s != ALIVE && s!= JUST_ALIVED)
8550 CombatStop();
8551 DeleteThreatList();
8552 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
8554 if(IsNonMeleeSpellCasted(false))
8555 InterruptNonMeleeSpells(false);
8558 if (s == JUST_DIED)
8560 RemoveAllAurasOnDeath();
8561 UnsummonAllTotems();
8563 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
8564 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
8565 // remove aurastates allowing special moves
8566 ClearAllReactives();
8567 ClearDiminishings();
8569 else if(s == JUST_ALIVED)
8571 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
8574 if (m_deathState != ALIVE && s == ALIVE)
8576 //_ApplyAllAuraMods();
8578 m_deathState = s;
8581 /*########################################
8582 ######## ########
8583 ######## AGGRO SYSTEM ########
8584 ######## ########
8585 ########################################*/
8586 bool Unit::CanHaveThreatList() const
8588 // only creatures can have threat list
8589 if( GetTypeId() != TYPEID_UNIT )
8590 return false;
8592 // only alive units can have threat list
8593 if( !isAlive() )
8594 return false;
8596 // totems can not have threat list
8597 if( ((Creature*)this)->isTotem() )
8598 return false;
8600 // vehicles can not have threat list
8601 if( ((Creature*)this)->isVehicle() )
8602 return false;
8604 // pets can not have a threat list, unless they are controlled by a creature
8605 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
8606 return false;
8608 return true;
8611 //======================================================================
8613 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
8615 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
8616 return threat;
8618 SpellSchools school = GetFirstSchoolInMask(schoolMask);
8620 return threat * m_threatModifier[school];
8623 //======================================================================
8625 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
8627 // Only mobs can manage threat lists
8628 if(CanHaveThreatList())
8629 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
8632 //======================================================================
8634 void Unit::DeleteThreatList()
8636 m_ThreatManager.clearReferences();
8639 //======================================================================
8641 void Unit::TauntApply(Unit* taunter)
8643 assert(GetTypeId()== TYPEID_UNIT);
8645 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
8646 return;
8648 if(!CanHaveThreatList())
8649 return;
8651 Unit *target = getVictim();
8652 if(target && target == taunter)
8653 return;
8655 SetInFront(taunter);
8656 if (((Creature*)this)->AI())
8657 ((Creature*)this)->AI()->AttackStart(taunter);
8659 m_ThreatManager.tauntApply(taunter);
8662 //======================================================================
8664 void Unit::TauntFadeOut(Unit *taunter)
8666 assert(GetTypeId()== TYPEID_UNIT);
8668 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
8669 return;
8671 if(!CanHaveThreatList())
8672 return;
8674 Unit *target = getVictim();
8675 if(!target || target != taunter)
8676 return;
8678 if(m_ThreatManager.isThreatListEmpty())
8680 if(((Creature*)this)->AI())
8681 ((Creature*)this)->AI()->EnterEvadeMode();
8682 return;
8685 m_ThreatManager.tauntFadeOut(taunter);
8686 target = m_ThreatManager.getHostilTarget();
8688 if (target && target != taunter)
8690 SetInFront(target);
8691 if (((Creature*)this)->AI())
8692 ((Creature*)this)->AI()->AttackStart(target);
8696 //======================================================================
8698 bool Unit::SelectHostilTarget()
8700 //function provides main threat functionality
8701 //next-victim-selection algorithm and evade mode are called
8702 //threat list sorting etc.
8704 assert(GetTypeId()== TYPEID_UNIT);
8705 Unit* target = NULL;
8707 //This function only useful once AI has been initialized
8708 if (!((Creature*)this)->AI())
8709 return false;
8711 if(!m_ThreatManager.isThreatListEmpty())
8713 if(!HasAuraType(SPELL_AURA_MOD_TAUNT))
8715 target = m_ThreatManager.getHostilTarget();
8719 if(target)
8721 if(!hasUnitState(UNIT_STAT_STUNNED))
8722 SetInFront(target);
8723 ((Creature*)this)->AI()->AttackStart(target);
8724 return true;
8727 // no target but something prevent go to evade mode
8728 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
8729 return false;
8731 // last case when creature don't must go to evade mode:
8732 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
8733 // for example at owner command to pet attack some far away creature
8734 // Note: creature not have targeted movement generator but have attacker in this case
8735 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
8737 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
8739 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
8740 return false;
8744 // enter in evade mode in other case
8745 ((Creature*)this)->AI()->EnterEvadeMode();
8747 return false;
8750 //======================================================================
8751 //======================================================================
8752 //======================================================================
8754 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
8756 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
8758 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
8760 int32 level = int32(getLevel());
8761 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
8762 level = (int32)spellProto->maxLevel;
8763 else if (level < (int32)spellProto->baseLevel)
8764 level = (int32)spellProto->baseLevel;
8765 level-= (int32)spellProto->spellLevel;
8767 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
8768 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
8769 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
8770 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
8771 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
8773 // range can have possitive and negative values, so order its for irand
8774 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
8775 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
8776 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
8778 int32 value = basePoints + randvalue;
8779 //random damage
8780 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
8781 value += (int32)(comboDamage * comboPoints);
8783 if(Player* modOwner = GetSpellModOwner())
8785 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
8786 switch(effect_index)
8788 case 0:
8789 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
8790 break;
8791 case 1:
8792 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
8793 break;
8794 case 2:
8795 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
8796 break;
8800 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
8801 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
8802 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
8803 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
8805 return value;
8808 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
8810 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
8812 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
8814 int32 minduration = GetSpellDuration(spellProto);
8815 int32 maxduration = GetSpellMaxDuration(spellProto);
8817 int32 duration;
8819 if( minduration != -1 && minduration != maxduration )
8820 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
8821 else
8822 duration = minduration;
8824 if (duration > 0)
8826 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
8827 // Find total mod value (negative bonus)
8828 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
8829 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
8830 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
8831 // Find max mod (negative bonus)
8832 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
8834 int32 durationMod = 0;
8835 // Select strongest negative mod
8836 if (durationMod_always > durationMod_not_stack)
8837 durationMod = durationMod_not_stack;
8838 else
8839 durationMod = durationMod_always;
8841 if (durationMod != 0)
8842 duration = int32(int64(duration) * (100+durationMod) /100);
8844 if (duration < 0) duration = 0;
8847 return duration;
8850 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
8852 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
8854 if(i->DRGroup != group)
8855 continue;
8857 if(!i->hitCount)
8858 return DIMINISHING_LEVEL_1;
8860 if(!i->hitTime)
8861 return DIMINISHING_LEVEL_1;
8863 // If last spell was casted more than 15 seconds ago - reset the count.
8864 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
8866 i->hitCount = DIMINISHING_LEVEL_1;
8867 return DIMINISHING_LEVEL_1;
8869 // or else increase the count.
8870 else
8872 return DiminishingLevels(i->hitCount);
8875 return DIMINISHING_LEVEL_1;
8878 void Unit::IncrDiminishing(DiminishingGroup group)
8880 // Checking for existing in the table
8881 bool IsExist = false;
8882 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
8884 if(i->DRGroup != group)
8885 continue;
8887 IsExist = true;
8888 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
8889 i->hitCount += 1;
8891 break;
8894 if(!IsExist)
8895 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
8898 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
8900 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
8901 return;
8903 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
8904 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
8906 // test pet/charm masters instead pets/charmeds
8907 Unit const* targetOwner = GetCharmerOrOwner();
8908 Unit const* casterOwner = caster->GetCharmerOrOwner();
8910 Unit const* target = targetOwner ? targetOwner : this;
8911 Unit const* source = casterOwner ? casterOwner : caster;
8913 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
8914 duration = 10000;
8917 float mod = 1.0f;
8919 // Some diminishings applies to mobs too (for example, Stun)
8920 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
8922 DiminishingLevels diminish = Level;
8923 switch(diminish)
8925 case DIMINISHING_LEVEL_1: break;
8926 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
8927 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
8928 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
8929 default: break;
8933 duration = int32(duration * mod);
8936 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
8938 // Checking for existing in the table
8939 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
8941 if(i->DRGroup != group)
8942 continue;
8944 i->hitTime = getMSTime();
8946 if(apply)
8947 i->stack += 1;
8948 else if(i->stack)
8949 i->stack -= 1;
8951 break;
8955 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
8957 return ObjectAccessor::GetUnit(object,guid);
8960 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
8962 return isVisibleForOrDetect(u, false, inVisibleList, false);
8965 uint32 Unit::GetCreatureType() const
8967 if(GetTypeId() == TYPEID_PLAYER)
8969 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(((Player*)this)->m_form);
8970 if(ssEntry && ssEntry->creatureType > 0)
8971 return ssEntry->creatureType;
8972 else
8973 return CREATURE_TYPE_HUMANOID;
8975 else
8976 return ((Creature*)this)->GetCreatureInfo()->type;
8979 /*#######################################
8980 ######## ########
8981 ######## STAT SYSTEM ########
8982 ######## ########
8983 #######################################*/
8985 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
8987 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
8989 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
8990 return false;
8993 float val = 1.0f;
8995 switch(modifierType)
8997 case BASE_VALUE:
8998 case TOTAL_VALUE:
8999 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9000 break;
9001 case BASE_PCT:
9002 case TOTAL_PCT:
9003 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9004 amount = -200.0f;
9006 val = (100.0f + amount) / 100.0f;
9007 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9008 break;
9010 default:
9011 break;
9014 if(!CanModifyStats())
9015 return false;
9017 switch(unitMod)
9019 case UNIT_MOD_STAT_STRENGTH:
9020 case UNIT_MOD_STAT_AGILITY:
9021 case UNIT_MOD_STAT_STAMINA:
9022 case UNIT_MOD_STAT_INTELLECT:
9023 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9025 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9026 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9028 case UNIT_MOD_MANA:
9029 case UNIT_MOD_RAGE:
9030 case UNIT_MOD_FOCUS:
9031 case UNIT_MOD_ENERGY:
9032 case UNIT_MOD_HAPPINESS:
9033 case UNIT_MOD_RUNE:
9034 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9036 case UNIT_MOD_RESISTANCE_HOLY:
9037 case UNIT_MOD_RESISTANCE_FIRE:
9038 case UNIT_MOD_RESISTANCE_NATURE:
9039 case UNIT_MOD_RESISTANCE_FROST:
9040 case UNIT_MOD_RESISTANCE_SHADOW:
9041 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9043 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9044 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9046 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9047 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9048 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9050 default:
9051 break;
9054 return true;
9057 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9059 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9061 sLog.outError("ERROR: trial to access non existed modifier value from UnitMods!");
9062 return 0.0f;
9065 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9066 return 0.0f;
9068 return m_auraModifiersGroup[unitMod][modifierType];
9071 float Unit::GetTotalStatValue(Stats stat) const
9073 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9075 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9076 return 0.0f;
9078 // value = ((base_value * base_pct) + total_value) * total_pct
9079 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9080 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9081 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9082 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9084 return value;
9087 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9089 if(unitMod >= UNIT_MOD_END)
9091 sLog.outError("ERROR: trial to access non existed UnitMods in GetTotalAuraModValue()!");
9092 return 0.0f;
9095 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9096 return 0.0f;
9098 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9099 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9100 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9101 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9103 return value;
9106 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9108 SpellSchools school = SPELL_SCHOOL_NORMAL;
9110 switch(unitMod)
9112 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9113 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9114 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9115 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9116 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9117 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9119 default:
9120 break;
9123 return school;
9126 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9128 Stats stat = STAT_STRENGTH;
9130 switch(unitMod)
9132 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9133 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9134 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9135 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9136 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9138 default:
9139 break;
9142 return stat;
9145 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9147 switch(unitMod)
9149 case UNIT_MOD_MANA: return POWER_MANA;
9150 case UNIT_MOD_RAGE: return POWER_RAGE;
9151 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9152 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9153 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9154 case UNIT_MOD_RUNE: return POWER_RUNE;
9155 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9158 return POWER_MANA;
9161 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9163 UnitMods unitMod = (attType == RANGED_ATTACK) ? UNIT_MOD_ATTACK_POWER_RANGED : UNIT_MOD_ATTACK_POWER;
9165 float val = GetTotalAuraModValue(unitMod);
9166 if(val < 0.0f)
9167 val = 0.0f;
9169 return val;
9172 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9174 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9175 return 0.0f;
9177 return m_weaponDamage[attType][type];
9180 void Unit::SetLevel(uint32 lvl)
9182 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9184 // group update
9185 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9186 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9189 void Unit::SetHealth(uint32 val)
9191 uint32 maxHealth = GetMaxHealth();
9192 if(maxHealth < val)
9193 val = maxHealth;
9195 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9197 // group update
9198 if(GetTypeId() == TYPEID_PLAYER)
9200 if(((Player*)this)->GetGroup())
9201 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9203 else if(((Creature*)this)->isPet())
9205 Pet *pet = ((Pet*)this);
9206 if(pet->isControlled())
9208 Unit *owner = GetOwner();
9209 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9210 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
9215 void Unit::SetMaxHealth(uint32 val)
9217 uint32 health = GetHealth();
9218 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
9220 // group update
9221 if(GetTypeId() == TYPEID_PLAYER)
9223 if(((Player*)this)->GetGroup())
9224 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
9226 else if(((Creature*)this)->isPet())
9228 Pet *pet = ((Pet*)this);
9229 if(pet->isControlled())
9231 Unit *owner = GetOwner();
9232 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9233 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
9237 if(val < health)
9238 SetHealth(val);
9241 void Unit::SetPower(Powers power, uint32 val)
9243 if(GetPower(power) == val)
9244 return;
9246 uint32 maxPower = GetMaxPower(power);
9247 if(maxPower < val)
9248 val = maxPower;
9250 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
9252 WorldPacket data(SMSG_POWER_UPDATE);
9253 data.append(GetPackGUID());
9254 data << uint8(power);
9255 data << uint32(val);
9256 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
9258 // group update
9259 if(GetTypeId() == TYPEID_PLAYER)
9261 if(((Player*)this)->GetGroup())
9262 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9264 else if(((Creature*)this)->isPet())
9266 Pet *pet = ((Pet*)this);
9267 if(pet->isControlled())
9269 Unit *owner = GetOwner();
9270 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9271 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9274 // Update the pet's character sheet with happiness damage bonus
9275 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
9277 pet->UpdateDamagePhysical(BASE_ATTACK);
9282 void Unit::SetMaxPower(Powers power, uint32 val)
9284 uint32 cur_power = GetPower(power);
9285 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
9287 // group update
9288 if(GetTypeId() == TYPEID_PLAYER)
9290 if(((Player*)this)->GetGroup())
9291 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9293 else if(((Creature*)this)->isPet())
9295 Pet *pet = ((Pet*)this);
9296 if(pet->isControlled())
9298 Unit *owner = GetOwner();
9299 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9300 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
9304 if(val < cur_power)
9305 SetPower(power, val);
9308 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
9310 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
9312 // group update
9313 if(GetTypeId() == TYPEID_PLAYER)
9315 if(((Player*)this)->GetGroup())
9316 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9318 else if(((Creature*)this)->isPet())
9320 Pet *pet = ((Pet*)this);
9321 if(pet->isControlled())
9323 Unit *owner = GetOwner();
9324 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9325 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9330 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
9332 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
9334 // group update
9335 if(GetTypeId() == TYPEID_PLAYER)
9337 if(((Player*)this)->GetGroup())
9338 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9340 else if(((Creature*)this)->isPet())
9342 Pet *pet = ((Pet*)this);
9343 if(pet->isControlled())
9345 Unit *owner = GetOwner();
9346 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9347 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
9352 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
9354 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
9355 if(apply)
9356 tAuraProcTriggerDamage.push_back(aura);
9357 else
9358 tAuraProcTriggerDamage.remove(aura);
9361 uint32 Unit::GetCreatePowers( Powers power ) const
9363 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
9364 switch(power)
9366 case POWER_MANA: return GetCreateMana();
9367 case POWER_RAGE: return 1000;
9368 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
9369 case POWER_ENERGY: return 100;
9370 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
9371 case POWER_RUNIC_POWER: return 1000;
9374 return 0;
9377 void Unit::AddToWorld()
9379 Object::AddToWorld();
9382 void Unit::RemoveFromWorld()
9384 // cleanup
9385 if(IsInWorld())
9387 RemoveNotOwnSingleTargetAuras();
9390 Object::RemoveFromWorld();
9393 void Unit::CleanupsBeforeDelete()
9395 if(m_uint32Values) // only for fully created object
9397 InterruptNonMeleeSpells(true);
9398 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
9399 CombatStop();
9400 ClearComboPointHolders();
9401 DeleteThreatList();
9402 getHostilRefManager().setOnlineOfflineState(false);
9403 RemoveAllAuras();
9404 RemoveAllGameObjects();
9405 RemoveAllDynObjects();
9406 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
9408 RemoveFromWorld();
9411 CharmInfo* Unit::InitCharmInfo(Unit *charm)
9413 if(!m_charmInfo)
9414 m_charmInfo = new CharmInfo(charm);
9415 return m_charmInfo;
9418 CharmInfo::CharmInfo(Unit* unit)
9419 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
9421 for(int i =0; i<4; ++i)
9423 m_charmspells[i].spellId = 0;
9424 m_charmspells[i].active = ACT_DISABLED;
9428 void CharmInfo::InitPetActionBar()
9430 // the first 3 SpellOrActions are attack, follow and stay
9431 for(uint32 i = 0; i < 3; i++)
9433 PetActionBar[i].Type = ACT_COMMAND;
9434 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
9436 PetActionBar[i + 7].Type = ACT_REACTION;
9437 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
9439 for(uint32 i=0; i < 4; i++)
9441 PetActionBar[i + 3].Type = ACT_DISABLED;
9442 PetActionBar[i + 3].SpellOrAction = 0;
9446 void CharmInfo::InitEmptyActionBar()
9448 for(uint32 x = 1; x < 10; ++x)
9450 PetActionBar[x].Type = ACT_PASSIVE;
9451 PetActionBar[x].SpellOrAction = 0;
9453 PetActionBar[0].Type = ACT_COMMAND;
9454 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
9457 void CharmInfo::InitPossessCreateSpells()
9459 if(m_unit->GetTypeId() == TYPEID_PLAYER)
9460 return;
9462 InitEmptyActionBar(); //charm action bar
9464 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
9466 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
9467 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
9468 else
9469 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
9473 void CharmInfo::InitCharmCreateSpells()
9475 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
9477 InitEmptyActionBar();
9478 return;
9481 InitPetActionBar();
9483 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
9485 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
9486 m_charmspells[x].spellId = spellId;
9488 if(!spellId)
9489 continue;
9491 if (IsPassiveSpell(spellId))
9493 m_unit->CastSpell(m_unit, spellId, true);
9494 m_charmspells[x].active = ACT_PASSIVE;
9496 else
9498 ActiveStates newstate;
9499 bool onlyselfcast = true;
9500 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
9502 if(!spellInfo) onlyselfcast = false;
9503 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
9505 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
9506 onlyselfcast = false;
9509 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
9510 newstate = ACT_DISABLED;
9511 else
9512 newstate = ACT_PASSIVE;
9514 AddSpellToAB(0, spellId, newstate);
9519 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
9521 for(uint8 i = 0; i < 10; i++)
9523 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
9525 PetActionBar[i].SpellOrAction = newid;
9526 if(!oldid)
9528 if(newstate == ACT_DECIDE)
9529 PetActionBar[i].Type = ACT_DISABLED;
9530 else
9531 PetActionBar[i].Type = newstate;
9534 return true;
9537 return false;
9540 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
9542 if(IsPassiveSpell(spellid))
9543 return;
9545 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
9547 if(spellid == m_charmspells[x].spellId)
9549 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
9554 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
9556 m_petnumber = petnumber;
9557 if(statwindow)
9558 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
9559 else
9560 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
9563 bool Unit::isFrozen() const
9565 AuraList const& mRoot = GetAurasByType(SPELL_AURA_MOD_ROOT);
9566 for(AuraList::const_iterator i = mRoot.begin(); i != mRoot.end(); ++i)
9567 if( GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
9568 return true;
9569 return false;
9572 struct ProcTriggeredData
9574 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
9575 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
9576 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
9578 SpellProcEventEntry const *spellProcEvent;
9579 Aura* triggeredByAura;
9580 Unit::spellEffectPair triggeredByAura_SpellPair;
9583 typedef std::list< ProcTriggeredData > ProcTriggeredList;
9584 typedef std::list< uint32> RemoveSpellList;
9586 // List of auras that CAN be trigger but may not exist in spell_proc_event
9587 // in most case need for drop charges
9588 // in some types of aura need do additional check
9589 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
9590 bool InitTriggerAuraData()
9592 for (int i=0;i<TOTAL_AURAS;i++)
9594 isTriggerAura[i]=false;
9595 isNonTriggerAura[i] = false;
9597 isTriggerAura[SPELL_AURA_PERIODIC_DAMAGE] = true;
9598 isTriggerAura[SPELL_AURA_DUMMY] = true;
9599 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
9600 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
9601 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
9602 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
9603 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
9604 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
9605 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
9606 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
9607 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
9608 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
9609 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
9610 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED] = true;
9611 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
9612 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
9613 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
9614 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
9615 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
9616 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
9617 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
9618 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
9619 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
9620 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
9621 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
9622 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
9623 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
9624 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
9625 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
9627 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
9628 isNonTriggerAura[SPELL_AURA_RESIST_PUSHBACK]=true;
9630 return true;
9633 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
9635 uint32 procEx = PROC_EX_NONE;
9636 // Check victim state
9637 if (missCondition!=SPELL_MISS_NONE)
9638 switch (missCondition)
9640 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
9641 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
9642 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
9643 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
9644 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
9645 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
9646 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
9647 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
9648 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
9649 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
9650 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
9651 default:
9652 break;
9654 else
9656 // On block
9657 if (damageInfo->blocked)
9658 procEx|=PROC_EX_BLOCK;
9659 // On absorb
9660 if (damageInfo->absorb)
9661 procEx|=PROC_EX_ABSORB;
9662 // On crit
9663 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
9664 procEx|=PROC_EX_CRITICAL_HIT;
9665 else
9666 procEx|=PROC_EX_NORMAL_HIT;
9668 return procEx;
9671 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
9673 // For melee/ranged based attack need update skills and set some Aura states
9674 if (procFlag & MELEE_BASED_TRIGGER_MASK)
9676 // Update skills here for players
9677 if (GetTypeId() == TYPEID_PLAYER)
9679 // On melee based hit/miss/resist need update skill (for victim and attacker)
9680 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
9682 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
9683 ((Player*)this)->UpdateCombatSkills(pTarget, attType, MELEE_HIT_MISS, isVictim);
9685 // Update defence if player is victim and parry/dodge/block
9686 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
9687 ((Player*)this)->UpdateDefense();
9689 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
9690 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
9692 // for victim
9693 if (isVictim)
9695 // if victim and dodge attack
9696 if (procExtra&PROC_EX_DODGE)
9698 //Update AURA_STATE on dodge
9699 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
9701 ModifyAuraState(AURA_STATE_DEFENSE, true);
9702 StartReactiveTimer( REACTIVE_DEFENSE );
9705 // if victim and parry attack
9706 if (procExtra & PROC_EX_PARRY)
9708 // For Hunters only Counterattack (skip Mongoose bite)
9709 if (getClass() == CLASS_HUNTER)
9711 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
9712 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
9714 else
9716 ModifyAuraState(AURA_STATE_DEFENSE, true);
9717 StartReactiveTimer( REACTIVE_DEFENSE );
9720 // if and victim block attack
9721 if (procExtra & PROC_EX_BLOCK)
9723 ModifyAuraState(AURA_STATE_DEFENSE,true);
9724 StartReactiveTimer( REACTIVE_DEFENSE );
9727 else //For attacker
9729 // Overpower on victim dodge
9730 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
9732 ((Player*)this)->AddComboPoints(pTarget, 1);
9733 StartReactiveTimer( REACTIVE_OVERPOWER );
9739 RemoveSpellList removedSpells;
9740 ProcTriggeredList procTriggered;
9741 // Fill procTriggered list
9742 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
9744 SpellProcEventEntry const* spellProcEvent = NULL;
9745 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
9746 continue;
9748 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
9750 // Handle effects proceed this time
9751 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
9753 // Some auras can be deleted in function called in this loop (except first, ofc)
9754 // Until storing auars in std::multimap to hard check deleting by another way
9755 if(i != procTriggered.begin())
9757 bool found = false;
9758 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
9759 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
9760 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
9762 if(itr->second==i->triggeredByAura)
9764 found = true;
9765 break;
9768 if(!found)
9770 // 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);
9771 // sLog.outDebug("It can be deleted one from early proccesed auras:");
9772 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
9773 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
9774 // sLog.outDebug(" <end of list>");
9775 continue;
9779 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
9780 Aura *triggeredByAura = i->triggeredByAura;
9781 Modifier *auraModifier = triggeredByAura->GetModifier();
9782 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
9783 uint32 effIndex = triggeredByAura->GetEffIndex();
9784 bool useCharges = triggeredByAura->m_procCharges > 0;
9785 // For players set spell cooldown if need
9786 uint32 cooldown = 0;
9787 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
9788 cooldown = spellProcEvent->cooldown;
9790 switch(auraModifier->m_auraname)
9792 case SPELL_AURA_PROC_TRIGGER_SPELL:
9794 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
9795 // Don`t drop charge or add cooldown for not started trigger
9796 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9797 continue;
9798 break;
9800 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
9802 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());
9803 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
9804 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
9805 SendSpellNonMeleeDamageLog(&damageInfo);
9806 DealSpellDamage(&damageInfo, true);
9807 break;
9809 case SPELL_AURA_MANA_SHIELD:
9810 case SPELL_AURA_DUMMY:
9812 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());
9813 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9814 continue;
9815 break;
9817 case SPELL_AURA_MOD_HASTE:
9819 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());
9820 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9821 continue;
9822 break;
9824 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
9826 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());
9827 if (!HandleOverrideClassScriptAuraProc(pTarget, triggeredByAura, procSpell, cooldown))
9828 continue;
9829 break;
9831 case SPELL_AURA_PRAYER_OF_MENDING:
9833 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
9834 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
9836 HandleMeandingAuraProc(triggeredByAura);
9837 break;
9839 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
9841 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());
9843 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
9844 continue;
9845 break;
9847 case SPELL_AURA_MOD_STUN:
9848 // Remove by default, but if charge exist drop it
9849 if (triggeredByAura->m_procCharges == 0)
9850 removedSpells.push_back(triggeredByAura->GetId());
9851 break;
9852 case SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS:
9853 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
9854 // Hunter's Mark (1-4 Rangs)
9855 if (spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && (spellInfo->SpellFamilyFlags&0x0000000000000400LL))
9857 uint32 basevalue = triggeredByAura->GetBasePoints();
9858 auraModifier->m_amount += basevalue/10;
9859 if (auraModifier->m_amount > basevalue*4)
9860 auraModifier->m_amount = basevalue*4;
9862 break;
9863 case SPELL_AURA_MOD_CASTING_SPEED:
9864 // Skip melee hits or instant cast spells
9865 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
9866 continue;
9867 break;
9868 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
9869 // Skip Melee hits and spells ws wrong school
9870 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
9871 continue;
9872 break;
9873 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
9874 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
9875 // Skip melee hits and spells ws wrong school or zero cost
9876 if (procSpell == NULL ||
9877 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
9878 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
9879 continue;
9880 break;
9881 case SPELL_AURA_MECHANIC_IMMUNITY:
9882 // Compare mechanic
9883 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
9884 continue;
9885 break;
9886 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
9887 // Compare mechanic
9888 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
9889 continue;
9890 break;
9891 default:
9892 // nothing do, just charges counter
9893 break;
9895 // Remove charge (aura can be removed by triggers)
9896 if(useCharges)
9898 // need found aura on drop (can be dropped by triggers)
9899 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
9900 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
9901 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
9903 if(itr->second == i->triggeredByAura)
9905 triggeredByAura->m_procCharges -=1;
9906 triggeredByAura->UpdateAuraCharges();
9907 if (triggeredByAura->m_procCharges <= 0)
9908 removedSpells.push_back(triggeredByAura->GetId());
9909 break;
9914 if (removedSpells.size())
9916 // Sort spells and remove dublicates
9917 removedSpells.sort();
9918 removedSpells.unique();
9919 // Remove auras from removedAuras
9920 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
9921 RemoveAurasDueToSpell(*i);
9925 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
9927 return SPELL_SCHOOL_MASK_NORMAL;
9930 Player* Unit::GetSpellModOwner()
9932 if(GetTypeId()==TYPEID_PLAYER)
9933 return (Player*)this;
9934 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
9936 Unit* owner = GetOwner();
9937 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
9938 return (Player*)owner;
9940 return NULL;
9943 ///----------Pet responses methods-----------------
9944 void Unit::SendPetCastFail(uint32 spellid, uint8 msg)
9946 Unit *owner = GetCharmerOrOwner();
9947 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
9948 return;
9950 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
9951 data << uint8(0); // cast count?
9952 data << uint32(spellid);
9953 data << uint8(msg);
9954 // uint32 for some reason
9955 // uint32 for some reason
9956 ((Player*)owner)->GetSession()->SendPacket(&data);
9959 void Unit::SendPetActionFeedback (uint8 msg)
9961 Unit* owner = GetOwner();
9962 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
9963 return;
9965 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
9966 data << uint8(msg);
9967 ((Player*)owner)->GetSession()->SendPacket(&data);
9970 void Unit::SendPetTalk (uint32 pettalk)
9972 Unit* owner = GetOwner();
9973 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
9974 return;
9976 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
9977 data << uint64(GetGUID());
9978 data << uint32(pettalk);
9979 ((Player*)owner)->GetSession()->SendPacket(&data);
9982 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
9984 Unit* owner = GetOwner();
9985 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
9986 return;
9988 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
9989 data << uint64(GetGUID());
9990 data << uint8(0x0); // flags (0x1, 0x2)
9991 data << uint32(spellid);
9992 data << uint32(cooltime);
9994 ((Player*)owner)->GetSession()->SendPacket(&data);
9997 void Unit::SendPetClearCooldown (uint32 spellid)
9999 Unit* owner = GetOwner();
10000 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10001 return;
10003 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10004 data << uint32(spellid);
10005 data << uint64(GetGUID());
10006 ((Player*)owner)->GetSession()->SendPacket(&data);
10009 void Unit::SendPetAIReaction(uint64 guid)
10011 Unit* owner = GetOwner();
10012 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10013 return;
10015 WorldPacket data(SMSG_AI_REACTION, 12);
10016 data << uint64(guid) << uint32(00000002);
10017 ((Player*)owner)->GetSession()->SendPacket(&data);
10020 ///----------End of Pet responses methods----------
10022 void Unit::StopMoving()
10024 clearUnitState(UNIT_STAT_MOVING);
10026 // send explicit stop packet
10027 // rely on vmaps here because for example stormwind is in air
10028 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10029 //if (fabs(GetPositionZ() - z) < 2.0f)
10030 // Relocate(GetPositionX(), GetPositionY(), z);
10031 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10033 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10035 // update position and orientation;
10036 WorldPacket data;
10037 BuildHeartBeatMsg(&data);
10038 SendMessageToSet(&data,false);
10041 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10043 if( apply )
10045 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10046 return;
10048 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10050 GetMotionMaster()->MovementExpired(false);
10051 CastStop(GetGUID()==casterGUID ? spellID : 0);
10053 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10055 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10057 else
10059 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10061 GetMotionMaster()->MovementExpired(false);
10063 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10065 // restore appropriate movement generator
10066 if(getVictim())
10067 GetMotionMaster()->MoveChase(getVictim());
10068 else
10069 GetMotionMaster()->Initialize();
10071 // attack caster if can
10072 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10073 if(caster && caster != getVictim() && ((Creature*)this)->AI())
10074 ((Creature*)this)->AI()->AttackStart(caster);
10078 if (GetTypeId() == TYPEID_PLAYER)
10079 ((Player*)this)->SetClientControl(this, !apply);
10082 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10084 if( apply )
10086 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10088 CastStop(GetGUID()==casterGUID ? spellID : 0);
10090 GetMotionMaster()->MoveConfused();
10092 else
10094 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10096 GetMotionMaster()->MovementExpired(false);
10098 if (GetTypeId() == TYPEID_UNIT)
10100 // if in combat restore movement generator
10101 if(getVictim())
10102 GetMotionMaster()->MoveChase(getVictim());
10106 if(GetTypeId() == TYPEID_PLAYER)
10107 ((Player*)this)->SetClientControl(this, !apply);
10110 bool Unit::IsSitState() const
10112 uint8 s = getStandState();
10113 return s == PLAYER_STATE_SIT_CHAIR || s == PLAYER_STATE_SIT_LOW_CHAIR ||
10114 s == PLAYER_STATE_SIT_MEDIUM_CHAIR || s == PLAYER_STATE_SIT_HIGH_CHAIR ||
10115 s == PLAYER_STATE_SIT;
10118 bool Unit::IsStandState() const
10120 uint8 s = getStandState();
10121 return !IsSitState() && s != PLAYER_STATE_SLEEP && s != PLAYER_STATE_KNEEL;
10124 void Unit::SetStandState(uint8 state)
10126 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10128 if (IsStandState())
10129 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10131 if(GetTypeId()==TYPEID_PLAYER)
10133 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10134 data << (uint8)state;
10135 ((Player*)this)->GetSession()->SendPacket(&data);
10139 bool Unit::IsPolymorphed() const
10141 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10144 void Unit::SetDisplayId(uint32 modelId)
10146 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10148 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10150 Pet *pet = ((Pet*)this);
10151 if(!pet->isControlled())
10152 return;
10153 Unit *owner = GetOwner();
10154 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10155 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10159 void Unit::ClearComboPointHolders()
10161 while(!m_ComboPointHolders.empty())
10163 uint32 lowguid = *m_ComboPointHolders.begin();
10165 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10166 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10167 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10168 else
10169 m_ComboPointHolders.erase(lowguid); // or remove manually
10173 void Unit::ClearAllReactives()
10175 for(int i=0; i < MAX_REACTIVE; ++i)
10176 m_reactiveTimer[i] = 0;
10178 if (HasAuraState( AURA_STATE_DEFENSE))
10179 ModifyAuraState(AURA_STATE_DEFENSE, false);
10180 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10181 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10182 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10183 ((Player*)this)->ClearComboPoints();
10186 void Unit::UpdateReactives( uint32 p_time )
10188 for(int i = 0; i < MAX_REACTIVE; ++i)
10190 ReactiveType reactive = ReactiveType(i);
10192 if(!m_reactiveTimer[reactive])
10193 continue;
10195 if ( m_reactiveTimer[reactive] <= p_time)
10197 m_reactiveTimer[reactive] = 0;
10199 switch ( reactive )
10201 case REACTIVE_DEFENSE:
10202 if (HasAuraState(AURA_STATE_DEFENSE))
10203 ModifyAuraState(AURA_STATE_DEFENSE, false);
10204 break;
10205 case REACTIVE_HUNTER_PARRY:
10206 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10207 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10208 break;
10209 case REACTIVE_OVERPOWER:
10210 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10211 ((Player*)this)->ClearComboPoints();
10212 break;
10213 default:
10214 break;
10217 else
10219 m_reactiveTimer[reactive] -= p_time;
10224 Unit* Unit::SelectNearbyTarget() const
10226 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
10227 Cell cell(p);
10228 cell.data.Part.reserved = ALL_DISTRICT;
10229 cell.SetNoCreate();
10231 std::list<Unit *> targets;
10234 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
10235 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(targets, u_check);
10237 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
10238 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
10240 CellLock<GridReadGuard> cell_lock(cell, p);
10241 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
10242 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
10245 // remove current target
10246 if(getVictim())
10247 targets.remove(getVictim());
10249 // remove not LoS targets
10250 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
10252 if(!IsWithinLOSInMap(*tIter))
10254 std::list<Unit *>::iterator tIter2 = tIter;
10255 ++tIter;
10256 targets.erase(tIter2);
10258 else
10259 ++tIter;
10262 // no appropriate targets
10263 if(targets.empty())
10264 return NULL;
10266 // select random
10267 uint32 rIdx = urand(0,targets.size()-1);
10268 std::list<Unit *>::const_iterator tcIter = targets.begin();
10269 for(uint32 i = 0; i < rIdx; ++i)
10270 ++tcIter;
10272 return *tcIter;
10275 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
10277 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
10279 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
10280 return true;
10282 return false;
10285 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
10287 if(val > 0)
10289 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
10290 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
10292 else
10294 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
10295 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
10299 void Unit::ApplyCastTimePercentMod(float val, bool apply )
10301 if(val > 0)
10302 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
10303 else
10304 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
10307 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
10309 // Not apply this to creature casted spells with casttime==0
10310 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
10311 return 3500;
10313 if (CastingTime > 7000) CastingTime = 7000;
10314 if (CastingTime < 1500) CastingTime = 1500;
10316 if(damagetype == DOT && !IsChanneledSpell(spellProto))
10317 CastingTime = 3500;
10319 int32 overTime = 0;
10320 uint8 effects = 0;
10321 bool DirectDamage = false;
10322 bool AreaEffect = false;
10324 for ( uint32 i=0; i<3;i++)
10326 switch ( spellProto->Effect[i] )
10328 case SPELL_EFFECT_SCHOOL_DAMAGE:
10329 case SPELL_EFFECT_POWER_DRAIN:
10330 case SPELL_EFFECT_HEALTH_LEECH:
10331 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
10332 case SPELL_EFFECT_POWER_BURN:
10333 case SPELL_EFFECT_HEAL:
10334 DirectDamage = true;
10335 break;
10336 case SPELL_EFFECT_APPLY_AURA:
10337 switch ( spellProto->EffectApplyAuraName[i] )
10339 case SPELL_AURA_PERIODIC_DAMAGE:
10340 case SPELL_AURA_PERIODIC_HEAL:
10341 case SPELL_AURA_PERIODIC_LEECH:
10342 if ( GetSpellDuration(spellProto) )
10343 overTime = GetSpellDuration(spellProto);
10344 break;
10345 default:
10346 // -5% per additional effect
10347 ++effects;
10348 break;
10350 default:
10351 break;
10354 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
10355 AreaEffect = true;
10358 // Combined Spells with Both Over Time and Direct Damage
10359 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
10361 // mainly for DoTs which are 3500 here otherwise
10362 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
10363 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
10364 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
10365 // Portion to Over Time
10366 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
10368 if ( damagetype == DOT )
10369 CastingTime = uint32(CastingTime * PtOT);
10370 else if ( PtOT < 1.0f )
10371 CastingTime = uint32(CastingTime * (1 - PtOT));
10372 else
10373 CastingTime = 0;
10376 // Area Effect Spells receive only half of bonus
10377 if ( AreaEffect )
10378 CastingTime /= 2;
10380 // -5% of total per any additional effect
10381 for ( uint8 i=0; i<effects; ++i)
10383 if ( CastingTime > 175 )
10385 CastingTime -= 175;
10387 else
10389 CastingTime = 0;
10390 break;
10394 return CastingTime;
10397 void Unit::UpdateAuraForGroup(uint8 slot)
10399 if(GetTypeId() == TYPEID_PLAYER)
10401 Player* player = (Player*)this;
10402 if(player->GetGroup())
10404 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
10405 player->SetAuraUpdateMask(slot);
10408 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10410 Pet *pet = ((Pet*)this);
10411 if(pet->isControlled())
10413 Unit *owner = GetOwner();
10414 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10416 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
10417 pet->SetAuraUpdateMask(slot);
10423 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
10425 if (!normalized || GetTypeId() != TYPEID_PLAYER)
10426 return float(GetAttackTime(attType))/1000.0f;
10428 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
10429 if (!Weapon)
10430 return 2.4; // fist attack
10432 switch (Weapon->GetProto()->InventoryType)
10434 case INVTYPE_2HWEAPON:
10435 return 3.3;
10436 case INVTYPE_RANGED:
10437 case INVTYPE_RANGEDRIGHT:
10438 case INVTYPE_THROWN:
10439 return 2.8;
10440 case INVTYPE_WEAPON:
10441 case INVTYPE_WEAPONMAINHAND:
10442 case INVTYPE_WEAPONOFFHAND:
10443 default:
10444 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
10448 Aura* Unit::GetDummyAura( uint32 spell_id ) const
10450 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
10451 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
10452 if ((*itr)->GetId() == spell_id)
10453 return *itr;
10455 return NULL;
10458 bool Unit::IsUnderLastManaUseEffect() const
10460 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
10463 void Unit::SetContestedPvP(Player *attackedPlayer)
10465 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
10467 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
10468 return;
10470 player->SetContestedPvPTimer(30000);
10471 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
10473 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
10474 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
10475 // call MoveInLineOfSight for nearby contested guards
10476 SetVisibility(GetVisibility());
10478 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
10480 addUnitState(UNIT_STAT_ATTACK_PLAYER);
10481 // call MoveInLineOfSight for nearby contested guards
10482 SetVisibility(GetVisibility());
10486 void Unit::AddPetAura(PetAura const* petSpell)
10488 m_petAuras.insert(petSpell);
10489 if(Pet* pet = GetPet())
10490 pet->CastPetAura(petSpell);
10493 void Unit::RemovePetAura(PetAura const* petSpell)
10495 m_petAuras.erase(petSpell);
10496 if(Pet* pet = GetPet())
10497 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
10500 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
10502 Pet* pet = new Pet(HUNTER_PET);
10504 if(!pet->CreateBaseAtCreature(creatureTarget))
10506 delete pet;
10507 return NULL;
10510 pet->SetOwnerGUID(GetGUID());
10511 pet->SetCreatorGUID(GetGUID());
10512 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
10513 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
10515 if(GetTypeId()==TYPEID_PLAYER)
10516 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
10518 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
10519 pet->SetFreeTalentPoints(pet->GetMaxTalentPointsForLevel(level));
10521 if(!pet->InitStatsForLevel(level))
10523 sLog.outError("ERROR: Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
10524 delete pet;
10525 return NULL;
10528 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
10529 // this enables pet details window (Shift+P)
10530 pet->AIM_Initialize();
10531 pet->InitPetCreateSpells();
10532 pet->SetHealth(pet->GetMaxHealth());
10534 return pet;
10537 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
10539 SpellEntry const* spellProto = aura->GetSpellProto ();
10541 // Get proc Event Entry
10542 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
10544 // Aura info stored here
10545 Modifier *mod = aura->GetModifier();
10546 // Skip this auras
10547 if (isNonTriggerAura[mod->m_auraname])
10548 return false;
10549 // If not trigger by default and spellProcEvent==NULL - skip
10550 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
10551 return false;
10553 // Get EventProcFlag
10554 uint32 EventProcFlag;
10555 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
10556 EventProcFlag = spellProcEvent->procFlags;
10557 else
10558 EventProcFlag = spellProto->procFlags; // else get from spell proto
10559 // Continue if no trigger exist
10560 if (!EventProcFlag)
10561 return false;
10563 // Check spellProcEvent data requirements
10564 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
10565 return false;
10567 // In most cases req get honor or XP from kill
10568 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
10570 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
10571 // Shadow Word: Death - can trigger from every kill
10572 if (aura->GetId() == 32409)
10573 allow = true;
10574 if (!allow)
10575 return false;
10577 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
10578 // But except periodic triggers (can triggered from self)
10579 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
10580 return false;
10582 // Check if current equipment allows aura to proc
10583 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
10585 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
10587 Item *item = NULL;
10588 if(attType == BASE_ATTACK)
10589 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
10590 else if (attType == OFF_ATTACK)
10591 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
10592 else
10593 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
10595 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
10596 return false;
10598 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
10599 return false;
10601 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
10603 // Check if player is wearing shield
10604 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
10605 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
10606 return false;
10609 // Get chance from spell
10610 float chance = (float)spellProto->procChance;
10611 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
10612 if(spellProcEvent && spellProcEvent->customChance)
10613 chance = spellProcEvent->customChance;
10614 // If PPM exist calculate chance from PPM
10615 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
10617 uint32 WeaponSpeed = GetAttackTime(attType);
10618 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
10620 // Apply chance modifer aura
10621 if(Player* modOwner = GetSpellModOwner())
10622 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
10624 return roll_chance_f(chance);
10627 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
10629 // aura can be deleted at casts
10630 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
10631 uint32 effIdx = triggeredByAura->GetEffIndex();
10632 int32 heal = triggeredByAura->GetModifier()->m_amount;
10633 uint64 caster_guid = triggeredByAura->GetCasterGUID();
10635 // jumps
10636 int32 jumps = triggeredByAura->m_procCharges-1;
10638 // current aura expire
10639 triggeredByAura->m_procCharges = 1; // will removed at next charges decrease
10641 // next target selection
10642 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
10644 float radius;
10645 if (spellProto->EffectRadiusIndex[effIdx])
10646 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
10647 else
10648 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
10650 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
10652 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
10654 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
10656 // aura will applied from caster, but spell casted from current aura holder
10657 SpellModifier *mod = new SpellModifier;
10658 mod->op = SPELLMOD_CHARGES;
10659 mod->value = jumps-5; // negative
10660 mod->type = SPELLMOD_FLAT;
10661 mod->spellId = spellProto->Id;
10662 mod->mask = spellProto->SpellFamilyFlags;
10663 mod->mask2 = spellProto->SpellFamilyFlags2;
10665 caster->AddSpellMod(mod, true);
10666 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
10667 caster->AddSpellMod(mod, false);
10672 // heal
10673 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
10674 return true;
10677 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
10679 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
10681 if(!IS_UNIT_GUID(target_guid))
10682 return;
10684 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
10685 if(!target)
10686 return;
10688 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
10690 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
10691 target->RemoveAura(iter);
10692 else
10693 ++iter;