Use configuration values for arena directly instead of values cached in local variabl...
[getmangos.git] / src / game / Unit.cpp
blob6b021721d9799008ba3403e281957510dbad323e
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Log.h"
21 #include "Opcodes.h"
22 #include "WorldPacket.h"
23 #include "WorldSession.h"
24 #include "World.h"
25 #include "ObjectMgr.h"
26 #include "SpellMgr.h"
27 #include "Unit.h"
28 #include "QuestDef.h"
29 #include "Player.h"
30 #include "Creature.h"
31 #include "Spell.h"
32 #include "Group.h"
33 #include "SpellAuras.h"
34 #include "MapManager.h"
35 #include "ObjectAccessor.h"
36 #include "CreatureAI.h"
37 #include "Formulas.h"
38 #include "Pet.h"
39 #include "Util.h"
40 #include "Totem.h"
41 #include "BattleGround.h"
42 #include "InstanceSaveMgr.h"
43 #include "GridNotifiersImpl.h"
44 #include "CellImpl.h"
45 #include "Path.h"
47 #include <math.h>
49 float baseMoveSpeed[MAX_MOVE_TYPE] =
51 2.5f, // MOVE_WALK
52 7.0f, // MOVE_RUN
53 1.25f, // MOVE_RUN_BACK
54 4.722222f, // MOVE_SWIM
55 4.5f, // MOVE_SWIM_BACK
56 3.141594f, // MOVE_TURN_RATE
57 7.0f, // MOVE_FLIGHT
58 4.5f, // MOVE_FLIGHT_BACK
59 3.14f // MOVE_PITCH_RATE
62 // Used for prepare can/can`t triggr aura
63 static bool InitTriggerAuraData();
64 // Define can trigger auras
65 static bool isTriggerAura[TOTAL_AURAS];
66 // Define can`t trigger auras (need for disable second trigger)
67 static bool isNonTriggerAura[TOTAL_AURAS];
68 // Prepare lists
69 static bool procPrepared = InitTriggerAuraData();
71 Unit::Unit()
72 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
74 m_objectType |= TYPEMASK_UNIT;
75 m_objectTypeId = TYPEID_UNIT;
76 // 2.3.2 - 0x70
77 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
79 m_attackTimer[BASE_ATTACK] = 0;
80 m_attackTimer[OFF_ATTACK] = 0;
81 m_attackTimer[RANGED_ATTACK] = 0;
82 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
83 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
84 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
86 m_extraAttacks = 0;
88 m_state = 0;
89 m_form = FORM_NONE;
90 m_deathState = ALIVE;
92 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
93 m_currentSpells[i] = NULL;
95 m_addDmgOnce = 0;
97 for(int i = 0; i < MAX_TOTEM; ++i)
98 m_TotemSlot[i] = 0;
100 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
101 //m_Aura = NULL;
102 //m_AurasCheck = 2000;
103 //m_removeAuraTimer = 4;
104 //tmpAura = NULL;
106 m_Visibility = VISIBILITY_ON;
108 m_detectInvisibilityMask = 0;
109 m_invisibilityMask = 0;
110 m_transform = 0;
111 m_ShapeShiftFormSpellId = 0;
112 m_canModifyStats = false;
114 for (int i = 0; i < MAX_SPELL_IMMUNITY; i++)
115 m_spellImmune[i].clear();
116 for (int i = 0; i < UNIT_MOD_END; i++)
118 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
119 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
120 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
121 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
123 // implement 50% base damage from offhand
124 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
126 for (int i = 0; i < 3; i++)
128 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
129 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
131 for (int i = 0; i < MAX_STATS; i++)
132 m_createStats[i] = 0.0f;
134 m_attacking = NULL;
135 m_modMeleeHitChance = 0.0f;
136 m_modRangedHitChance = 0.0f;
137 m_modSpellHitChance = 0.0f;
138 m_baseSpellCritChance = 5;
140 m_CombatTimer = 0;
141 m_lastManaUse = 0;
143 //m_victimThreat = 0.0f;
144 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
145 m_threatModifier[i] = 1.0f;
146 m_isSorted = true;
147 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
148 m_speed_rate[i] = 1.0f;
150 m_removedAuras = 0;
151 m_charmInfo = NULL;
152 m_unit_movement_flags = 0;
154 // remove aurastates allowing special moves
155 for(int i=0; i < MAX_REACTIVE; ++i)
156 m_reactiveTimer[i] = 0;
159 Unit::~Unit()
161 // set current spells as deletable
162 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
164 if (m_currentSpells[i])
166 m_currentSpells[i]->SetReferencedFromCurrent(false);
167 m_currentSpells[i] = NULL;
171 RemoveAllGameObjects();
172 RemoveAllDynObjects();
174 if(m_charmInfo) delete m_charmInfo;
177 void Unit::Update( uint32 p_time )
179 /*if(p_time > m_AurasCheck)
181 m_AurasCheck = 2000;
182 _UpdateAura();
183 }else
184 m_AurasCheck -= p_time;*/
186 // WARNING! Order of execution here is important, do not change.
187 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
188 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
189 m_Events.Update( p_time );
190 _UpdateSpells( p_time );
192 // update combat timer only for players and pets
193 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
195 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
196 // targets without stopping half way there and running off.
197 // These flags are reset after target dies or another command is given.
198 if( m_HostilRefManager.isEmpty() )
200 // m_CombatTimer set at aura start and it will be freeze until aura removing
201 if ( m_CombatTimer <= p_time )
202 ClearInCombat();
203 else
204 m_CombatTimer -= p_time;
208 if(uint32 base_att = getAttackTimer(BASE_ATTACK))
210 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
213 // update abilities available only for fraction of time
214 UpdateReactives( p_time );
216 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
217 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
218 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
220 i_motionMaster.UpdateMotion(p_time);
223 bool Unit::haveOffhandWeapon() const
225 if(GetTypeId() == TYPEID_PLAYER)
226 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
227 else
228 return false;
231 void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
233 float x, y, z;
234 if(GetMotionMaster()->GetDestination(x, y, z))
235 SendMonsterMoveWithSpeed(x, y, z, GetUnitMovementFlags(), 0, player);
238 void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 MovementFlags, uint32 transitTime, Player* player)
240 if (!transitTime)
242 float dx = x - GetPositionX();
243 float dy = y - GetPositionY();
244 float dz = z - GetPositionZ();
246 float dist = ((dx*dx) + (dy*dy) + (dz*dz));
247 if(dist<0)
248 dist = 0;
249 else
250 dist = sqrt(dist);
252 double speed = GetSpeed((MovementFlags & MOVEMENTFLAG_WALK_MODE) ? MOVE_WALK : MOVE_RUN);
253 if(speed<=0)
254 speed = 2.5f;
255 speed *= 0.001f;
256 transitTime = static_cast<uint32>(dist / speed + 0.5);
258 //float orientation = (float)atan2((double)dy, (double)dx);
259 SendMonsterMove(x, y, z, 0, MovementFlags, transitTime, player);
262 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player)
264 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
265 data.append(GetPackGUID());
267 // Point A, starting location
268 data << GetPositionX() << GetPositionY() << GetPositionZ();
269 // unknown field - unrelated to orientation
270 // seems to increment about 1000 for every 1.7 seconds
271 // for now, we'll just use mstime
272 data << getMSTime();
274 data << uint8(type); // unknown
275 switch(type)
277 case 0: // normal packet
278 break;
279 case 1: // stop packet
280 SendMessageToSet( &data, true );
281 return;
282 case 2: // not used currently
283 data << float(0);
284 data << float(0);
285 data << float(0);
286 break;
287 case 3: // not used currently
288 data << uint64(0); // probably target guid
289 break;
290 case 4: // not used currently
291 data << float(0); // probably orientation
292 break;
295 //Movement Flags (0x0 = walk, 0x100 = run, 0x200 = fly/swim)
296 data << uint32(MovementFlags);
298 data << Time; // Time in between points
299 data << uint32(1); // 1 single waypoint
300 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
302 if(player)
303 player->GetSession()->SendPacket(&data);
304 else
305 SendMessageToSet( &data, true );
308 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, uint32 MovementFlags)
310 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
312 uint32 pathSize = end-start;
314 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+4+4+4+4+1+4+4+4+pathSize*4*3) );
315 data.append(GetPackGUID());
316 data << GetPositionX();
317 data << GetPositionY();
318 data << GetPositionZ();
320 // unknown field - unrelated to orientation
321 // seems to increment about 1000 for every 1.7 seconds
322 // for now, we'll just use mstime
323 data << getMSTime();
325 data << uint8( 0 );
326 data << uint32( MovementFlags );
327 data << uint32( traveltime );
328 data << uint32( pathSize );
329 data.append( (char*)path.GetNodes(start), pathSize * 4 * 3 );
331 //WPAssert( data.size() == 37 + pathnodes.Size( ) * 4 * 3 );
332 SendMessageToSet(&data, true);
335 void Unit::resetAttackTimer(WeaponAttackType type)
337 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
340 bool Unit::canReachWithAttack(Unit *pVictim) const
342 assert(pVictim);
343 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
344 if( reach <= 0.0f )
345 reach = 1.0f;
346 return IsWithinDistInMap(pVictim, reach);
349 void Unit::RemoveSpellsCausingAura(AuraType auraType)
351 if (auraType >= TOTAL_AURAS) return;
352 AuraList::iterator iter, next;
353 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
355 next = iter;
356 ++next;
358 if (*iter)
360 RemoveAurasDueToSpell((*iter)->GetId());
361 if (!m_modAuras[auraType].empty())
362 next = m_modAuras[auraType].begin();
363 else
364 return;
369 bool Unit::HasAuraType(AuraType auraType) const
371 return (!m_modAuras[auraType].empty());
374 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
375 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
377 if(!HasAuraType(auraType))
378 return;
380 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
381 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
382 float chance = float(damage) / max_dmg * 100.0f;
383 if (roll_chance_f(chance))
384 RemoveSpellsCausingAura(auraType);
387 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
389 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
390 return 0;
392 //You don't lose health from damage taken from another player while in a sanctuary
393 //You still see it in the combat log though
394 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
396 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
397 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
398 return 0;
401 // remove affects from victim (including from 0 damage and DoTs)
402 if(pVictim != this)
403 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
405 // remove affects from attacker at any non-DoT damage (including 0 damage)
406 if( damagetype != DOT)
408 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
409 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
411 if(pVictim != this)
412 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
414 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
415 pVictim->SetStandState(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)
803 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
804 pVictim->InterruptSpell(i);
805 else
806 spell->Delayed();
811 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
813 if (spell->getState() == SPELL_STATE_CASTING)
815 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
816 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
818 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
819 spell->DelayedChannel();
821 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
823 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
824 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
827 else if (spell->getState() == SPELL_STATE_DELAYED)
828 // break channeled spell in delayed state on damage
830 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
831 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
836 // last damage from duel opponent
837 if(duel_hasEnded)
839 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
840 Player *he = (Player*)pVictim;
842 assert(he->duel);
844 he->SetHealth(1);
846 he->duel->opponent->CombatStopWithPets(true);
847 he->CombatStopWithPets(true);
849 he->CastSpell(he, 7267, true); // beg
850 he->DuelComplete(DUEL_WON);
854 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
856 return damage;
859 void Unit::CastStop(uint32 except_spellid)
861 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
862 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
863 InterruptSpell(i,false);
866 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
868 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
870 if(!spellInfo)
872 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
873 return;
876 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
879 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
881 if(!spellInfo)
883 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
884 return;
887 if (castItem)
888 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
890 if(!originalCaster && triggeredByAura)
891 originalCaster = triggeredByAura->GetCasterGUID();
893 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
895 SpellCastTargets targets;
896 targets.setUnitTarget( Victim );
897 spell->m_CastItem = castItem;
898 spell->prepare(&targets, triggeredByAura);
901 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
903 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
905 if(!spellInfo)
907 sLog.outError("CastCustomSpell: unknown spell id %i\n", spellId);
908 return;
911 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
914 void Unit::CastCustomSpell(Unit* Victim,SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
916 if(!spellInfo)
918 sLog.outError("CastCustomSpell: unknown spell");
919 return;
922 if (castItem)
923 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
925 if(!originalCaster && triggeredByAura)
926 originalCaster = triggeredByAura->GetCasterGUID();
928 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
930 if(bp0)
931 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
933 if(bp1)
934 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
936 if(bp2)
937 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
939 SpellCastTargets targets;
940 targets.setUnitTarget( Victim );
941 spell->m_CastItem = castItem;
942 spell->prepare(&targets, triggeredByAura);
945 // used for scripting
946 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
948 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
950 if(!spellInfo)
952 sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
953 return;
956 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
959 // used for scripting
960 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
962 if(!spellInfo)
964 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
965 return;
968 if (castItem)
969 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
971 if(!originalCaster && triggeredByAura)
972 originalCaster = triggeredByAura->GetCasterGUID();
974 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
976 SpellCastTargets targets;
977 targets.setDestination(x, y, z);
978 spell->m_CastItem = castItem;
979 spell->prepare(&targets, triggeredByAura);
982 // Obsolete func need remove, here only for comotability vs another patches
983 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
985 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
986 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
987 CalculateSpellDamage(&damageInfo, damage, spellInfo);
988 SendSpellNonMeleeDamageLog(&damageInfo);
989 DealSpellDamage(&damageInfo, true);
990 return damageInfo.damage;
993 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
995 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
996 Unit *pVictim = damageInfo->target;
998 if (damage < 0)
999 return;
1001 if(!this || !pVictim)
1002 return;
1003 if(!this->isAlive() || !pVictim->isAlive())
1004 return;
1006 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1007 // Check spell crit chance
1008 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1009 bool blocked = false;
1010 // Per-school calc
1011 switch (spellInfo->DmgClass)
1013 // Melee and Ranged Spells
1014 case SPELL_DAMAGE_CLASS_RANGED:
1015 case SPELL_DAMAGE_CLASS_MELEE:
1017 // Physical Damage
1018 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1020 //Calculate armor mitigation
1021 damage = CalcArmorReducedDamage(pVictim, damage);
1022 // Get blocked status
1023 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1025 // Magical Damage
1026 else
1028 // Calculate damage bonus
1029 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1031 if (crit)
1033 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1035 // Calculate crit bonus
1036 uint32 crit_bonus = damage;
1037 // Apply crit_damage bonus for melee spells
1038 if(Player* modOwner = GetSpellModOwner())
1039 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1040 damage += crit_bonus;
1042 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1043 int32 critPctDamageMod=0;
1044 if(attackType == RANGED_ATTACK)
1045 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1046 else
1048 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1049 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1051 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1052 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1054 if (critPctDamageMod!=0)
1055 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1057 // Resilience - reduce crit damage
1058 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1059 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1061 // Spell weapon based damage CAN BE crit & blocked at same time
1062 if (blocked)
1064 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1065 if (damage < damageInfo->blocked)
1066 damageInfo->blocked = damage;
1067 damage-=damageInfo->blocked;
1070 break;
1071 // Magical Attacks
1072 case SPELL_DAMAGE_CLASS_NONE:
1073 case SPELL_DAMAGE_CLASS_MAGIC:
1075 // Calculate damage bonus
1076 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1077 // If crit add critical bonus
1078 if (crit)
1080 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1081 damage = SpellCriticalBonus(spellInfo, damage, pVictim);
1082 // Resilience - reduce crit damage
1083 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1084 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1087 break;
1090 // Calculate absorb resist
1091 if(damage > 0)
1093 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1094 damage-= damageInfo->absorb + damageInfo->resist;
1096 else
1097 damage = 0;
1098 damageInfo->damage = damage;
1101 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1103 if (damageInfo==0)
1104 return;
1106 Unit *pVictim = damageInfo->target;
1108 if(!this || !pVictim)
1109 return;
1111 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1112 return;
1114 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1115 if (spellProto == NULL)
1117 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1118 return;
1121 //You don't lose health from damage taken from another player while in a sanctuary
1122 //You still see it in the combat log though
1123 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1125 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1126 if(area && area->flags & 0x800) //sanctuary
1127 return;
1130 // Call default DealDamage
1131 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1132 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1135 //TODO for melee need create structure as in
1136 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1138 damageInfo->attacker = this;
1139 damageInfo->target = pVictim;
1140 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1141 damageInfo->attackType = attackType;
1142 damageInfo->damage = 0;
1143 damageInfo->cleanDamage = 0;
1144 damageInfo->absorb = 0;
1145 damageInfo->resist = 0;
1146 damageInfo->blocked_amount = 0;
1148 damageInfo->TargetState = 0;
1149 damageInfo->HitInfo = 0;
1150 damageInfo->procAttacker = PROC_FLAG_NONE;
1151 damageInfo->procVictim = PROC_FLAG_NONE;
1152 damageInfo->procEx = PROC_EX_NONE;
1153 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1155 if(!this || !pVictim)
1156 return;
1157 if(!this->isAlive() || !pVictim->isAlive())
1158 return;
1160 // Select HitInfo/procAttacker/procVictim flag based on attack type
1161 switch (attackType)
1163 case BASE_ATTACK:
1164 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1165 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1166 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1167 break;
1168 case OFF_ATTACK:
1169 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1170 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1171 damageInfo->HitInfo = HITINFO_LEFTSWING;
1172 break;
1173 case RANGED_ATTACK:
1174 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1175 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1176 damageInfo->HitInfo = 0x08;// test
1177 break;
1178 default:
1179 break;
1182 // Physical Immune check
1183 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1185 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1186 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1188 damageInfo->procEx |=PROC_EX_IMMUNE;
1189 damageInfo->damage = 0;
1190 damageInfo->cleanDamage = 0;
1191 return;
1193 damage += CalculateDamage (damageInfo->attackType, false);
1194 // Add melee damage bonus
1195 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1196 // Calculate armor reduction
1197 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1198 damageInfo->cleanDamage += damage - damageInfo->damage;
1200 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1202 // Disable parry or dodge for ranged attack
1203 if(damageInfo->attackType == RANGED_ATTACK)
1205 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1206 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1209 switch(damageInfo->hitOutCome)
1211 case MELEE_HIT_EVADE:
1213 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1214 damageInfo->TargetState = VICTIMSTATE_EVADES;
1216 damageInfo->procEx|=PROC_EX_EVADE;
1217 damageInfo->damage = 0;
1218 damageInfo->cleanDamage = 0;
1219 return;
1221 case MELEE_HIT_MISS:
1223 damageInfo->HitInfo |= HITINFO_MISS;
1224 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1226 damageInfo->procEx|=PROC_EX_MISS;
1227 damageInfo->damage = 0;
1228 damageInfo->cleanDamage = 0;
1229 break;
1231 case MELEE_HIT_NORMAL:
1232 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1233 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1234 break;
1235 case MELEE_HIT_CRIT:
1237 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1238 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1240 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1241 // Crit bonus calc
1242 damageInfo->damage += damageInfo->damage;
1243 int32 mod=0;
1244 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1245 if(damageInfo->attackType == RANGED_ATTACK)
1246 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1247 else
1249 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1250 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1253 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1255 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1256 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1257 if (mod!=0)
1258 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1260 // Resilience - reduce crit damage
1261 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1263 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1264 damageInfo->damage -= resilienceReduction;
1265 damageInfo->cleanDamage += resilienceReduction;
1267 break;
1269 case MELEE_HIT_PARRY:
1270 damageInfo->TargetState = VICTIMSTATE_PARRY;
1271 damageInfo->procEx|=PROC_EX_PARRY;
1272 damageInfo->cleanDamage += damageInfo->damage;
1273 damageInfo->damage = 0;
1274 break;
1276 case MELEE_HIT_DODGE:
1277 damageInfo->TargetState = VICTIMSTATE_DODGE;
1278 damageInfo->procEx|=PROC_EX_DODGE;
1279 damageInfo->cleanDamage += damageInfo->damage;
1280 damageInfo->damage = 0;
1281 break;
1282 case MELEE_HIT_BLOCK:
1284 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1285 damageInfo->HitInfo |= HITINFO_BLOCK;
1286 damageInfo->procEx|=PROC_EX_BLOCK;
1287 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1288 if (damageInfo->blocked_amount >= damageInfo->damage)
1290 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1291 damageInfo->blocked_amount = damageInfo->damage;
1293 damageInfo->damage -= damageInfo->blocked_amount;
1294 damageInfo->cleanDamage += damageInfo->blocked_amount;
1295 break;
1297 case MELEE_HIT_GLANCING:
1299 damageInfo->HitInfo |= HITINFO_GLANCING;
1300 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1301 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1302 float reducePercent = 1.0f; //damage factor
1303 // calculate base values and mods
1304 float baseLowEnd = 1.3;
1305 float baseHighEnd = 1.2;
1306 switch(getClass()) // lowering base values for casters
1308 case CLASS_SHAMAN:
1309 case CLASS_PRIEST:
1310 case CLASS_MAGE:
1311 case CLASS_WARLOCK:
1312 case CLASS_DRUID:
1313 baseLowEnd -= 0.7;
1314 baseHighEnd -= 0.3;
1315 break;
1318 float maxLowEnd = 0.6;
1319 switch(getClass()) // upper for melee classes
1321 case CLASS_WARRIOR:
1322 case CLASS_ROGUE:
1323 maxLowEnd = 0.91; //If the attacker is a melee class then instead the lower value of 0.91
1326 // calculate values
1327 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1328 float lowEnd = baseLowEnd - ( 0.05f * diff );
1329 float highEnd = baseHighEnd - ( 0.03f * diff );
1331 // apply max/min bounds
1332 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1333 lowEnd = 0.01f;
1334 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1335 lowEnd = maxLowEnd;
1337 if ( highEnd < 0.2f ) //high end limits
1338 highEnd = 0.2f;
1339 if ( highEnd > 0.99f )
1340 highEnd = 0.99f;
1342 if(lowEnd > highEnd) // prevent negative range size
1343 lowEnd = highEnd;
1345 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1347 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1348 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1349 break;
1351 case MELEE_HIT_CRUSHING:
1353 damageInfo->HitInfo |= HITINFO_CRUSHING;
1354 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1355 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1356 // 150% normal damage
1357 damageInfo->damage += (damageInfo->damage / 2);
1358 break;
1360 default:
1362 break;
1365 // Calculate absorb resist
1366 if(int32(damageInfo->damage) > 0)
1368 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1369 // Calculate absorb & resists
1370 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1371 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1372 if (damageInfo->absorb)
1374 damageInfo->HitInfo|=HITINFO_ABSORB;
1375 damageInfo->procEx|=PROC_EX_ABSORB;
1377 if (damageInfo->resist)
1378 damageInfo->HitInfo|=HITINFO_RESIST;
1381 else // Umpossible get negative result but....
1382 damageInfo->damage = 0;
1385 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1387 if (damageInfo==0) return;
1388 Unit *pVictim = damageInfo->target;
1390 if(!this || !pVictim)
1391 return;
1393 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1394 return;
1396 //You don't lose health from damage taken from another player while in a sanctuary
1397 //You still see it in the combat log though
1398 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1400 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1401 if(area && area->flags & 0x800) //sanctuary
1402 return;
1405 // Hmmmm dont like this emotes cloent must by self do all animations
1406 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1407 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1408 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1409 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1411 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1413 // Get attack timers
1414 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1415 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1416 // Reduce attack time
1417 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1419 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20;
1420 float percent60 = 3 * percent20;
1421 if(offtime > percent20 && offtime <= percent60)
1423 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1425 else if(offtime > percent60)
1427 offtime -= 2 * percent20;
1428 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1431 else
1433 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1434 float percent60 = 3 * percent20;
1435 if(basetime > percent20 && basetime <= percent60)
1437 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1439 else if(basetime > percent60)
1441 basetime -= 2 * percent20;
1442 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1447 // Call default DealDamage
1448 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1449 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1451 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1452 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1453 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1455 // -probability is between 0% and 40%
1456 // 20% base chance
1457 float Probability = 20;
1459 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1460 if( pVictim->getLevel() < 30 )
1461 Probability = 0.65f*pVictim->getLevel()+0.5;
1463 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1464 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1466 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1468 if(Probability > 40)
1469 Probability = 40;
1471 if(roll_chance_f(Probability))
1472 CastSpell(pVictim, 1604, true);
1475 // If not miss
1476 if (!(damageInfo->HitInfo & HITINFO_MISS))
1478 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1480 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1481 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1484 // victim's damage shield
1485 std::set<Aura*> alreadyDone;
1486 uint32 removedAuras = pVictim->m_removedAuras;
1487 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1488 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1490 next++;
1491 if (alreadyDone.find(*i) == alreadyDone.end())
1493 alreadyDone.insert(*i);
1494 uint32 damage=(*i)->GetModifier()->m_amount;
1495 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1496 if(!spellProto)
1497 continue;
1498 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1499 //uint32 absorb;
1500 //uint32 resist;
1501 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1502 //damage-=absorb + resist;
1504 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1505 data << uint64(pVictim->GetGUID());
1506 data << uint64(GetGUID());
1507 data << uint32(spellProto->Id);
1508 data << uint32(damage); // Damage
1509 data << uint32(0); // Overkill
1510 data << uint32(spellProto->SchoolMask);
1511 pVictim->SendMessageToSet(&data, true );
1513 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1515 if (pVictim->m_removedAuras > removedAuras)
1517 removedAuras = pVictim->m_removedAuras;
1518 next = vDamageShields.begin();
1526 void Unit::HandleEmoteCommand(uint32 anim_id)
1528 WorldPacket data( SMSG_EMOTE, 12 );
1529 data << uint32(anim_id);
1530 data << uint64(GetGUID());
1531 SendMessageToSet(&data, true);
1534 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1536 uint32 newdamage = 0;
1537 float armor = pVictim->GetArmor();
1538 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1539 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1541 // Apply Player CR_ARMOR_PENETRATION rating
1542 if (GetTypeId()==TYPEID_PLAYER)
1543 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1545 if (armor < 0.0f) armor=0.0f;
1547 float levelModifier = getLevel();
1548 if ( levelModifier > 59 )
1549 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1551 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1552 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1554 if(tmpvalue < 0.0f)
1555 tmpvalue = 0.0f;
1556 if(tmpvalue > 0.75f)
1557 tmpvalue = 0.75f;
1558 newdamage = uint32(damage - (damage * tmpvalue));
1560 return (newdamage > 1) ? newdamage : 1;
1563 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1565 if(!pVictim || !pVictim->isAlive() || !damage)
1566 return;
1568 // Magic damage, check for resists
1569 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1571 // Get base victim resistance for school
1572 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1573 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1574 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1576 tmpvalue2 *= (float)(0.15f / getLevel());
1577 if (tmpvalue2 < 0.0f)
1578 tmpvalue2 = 0.0f;
1579 if (tmpvalue2 > 0.75f)
1580 tmpvalue2 = 0.75f;
1581 uint32 ran = urand(0, 100);
1582 uint32 faq[4] = {24,6,4,6};
1583 uint8 m = 0;
1584 float Binom = 0.0f;
1585 for (uint8 i = 0; i < 4; i++)
1587 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1588 if (ran > Binom )
1589 ++m;
1590 else
1591 break;
1593 if (damagetype == DOT && m == 4)
1594 *resist += uint32(damage - 1);
1595 else
1596 *resist += uint32(damage * m / 4);
1597 if(*resist > damage)
1598 *resist = damage;
1600 else
1601 *resist = 0;
1603 int32 RemainingDamage = damage - *resist;
1605 // Get unit state (need for some absorb check)
1606 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1607 // Need remove expired auras after
1608 bool existExpired = false;
1609 // absorb without mana cost
1610 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1611 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1613 Modifier* mod = (*i)->GetModifier();
1614 if (!(mod->m_miscvalue & schoolMask))
1615 continue;
1617 SpellEntry const* spellProto = (*i)->GetSpellProto();
1619 // Max Amount can be absorbed by this aura
1620 int32 currentAbsorb = mod->m_amount;
1622 // Found empty aura (umpossible but..)
1623 if (currentAbsorb <=0)
1625 existExpired = true;
1626 continue;
1628 // Handle custom absorb auras
1629 // TODO: try find better way
1630 switch(spellProto->SpellFamilyName)
1632 case SPELLFAMILY_GENERIC:
1634 // Astral Shift
1635 if (spellProto->SpellIconID == 3066)
1637 //reduces all damage taken while stun, fear or silence
1638 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1639 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1640 continue;
1642 // Nerves of Steel
1643 if (spellProto->SpellIconID == 2115)
1645 // while affected by Stun and Fear
1646 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1647 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1648 continue;
1650 // Spell Deflection
1651 if (spellProto->SpellIconID == 3006)
1653 // You have a chance equal to your Parry chance
1654 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1655 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1656 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1657 continue;
1659 // Reflective Shield (Lady Malande boss)
1660 if (spellProto->Id == 41475)
1662 int32 reflectDamage = 0;
1663 if(RemainingDamage < currentAbsorb)
1664 reflectDamage = RemainingDamage / 2;
1665 else
1666 reflectDamage = currentAbsorb / 2;
1667 pVictim->CastCustomSpell(this, 33619, &reflectDamage, NULL, NULL, true, NULL, *i);
1668 break;
1670 if (spellProto->Id == 39228 || // Argussian Compass
1671 spellProto->Id == 60218) // Essence of Gossamer
1673 // Max absorb stored in 1 dummy effect
1674 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1675 currentAbsorb = spellProto->EffectBasePoints[1];
1676 break;
1678 break;
1680 case SPELLFAMILY_DRUID:
1682 // Primal Tenacity
1683 if (spellProto->SpellIconID == 2253)
1685 //reduces all damage taken while Stunned
1686 if (unitflag & UNIT_FLAG_STUNNED)
1687 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1688 continue;
1690 break;
1692 case SPELLFAMILY_ROGUE:
1694 // Cheat Death
1695 if(spellProto->SpellIconID == 2109)
1697 if (pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1698 pVictim->GetHealth() <= RemainingDamage && // Only if damage kill
1699 !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
1700 roll_chance_i(currentAbsorb)) // Only if roll
1702 pVictim->CastSpell(pVictim,31231,true);
1703 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1704 // with health > 10% lost health until health==10%, in other case no losses
1705 uint32 health10 = pVictim->GetMaxHealth()/10;
1706 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1708 continue;
1710 break;
1712 case SPELLFAMILY_PRIEST:
1714 // Reflective Shield
1715 if (spellProto->SpellFamilyFlags == 0x1)
1717 if (pVictim == this)
1718 break;
1719 Unit* caster = (*i)->GetCaster();
1720 if (!caster)
1721 break;
1722 int32 reflectDamage = 0;
1723 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1724 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1726 switch((*k)->GetModifier()->m_miscvalue)
1728 case 5065: // Rank 1
1729 case 5064: // Rank 2
1730 case 5063: // Rank 3
1732 if(RemainingDamage >= currentAbsorb)
1733 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1734 else
1735 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1736 } break;
1737 default: break;
1739 if (reflectDamage)
1741 pVictim->CastCustomSpell(this, 33619, &reflectDamage, NULL, NULL, true, NULL, *i);
1742 break;
1745 break;
1747 break;
1749 case SPELLFAMILY_SHAMAN:
1751 // Astral Shift
1752 if (spellProto->SpellIconID == 3066)
1754 //reduces all damage taken while stun, fear or silence
1755 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1756 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1757 continue;
1759 break;
1761 case SPELLFAMILY_DEATHKNIGHT:
1763 // Shadow of Death
1764 if (spellProto->SpellIconID == 1958)
1766 // TODO: absorb only while transform
1767 continue;
1769 // Anti-Magic Shell (on self)
1770 if (spellProto->Id == 48707)
1772 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1773 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1774 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1775 int32 regen = absorbed * 2 / 10;
1776 pVictim->CastCustomSpell(pVictim, 49088, &regen, 0, 0, true, 0, *i);
1777 RemainingDamage -= absorbed;
1778 continue;
1780 // Anti-Magic Shell (on single party/raid member)
1781 if (spellProto->Id == 50462)
1783 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1784 continue;
1786 // Anti-Magic Zone
1787 if (spellProto->Id == 50461)
1789 Unit* caster = (*i)->GetCaster();
1790 if (!caster)
1791 continue;
1792 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1793 int32 canabsorb = caster->GetHealth();
1794 if (canabsorb < absorbed)
1795 absorbed = canabsorb;
1796 DealDamage(caster, absorbed, NULL, damagetype, schoolMask, 0, false);
1797 RemainingDamage -= absorbed;
1798 continue;
1800 break;
1802 default:
1803 break;
1806 // currentAbsorb - damage can be absorbed by shield
1807 // If need absorb less damage
1808 if (RemainingDamage < currentAbsorb)
1809 currentAbsorb = RemainingDamage;
1811 RemainingDamage -= currentAbsorb;
1813 // Reduce shield amount
1814 mod->m_amount-=currentAbsorb;
1815 // Need remove it later
1816 if (mod->m_amount<=0)
1817 existExpired = true;
1820 // Remove all expired absorb auras
1821 if (existExpired)
1823 for(AuraList::const_iterator i = vSchoolAbsorb.begin(), next; i != vSchoolAbsorb.end();)
1825 if ((*i)->GetModifier()->m_amount<=0)
1827 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1828 i = vSchoolAbsorb.begin();
1830 else
1831 ++i;
1835 // absorb by mana cost
1836 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1837 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1839 next = i; ++next;
1841 // check damage school mask
1842 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1843 continue;
1845 int32 currentAbsorb;
1846 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1847 currentAbsorb = (*i)->GetModifier()->m_amount;
1848 else
1849 currentAbsorb = RemainingDamage;
1851 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1852 if(Player *modOwner = GetSpellModOwner())
1853 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1855 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1856 if (currentAbsorb > maxAbsorb)
1857 currentAbsorb = maxAbsorb;
1859 (*i)->GetModifier()->m_amount -= currentAbsorb;
1860 if((*i)->GetModifier()->m_amount <= 0)
1862 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1863 next = vManaShield.begin();
1866 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1867 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1869 RemainingDamage -= currentAbsorb;
1872 // only split damage if not damaging yourself
1873 if(pVictim != this)
1875 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1876 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1878 next = i; ++next;
1880 // check damage school mask
1881 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1882 continue;
1884 // Damage can be splitted only if aura has an alive caster
1885 Unit *caster = (*i)->GetCaster();
1886 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1887 continue;
1889 int32 currentAbsorb;
1890 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1891 currentAbsorb = (*i)->GetModifier()->m_amount;
1892 else
1893 currentAbsorb = RemainingDamage;
1895 RemainingDamage -= currentAbsorb;
1897 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1899 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1900 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1903 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1904 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1906 next = i; ++next;
1908 // check damage school mask
1909 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1910 continue;
1912 // Damage can be splitted only if aura has an alive caster
1913 Unit *caster = (*i)->GetCaster();
1914 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1915 continue;
1917 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1919 RemainingDamage -= splitted;
1921 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1923 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1924 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1928 *absorb = damage - RemainingDamage - *resist;
1931 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1933 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1934 return;
1936 if (!pVictim->isAlive())
1937 return;
1939 if(IsNonMeleeSpellCasted(false))
1940 return;
1942 uint32 hitInfo;
1943 if (attType == BASE_ATTACK)
1944 hitInfo = HITINFO_NORMALSWING2;
1945 else if (attType == OFF_ATTACK)
1946 hitInfo = HITINFO_LEFTSWING;
1947 else
1948 return; // ignore ranged case
1950 uint32 extraAttacks = m_extraAttacks;
1952 // melee attack spell casted at main hand attack only
1953 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1955 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1957 // not recent extra attack only at any non extra attack (melee spell case)
1958 if(!extra && extraAttacks)
1960 while(m_extraAttacks)
1962 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1963 if(m_extraAttacks > 0)
1964 --m_extraAttacks;
1968 return;
1971 CalcDamageInfo damageInfo;
1972 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1973 // Send log damage message to client
1974 SendAttackStateUpdate(&damageInfo);
1975 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1976 DealMeleeDamage(&damageInfo,true);
1978 if (GetTypeId() == TYPEID_PLAYER)
1979 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1980 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1981 else
1982 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1983 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1985 // extra attack only at any non extra attack (normal case)
1986 if(!extra && extraAttacks)
1988 while(m_extraAttacks)
1990 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1991 if(m_extraAttacks > 0)
1992 --m_extraAttacks;
1997 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
1999 // This is only wrapper
2001 // Miss chance based on melee
2002 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2004 // Critical hit chance
2005 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2007 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2008 float dodge_chance = pVictim->GetUnitDodgeChance();
2009 float block_chance = pVictim->GetUnitBlockChance();
2010 float parry_chance = pVictim->GetUnitParryChance();
2012 // Useful if want to specify crit & miss chances for melee, else it could be removed
2013 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2015 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2018 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2020 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2021 return MELEE_HIT_EVADE;
2023 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2024 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2026 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2027 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2029 // bonus from skills is 0.04%
2030 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2031 int32 sum = 0, tmp = 0;
2032 int32 roll = urand (0, 10000);
2034 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2035 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2036 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2038 tmp = miss_chance;
2040 if (tmp > 0 && roll < (sum += tmp ))
2042 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2043 return MELEE_HIT_MISS;
2046 // always crit against a sitting target (except 0 crit chance)
2047 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2049 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2050 return MELEE_HIT_CRIT;
2053 // Dodge chance
2055 // only players can't dodge if attacker is behind
2056 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2058 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2060 else
2062 // Reduce dodge chance by attacker expertise rating
2063 if (GetTypeId() == TYPEID_PLAYER)
2064 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2066 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2067 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2069 tmp = dodge_chance;
2070 if ( (tmp > 0) // check if unit _can_ dodge
2071 && ((tmp -= skillBonus) > 0)
2072 && roll < (sum += tmp))
2074 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2075 return MELEE_HIT_DODGE;
2079 // parry & block chances
2081 // check if attack comes from behind, nobody can parry or block if attacker is behind
2082 if (!pVictim->HasInArc(M_PI,this))
2084 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2086 else
2088 // Reduce parry chance by attacker expertise rating
2089 if (GetTypeId() == TYPEID_PLAYER)
2090 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2092 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2094 int32 tmp = int32(parry_chance);
2095 if ( (tmp > 0) // check if unit _can_ parry
2096 && ((tmp -= skillBonus) > 0)
2097 && (roll < (sum += tmp)))
2099 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
2100 return MELEE_HIT_PARRY;
2104 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2106 tmp = block_chance;
2107 if ( (tmp > 0) // check if unit _can_ block
2108 && ((tmp -= skillBonus) > 0)
2109 && (roll < (sum += tmp)))
2111 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2112 return MELEE_HIT_BLOCK;
2117 // Critical chance
2118 tmp = crit_chance;
2120 if (tmp > 0 && roll < (sum += tmp))
2122 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2123 return MELEE_HIT_CRIT;
2126 // 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)
2127 if( attType != RANGED_ATTACK &&
2128 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2129 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2130 getLevel() < pVictim->getLevelForTarget(this) )
2132 // cap possible value (with bonuses > max skill)
2133 int32 skill = attackerWeaponSkill;
2134 int32 maxskill = attackerMaxSkillValueForLevel;
2135 skill = (skill > maxskill) ? maxskill : skill;
2137 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2138 tmp = tmp > 4000 ? 4000 : tmp;
2139 if (roll < (sum += tmp))
2141 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2142 return MELEE_HIT_GLANCING;
2146 // mobs can score crushing blows if they're 4 or more levels above victim
2147 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2148 // can be from by creature (if can) or from controlled player that considered as creature
2149 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2150 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2151 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2153 // when their weapon skill is 15 or more above victim's defense skill
2154 tmp = victimDefenseSkill;
2155 int32 tmpmax = victimMaxSkillValueForLevel;
2156 // having defense above your maximum (from items, talents etc.) has no effect
2157 tmp = tmp > tmpmax ? tmpmax : tmp;
2158 // tmp = mob's level * 5 - player's current defense skill
2159 tmp = attackerMaxSkillValueForLevel - tmp;
2160 if(tmp >= 15)
2162 // add 2% chance per lacking skill point, min. is 15%
2163 tmp = tmp * 200 - 1500;
2164 if (roll < (sum += tmp))
2166 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2167 return MELEE_HIT_CRUSHING;
2172 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2173 return MELEE_HIT_NORMAL;
2176 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2178 float min_damage, max_damage;
2180 if (normalized && GetTypeId()==TYPEID_PLAYER)
2181 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2182 else
2184 switch (attType)
2186 case RANGED_ATTACK:
2187 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2188 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2189 break;
2190 case BASE_ATTACK:
2191 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2192 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2193 break;
2194 case OFF_ATTACK:
2195 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2196 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2197 break;
2198 // Just for good manner
2199 default:
2200 min_damage = 0.0f;
2201 max_damage = 0.0f;
2202 break;
2206 if (min_damage > max_damage)
2208 std::swap(min_damage,max_damage);
2211 if(max_damage == 0.0f)
2212 max_damage = 5.0f;
2214 return urand((uint32)min_damage, (uint32)max_damage);
2217 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2219 if(spellProto->spellLevel <= 0)
2220 return 1.0f;
2222 float LvlPenalty = 0.0f;
2224 if(spellProto->spellLevel < 20)
2225 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2226 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2227 if(LvlFactor > 1.0f)
2228 LvlFactor = 1.0f;
2230 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2233 void Unit::SendAttackStart(Unit* pVictim)
2235 WorldPacket data( SMSG_ATTACKSTART, 16 );
2236 data << uint64(GetGUID());
2237 data << uint64(pVictim->GetGUID());
2239 SendMessageToSet(&data, true);
2240 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2243 void Unit::SendAttackStop(Unit* victim)
2245 if(!victim)
2246 return;
2248 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2249 data.append(GetPackGUID());
2250 data.append(victim->GetPackGUID()); // can be 0x00...
2251 data << uint32(0); // can be 0x1
2252 SendMessageToSet(&data, true);
2253 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2255 /*if(victim->GetTypeId() == TYPEID_UNIT)
2256 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2259 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2261 if (pVictim->HasInArc(M_PI,this))
2263 /* Currently not exist spells with ignore block
2264 // Ignore combat result aura (parry/dodge check on prepare)
2265 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2266 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2268 if (!(*i)->isAffectedOnSpell(spellProto))
2269 continue;
2270 if ((*i)->GetModifier()->m_miscvalue == )
2271 return false;
2275 // Check creatures flags_extra for disable block
2276 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2277 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2278 return false;
2280 float blockChance = GetUnitBlockChance();
2281 blockChance += (GetWeaponSkillValue(attackType) - pVictim->GetMaxSkillValueForLevel() )*0.04;
2282 if (roll_chance_f(blockChance))
2283 return true;
2285 return false;
2288 // Melee based spells can be miss, parry or dodge on this step
2289 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2290 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2292 // Calculate hit chance (more correct for chance mod)
2293 int32 HitChance;
2295 // PvP - PvE melee chances
2296 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2297 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2298 if(leveldif < 3)
2299 HitChance = 95 - leveldif;
2300 else
2301 HitChance = 93 - (leveldif - 2) * lchance;
2303 // Hit chance depends from victim auras
2304 if(attType == RANGED_ATTACK)
2305 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2306 else
2307 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2309 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2310 if(Player *modOwner = GetSpellModOwner())
2311 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2313 // Miss = 100 - hit
2314 float miss_chance= 100.0f - HitChance;
2316 // Bonuses from attacker aura and ratings
2317 if (attType == RANGED_ATTACK)
2318 miss_chance -= m_modRangedHitChance;
2319 else
2320 miss_chance -= m_modMeleeHitChance;
2322 // bonus from skills is 0.04%
2323 miss_chance -= skillDiff * 0.04f;
2325 // Limit miss chance from 0 to 60%
2326 if (miss_chance < 0.0f)
2327 return 0.0f;
2328 if (miss_chance > 60.0f)
2329 return 60.0f;
2330 return miss_chance;
2333 // Melee based spells hit result calculations
2334 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2336 WeaponAttackType attType = BASE_ATTACK;
2338 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2339 attType = RANGED_ATTACK;
2341 // bonus from skills is 0.04% per skill Diff
2342 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2343 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2344 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2346 uint32 roll = urand (0, 10000);
2348 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2349 // Roll miss
2350 uint32 tmp = missChance;
2351 if (roll < tmp)
2352 return SPELL_MISS_MISS;
2354 bool canDodge = true;
2355 bool canParry = true;
2357 // Same spells cannot be parry/dodge
2358 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2359 return SPELL_MISS_NONE;
2361 // Ranged attack cannot be parry/dodge
2362 if (attType == RANGED_ATTACK)
2363 return SPELL_MISS_NONE;
2365 // Check for attack from behind
2366 if (!pVictim->HasInArc(M_PI,this))
2368 // Can`t dodge from behind in PvP (but its possible in PvE)
2369 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2370 canDodge = false;
2371 // Can`t parry
2372 canParry = false;
2374 // Check creatures flags_extra for disable parry
2375 if(pVictim->GetTypeId()==TYPEID_UNIT)
2377 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2378 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2379 canParry = false;
2381 // Ignore combat result aura
2382 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2383 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2385 if (!(*i)->isAffectedOnSpell(spell))
2386 continue;
2387 switch((*i)->GetModifier()->m_miscvalue)
2389 case MELEE_HIT_DODGE: canDodge = false; break;
2390 case MELEE_HIT_BLOCK: break; // Block check in hit step
2391 case MELEE_HIT_PARRY: canParry = false; break;
2392 default:
2393 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2394 break;
2398 if (canDodge)
2400 // Roll dodge
2401 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2402 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2403 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2404 // Reduce dodge chance by attacker expertise rating
2405 if (GetTypeId() == TYPEID_PLAYER)
2406 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2407 if (dodgeChance < 0)
2408 dodgeChance = 0;
2410 tmp += dodgeChance;
2411 if (roll < tmp)
2412 return SPELL_MISS_DODGE;
2415 if (canParry)
2417 // Roll parry
2418 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2419 // Reduce parry chance by attacker expertise rating
2420 if (GetTypeId() == TYPEID_PLAYER)
2421 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2422 if (parryChance < 0)
2423 parryChance = 0;
2425 tmp += parryChance;
2426 if (roll < tmp)
2427 return SPELL_MISS_PARRY;
2430 return SPELL_MISS_NONE;
2433 // TODO need use unit spell resistances in calculations
2434 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2436 // Can`t miss on dead target (on skinning for example)
2437 if (!pVictim->isAlive())
2438 return SPELL_MISS_NONE;
2440 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2441 // PvP - PvE spell misschances per leveldif > 2
2442 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2443 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2445 // Base hit chance from attacker and victim levels
2446 int32 modHitChance;
2447 if(leveldif < 3)
2448 modHitChance = 96 - leveldif;
2449 else
2450 modHitChance = 94 - (leveldif - 2) * lchance;
2452 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2453 if(Player *modOwner = GetSpellModOwner())
2454 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2455 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2456 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2457 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2458 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2459 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2460 if (IsAreaOfEffectSpell(spell))
2461 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2462 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2463 if (IsDispelSpell(spell))
2464 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2465 // Chance resist mechanic (select max value from every mechanic spell effect)
2466 int32 resist_mech = 0;
2467 // Get effects mechanic and chance
2468 for(int eff = 0; eff < 3; ++eff)
2470 int32 effect_mech = GetEffectMechanic(spell, eff);
2471 if (effect_mech)
2473 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2474 if (resist_mech < temp)
2475 resist_mech = temp;
2478 // Apply mod
2479 modHitChance-=resist_mech;
2481 // Chance resist debuff
2482 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2484 int32 HitChance = modHitChance * 100;
2485 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2486 HitChance += int32(m_modSpellHitChance*100.0f);
2488 // Decrease hit chance from victim rating bonus
2489 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2490 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2492 if (HitChance < 100) HitChance = 100;
2493 if (HitChance > 9900) HitChance = 9900;
2495 uint32 rand = urand(0,10000);
2496 if (rand > HitChance)
2497 return SPELL_MISS_RESIST;
2498 return SPELL_MISS_NONE;
2501 // Calculate spell hit result can be:
2502 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2503 // For melee based spells:
2504 // Miss
2505 // Dodge
2506 // Parry
2507 // For spells
2508 // Resist
2509 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2511 // Return evade for units in evade mode
2512 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2513 return SPELL_MISS_EVADE;
2515 // Check for immune
2516 if (pVictim->IsImmunedToSpell(spell))
2517 return SPELL_MISS_IMMUNE;
2519 // All positive spells can`t miss
2520 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2521 if (IsPositiveSpell(spell->Id))
2522 return SPELL_MISS_NONE;
2524 // Check for immune
2525 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2526 return SPELL_MISS_IMMUNE;
2528 // Try victim reflect spell
2529 if (CanReflect)
2531 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2532 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2533 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2534 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2535 reflectchance += (*i)->GetModifier()->m_amount;
2536 if (reflectchance > 0 && roll_chance_i(reflectchance))
2538 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2539 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2540 return SPELL_MISS_REFLECT;
2544 switch (spell->DmgClass)
2546 case SPELL_DAMAGE_CLASS_RANGED:
2547 case SPELL_DAMAGE_CLASS_MELEE:
2548 return MeleeSpellHitResult(pVictim, spell);
2549 case SPELL_DAMAGE_CLASS_NONE:
2550 case SPELL_DAMAGE_CLASS_MAGIC:
2551 return MagicSpellHitResult(pVictim, spell);
2553 return SPELL_MISS_NONE;
2556 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2558 if(!pVictim)
2559 return 0.0f;
2561 // Base misschance 5%
2562 float misschance = 5.0f;
2564 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2565 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2567 bool isNormal = false;
2568 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2570 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2572 isNormal = true;
2573 break;
2576 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2578 misschance = 5.0f;
2580 else
2582 misschance = 24.0f;
2586 // PvP : PvE melee misschances per leveldif > 2
2587 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2589 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2590 if(leveldif < 0)
2591 leveldif = 0;
2593 // Hit chance from attacker based on ratings and auras
2594 float m_modHitChance;
2595 if (attType == RANGED_ATTACK)
2596 m_modHitChance = m_modRangedHitChance;
2597 else
2598 m_modHitChance = m_modMeleeHitChance;
2600 if(leveldif < 3)
2601 misschance += (leveldif - m_modHitChance);
2602 else
2603 misschance += ((leveldif - 2) * chance - m_modHitChance);
2605 // Hit chance for victim based on ratings
2606 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2608 if (attType == RANGED_ATTACK)
2609 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2610 else
2611 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2614 // Modify miss chance by victim auras
2615 if(attType == RANGED_ATTACK)
2616 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2617 else
2618 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2620 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2621 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2622 misschance -= skillBonus * 0.04f;
2624 // Limit miss chance from 0 to 60%
2625 if ( misschance < 0.0f)
2626 return 0.0f;
2627 if ( misschance > 60.0f)
2628 return 60.0f;
2630 return misschance;
2633 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2635 if(GetTypeId() == TYPEID_PLAYER)
2637 // in PvP use full skill instead current skill value
2638 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2639 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2640 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2641 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2642 return value;
2644 else
2645 return GetUnitMeleeSkill(target);
2648 float Unit::GetUnitDodgeChance() const
2650 if(hasUnitState(UNIT_STAT_STUNNED))
2651 return 0.0f;
2652 if( GetTypeId() == TYPEID_PLAYER )
2653 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2654 else
2656 if(((Creature const*)this)->isTotem())
2657 return 0.0f;
2658 else
2660 float dodge = 5.0f;
2661 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2662 return dodge > 0.0f ? dodge : 0.0f;
2667 float Unit::GetUnitParryChance() const
2669 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2670 return 0.0f;
2672 float chance = 0.0f;
2674 if(GetTypeId() == TYPEID_PLAYER)
2676 Player const* player = (Player const*)this;
2677 if(player->CanParry() )
2679 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2680 if(!tmpitem)
2681 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2683 if(tmpitem)
2684 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2687 else if(GetTypeId() == TYPEID_UNIT)
2689 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2691 chance = 5.0f;
2692 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2696 return chance > 0.0f ? chance : 0.0f;
2699 float Unit::GetUnitBlockChance() const
2701 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2702 return 0.0f;
2704 if(GetTypeId() == TYPEID_PLAYER)
2706 Player const* player = (Player const*)this;
2707 if(player->CanBlock() )
2709 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2710 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2711 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2713 // is player but has no block ability or no not broken shield equipped
2714 return 0.0f;
2716 else
2718 if(((Creature const*)this)->isTotem())
2719 return 0.0f;
2720 else
2722 float block = 5.0f;
2723 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2724 return block > 0.0f ? block : 0.0f;
2729 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2731 float crit;
2733 if(GetTypeId() == TYPEID_PLAYER)
2735 switch(attackType)
2737 case BASE_ATTACK:
2738 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2739 break;
2740 case OFF_ATTACK:
2741 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2742 break;
2743 case RANGED_ATTACK:
2744 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2745 break;
2746 // Just for good manner
2747 default:
2748 crit = 0.0f;
2749 break;
2752 else
2754 crit = 5.0f;
2755 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2758 // flat aura mods
2759 if(attackType == RANGED_ATTACK)
2760 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2761 else
2762 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2764 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2766 // reduce crit chance from Rating for players
2767 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2769 if (attackType==RANGED_ATTACK)
2770 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2771 else
2772 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2775 // Apply crit chance from defence skill
2776 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2778 if (crit < 0.0f)
2779 crit = 0.0f;
2780 return crit;
2783 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2785 uint32 value = 0;
2786 if(GetTypeId() == TYPEID_PLAYER)
2788 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2790 // feral or unarmed skill only for base attack
2791 if(attType != BASE_ATTACK && !item )
2792 return 0;
2794 if(((Player*)this)->IsInFeralForm())
2795 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2797 // weapon skill or (unarmed for base attack)
2798 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2800 // in PvP use full skill instead current skill value
2801 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2802 ? ((Player*)this)->GetMaxSkillValue(skill)
2803 : ((Player*)this)->GetSkillValue(skill);
2804 // Modify value from ratings
2805 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2806 switch (attType)
2808 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2809 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2810 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2813 else
2814 value = GetUnitMeleeSkill(target);
2815 return value;
2818 void Unit::_UpdateSpells( uint32 time )
2820 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2821 _UpdateAutoRepeatSpell();
2823 // remove finished spells from current pointers
2824 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2826 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2828 m_currentSpells[i]->SetReferencedFromCurrent(false);
2829 m_currentSpells[i] = NULL; // remove pointer
2833 // TODO: Find a better way to prevent crash when multiple auras are removed.
2834 m_removedAuras = 0;
2835 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2836 if ((*i).second)
2837 (*i).second->SetUpdated(false);
2839 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2841 next = i;
2842 ++next;
2843 if ((*i).second)
2845 // prevent double update
2846 if ((*i).second->IsUpdated())
2847 continue;
2848 (*i).second->SetUpdated(true);
2849 (*i).second->Update( time );
2850 // several auras can be deleted due to update
2851 if (m_removedAuras)
2853 if (m_Auras.empty()) break;
2854 next = m_Auras.begin();
2855 m_removedAuras = 0;
2860 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2862 if ((*i).second)
2864 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2866 RemoveAura(i);
2868 else
2870 ++i;
2873 else
2875 ++i;
2879 if(!m_gameObj.empty())
2881 std::list<GameObject*>::iterator ite1, dnext1;
2882 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2884 dnext1 = ite1;
2885 //(*i)->Update( difftime );
2886 if( !(*ite1)->isSpawned() )
2888 (*ite1)->SetOwnerGUID(0);
2889 (*ite1)->SetRespawnTime(0);
2890 (*ite1)->Delete();
2891 dnext1 = m_gameObj.erase(ite1);
2893 else
2894 ++dnext1;
2899 void Unit::_UpdateAutoRepeatSpell()
2901 //check "realtime" interrupts
2902 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2904 // cancel wand shoot
2905 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2906 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2907 m_AutoRepeatFirstCast = true;
2908 return;
2911 //apply delay
2912 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2913 setAttackTimer(RANGED_ATTACK,500);
2914 m_AutoRepeatFirstCast = false;
2916 //castroutine
2917 if (isAttackReady(RANGED_ATTACK))
2919 // Check if able to cast
2920 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CanCast(true))
2922 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2923 return;
2926 // we want to shoot
2927 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2928 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2930 // all went good, reset attack
2931 resetAttackTimer(RANGED_ATTACK);
2935 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2937 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2939 uint32 CSpellType = pSpell->GetCurrentContainer();
2941 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
2943 // break same type spell if it is not delayed
2944 InterruptSpell(CSpellType,false);
2946 // special breakage effects:
2947 switch (CSpellType)
2949 case CURRENT_GENERIC_SPELL:
2951 // generic spells always break channeled not delayed spells
2952 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
2954 // autorepeat breaking
2955 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
2957 // break autorepeat if not Auto Shot
2958 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2959 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2960 m_AutoRepeatFirstCast = true;
2962 } break;
2964 case CURRENT_CHANNELED_SPELL:
2966 // channel spells always break generic non-delayed and any channeled spells
2967 InterruptSpell(CURRENT_GENERIC_SPELL,false);
2968 InterruptSpell(CURRENT_CHANNELED_SPELL);
2970 // it also does break autorepeat if not Auto Shot
2971 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
2972 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
2973 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2974 } break;
2976 case CURRENT_AUTOREPEAT_SPELL:
2978 // only Auto Shoot does not break anything
2979 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2981 // generic autorepeats break generic non-delayed and channeled non-delayed spells
2982 InterruptSpell(CURRENT_GENERIC_SPELL,false);
2983 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
2985 // special action: set first cast flag
2986 m_AutoRepeatFirstCast = true;
2987 } break;
2989 default:
2991 // other spell types don't break anything now
2992 } break;
2995 // current spell (if it is still here) may be safely deleted now
2996 if (m_currentSpells[CSpellType])
2997 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
2999 // set new current spell
3000 m_currentSpells[CSpellType] = pSpell;
3001 pSpell->SetReferencedFromCurrent(true);
3004 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
3006 assert(spellType < CURRENT_MAX_SPELL);
3008 if(m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3010 // send autorepeat cancel message for autorepeat spells
3011 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3013 if(GetTypeId()==TYPEID_PLAYER)
3014 ((Player*)this)->SendAutoRepeatCancel();
3017 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3018 m_currentSpells[spellType]->cancel();
3019 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3020 m_currentSpells[spellType] = NULL;
3024 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3026 // We don't do loop here to explicitly show that melee spell is excluded.
3027 // Maybe later some special spells will be excluded too.
3029 // generic spells are casted when they are not finished and not delayed
3030 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3031 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3032 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3033 return(true);
3035 // channeled spells may be delayed, but they are still considered casted
3036 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3037 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3038 return(true);
3040 // autorepeat spells may be finished or delayed, but they are still considered casted
3041 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3042 return(true);
3044 return(false);
3047 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3049 // generic spells are interrupted if they are not finished or delayed
3050 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3052 if ( (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3053 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3054 m_currentSpells[CURRENT_GENERIC_SPELL]->cancel();
3055 m_currentSpells[CURRENT_GENERIC_SPELL]->SetReferencedFromCurrent(false);
3056 m_currentSpells[CURRENT_GENERIC_SPELL] = NULL;
3059 // autorepeat spells are interrupted if they are not finished or delayed
3060 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3062 // send disable autorepeat packet in any case
3063 if(GetTypeId()==TYPEID_PLAYER)
3064 ((Player*)this)->SendAutoRepeatCancel();
3066 if ( (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3067 (withDelayed || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_DELAYED) )
3068 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->cancel();
3069 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->SetReferencedFromCurrent(false);
3070 m_currentSpells[CURRENT_AUTOREPEAT_SPELL] = NULL;
3073 // channeled spells are interrupted if they are not finished, even if they are delayed
3074 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3076 if (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)
3077 m_currentSpells[CURRENT_CHANNELED_SPELL]->cancel();
3078 m_currentSpells[CURRENT_CHANNELED_SPELL]->SetReferencedFromCurrent(false);
3079 m_currentSpells[CURRENT_CHANNELED_SPELL] = NULL;
3083 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3085 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
3086 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3087 return m_currentSpells[i];
3088 return NULL;
3091 bool Unit::isInFront(Unit const* target, float distance, float arc) const
3093 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
3096 void Unit::SetInFront(Unit const* target)
3098 SetOrientation(GetAngle(target));
3101 bool Unit::isInBack(Unit const* target, float distance, float arc) const
3103 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
3106 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3108 if(IsInWater())
3109 return c->canSwim();
3110 else
3111 return c->canWalk() || c->canFly();
3114 bool Unit::IsInWater() const
3116 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3119 bool Unit::IsUnderWater() const
3121 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3124 void Unit::DeMorph()
3126 SetDisplayId(GetNativeDisplayId());
3129 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3131 int32 modifier = 0;
3133 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3134 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3135 modifier += (*i)->GetModifier()->m_amount;
3137 return modifier;
3140 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3142 float multiplier = 1.0f;
3144 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3145 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3146 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3148 return multiplier;
3151 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3153 int32 modifier = 0;
3155 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3156 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3157 if ((*i)->GetModifier()->m_amount > modifier)
3158 modifier = (*i)->GetModifier()->m_amount;
3160 return modifier;
3163 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3165 int32 modifier = 0;
3167 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3168 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3169 if ((*i)->GetModifier()->m_amount < modifier)
3170 modifier = (*i)->GetModifier()->m_amount;
3172 return modifier;
3175 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3177 int32 modifier = 0;
3179 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3180 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3182 Modifier* mod = (*i)->GetModifier();
3183 if (mod->m_miscvalue & misc_mask)
3184 modifier += mod->m_amount;
3186 return modifier;
3189 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3191 float multiplier = 1.0f;
3193 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3194 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3196 Modifier* mod = (*i)->GetModifier();
3197 if (mod->m_miscvalue & misc_mask)
3198 multiplier *= (100.0f + mod->m_amount)/100.0f;
3200 return multiplier;
3203 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3205 int32 modifier = 0;
3207 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3208 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3210 Modifier* mod = (*i)->GetModifier();
3211 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3212 modifier = mod->m_amount;
3215 return modifier;
3218 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3220 int32 modifier = 0;
3222 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3223 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3225 Modifier* mod = (*i)->GetModifier();
3226 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3227 modifier = mod->m_amount;
3230 return modifier;
3233 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3235 int32 modifier = 0;
3237 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3238 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3240 Modifier* mod = (*i)->GetModifier();
3241 if (mod->m_miscvalue == misc_value)
3242 modifier += mod->m_amount;
3244 return modifier;
3247 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3249 float multiplier = 1.0f;
3251 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3252 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3254 Modifier* mod = (*i)->GetModifier();
3255 if (mod->m_miscvalue == misc_value)
3256 multiplier *= (100.0f + mod->m_amount)/100.0f;
3258 return multiplier;
3261 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3263 int32 modifier = 0;
3265 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3266 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3268 Modifier* mod = (*i)->GetModifier();
3269 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3270 modifier = mod->m_amount;
3273 return modifier;
3276 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3278 int32 modifier = 0;
3280 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3281 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3283 Modifier* mod = (*i)->GetModifier();
3284 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3285 modifier = mod->m_amount;
3288 return modifier;
3291 bool Unit::AddAura(Aura *Aur)
3293 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3294 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3295 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3297 delete Aur;
3298 return false;
3301 if(Aur->GetTarget() != this)
3303 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3304 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3305 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3306 delete Aur;
3307 return false;
3310 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3312 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3313 AuraMap::iterator i = m_Auras.find( spair );
3315 // take out same spell
3316 if (i != m_Auras.end())
3318 // passive and persistent auras can stack with themselves any number of times
3319 if (!Aur->IsPassive() && !Aur->IsPersistent())
3321 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3323 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3325 // Aura can stack on self -> Stack it;
3326 if(aurSpellInfo->StackAmount)
3328 i2->second->modStackAmount(1);
3329 delete Aur;
3330 return false;
3332 // can be only single (this check done at _each_ aura add
3333 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3334 break;
3337 bool stop = false;
3338 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3340 // DoT/HoT/etc
3341 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3342 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3343 case SPELL_AURA_PERIODIC_LEECH:
3344 case SPELL_AURA_PERIODIC_HEAL:
3345 case SPELL_AURA_OBS_MOD_HEALTH:
3346 case SPELL_AURA_PERIODIC_MANA_LEECH:
3347 case SPELL_AURA_PERIODIC_ENERGIZE:
3348 case SPELL_AURA_OBS_MOD_MANA:
3349 case SPELL_AURA_POWER_BURN_MANA:
3350 break;
3351 default: // not allow
3352 // can be only single (this check done at _each_ aura add
3353 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3354 stop = true;
3355 break;
3358 if(stop)
3359 break;
3364 // passive auras not stacable with other ranks
3365 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3367 if (!RemoveNoStackAurasDueToAura(Aur))
3369 delete Aur;
3370 return false; // couldn't remove conflicting aura with higher rank
3374 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3375 if (IsSingleTargetSpell(aurSpellInfo) && Aur->GetTarget())
3377 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3378 for(;;)
3380 Unit* caster = Aur->GetCaster();
3381 if(!caster) // caster deleted and not required adding scAura
3382 break;
3384 bool restart = false;
3385 AuraList& scAuras = caster->GetSingleCastAuras();
3386 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3388 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3389 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3391 if ((*itr)->IsInUse())
3393 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());
3394 continue;
3396 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3397 restart = true;
3398 break;
3402 if(!restart)
3404 // done
3405 scAuras.push_back(Aur);
3406 break;
3411 // add aura, register in lists and arrays
3412 Aur->_AddAura();
3413 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3414 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3416 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3419 Aur->ApplyModifier(true,true);
3420 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3421 return true;
3424 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3426 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3427 if(!spellInfo)
3428 return;
3429 AuraMap::iterator i,next;
3430 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3432 next = i;
3433 ++next;
3434 uint32 i_spellId = (*i).second->GetId();
3435 if((*i).second && i_spellId && i_spellId != spellId)
3437 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3439 RemoveAurasDueToSpell(i_spellId);
3441 if( m_Auras.empty() )
3442 break;
3443 else
3444 next = m_Auras.begin();
3450 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3452 if (!Aur)
3453 return false;
3455 SpellEntry const* spellProto = Aur->GetSpellProto();
3456 if (!spellProto)
3457 return false;
3459 uint32 spellId = Aur->GetId();
3461 // passive spell special case (only non stackable with ranks)
3462 if(IsPassiveSpell(spellId))
3464 if(IsPassiveSpellStackableWithRanks(spellProto))
3465 return true;
3468 uint32 effIndex = Aur->GetEffIndex();
3470 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3472 AuraMap::iterator i,next;
3473 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3475 next = i;
3476 ++next;
3477 if (!(*i).second) continue;
3479 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3481 if (!i_spellProto)
3482 continue;
3484 uint32 i_spellId = i_spellProto->Id;
3486 // early checks that spellId is passive non stackable spell
3487 if(IsPassiveSpell(i_spellId))
3489 // passive non-stackable spells not stackable only for same caster
3490 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3491 continue;
3493 // passive non-stackable spells not stackable only with another rank of same spell
3494 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3495 continue;
3498 uint32 i_effIndex = (*i).second->GetEffIndex();
3500 if(i_spellId == spellId) continue;
3502 bool is_triggered_by_spell = false;
3503 // prevent triggered aura of removing aura that triggered it
3504 for(int j = 0; j < 3; ++j)
3505 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3506 is_triggered_by_spell = true;
3507 if (is_triggered_by_spell) continue;
3509 for(int j = 0; j < 3; ++j)
3511 // prevent remove dummy triggered spells at next effect aura add
3512 switch(spellProto->Effect[j]) // main spell auras added added after triggered spell
3514 case SPELL_EFFECT_DUMMY:
3515 switch(spellId)
3517 case 5420: if(i_spellId==34123) is_triggered_by_spell = true; break;
3519 break;
3522 if(is_triggered_by_spell)
3523 break;
3525 // prevent remove form main spell by triggered passive spells
3526 switch(i_spellProto->EffectApplyAuraName[j]) // main aura added before triggered spell
3528 case SPELL_AURA_MOD_SHAPESHIFT:
3529 switch(i_spellId)
3531 case 24858: if(spellId==24905) is_triggered_by_spell = true; break;
3532 case 33891: if(spellId==5420 || spellId==34123) is_triggered_by_spell = true; break;
3533 case 34551: if(spellId==22688) is_triggered_by_spell = true; break;
3535 break;
3539 if(!is_triggered_by_spell)
3541 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3543 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3545 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3547 // cannot remove higher rank
3548 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3549 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3550 return false;
3552 // Its a parent aura (create this aura in ApplyModifier)
3553 if ((*i).second->IsInUse())
3555 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());
3556 continue;
3558 RemoveAurasDueToSpell(i_spellId);
3560 if( m_Auras.empty() )
3561 break;
3562 else
3563 next = m_Auras.begin();
3565 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3567 // Its a parent aura (create this aura in ApplyModifier)
3568 if ((*i).second->IsInUse())
3570 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());
3571 continue;
3573 RemoveAurasDueToSpell(i_spellId);
3575 if( m_Auras.empty() )
3576 break;
3577 else
3578 next = m_Auras.begin();
3580 // Potions stack aura by aura (elixirs/flask already checked)
3581 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3583 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3585 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3586 return false; // cannot remove higher rank
3588 // Its a parent aura (create this aura in ApplyModifier)
3589 if ((*i).second->IsInUse())
3591 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());
3592 continue;
3594 RemoveAura(i);
3595 next = i;
3600 return true;
3603 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3605 spellEffectPair spair = spellEffectPair(spellId, effindex);
3606 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3608 if(iter->second!=except)
3610 RemoveAura(iter);
3611 iter = m_Auras.lower_bound(spair);
3613 else
3614 ++iter;
3618 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3620 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3622 Aura *aur = iter->second;
3623 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3625 // Custom dispel case
3626 // Unstable Affliction
3627 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3629 int32 damage = aur->GetModifier()->m_amount*9;
3630 uint64 caster_guid = aur->GetCasterGUID();
3632 // Remove aura
3633 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3635 // backfire damage and silence
3636 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3638 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3640 else
3641 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3643 else
3644 ++iter;
3648 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3650 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3652 Aura *aur = iter->second;
3653 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3655 int32 basePoints = aur->GetBasePoints();
3656 // construct the new aura for the attacker
3657 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer);
3658 if(!new_aur)
3659 continue;
3661 // set its duration and maximum duration
3662 // max duration 2 minutes (in msecs)
3663 int32 dur = aur->GetAuraDuration();
3664 const int32 max_dur = 2*MINUTE*1000;
3665 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3666 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3668 // add the new aura to stealer
3669 stealer->AddAura(new_aur);
3671 // Remove aura as dispel
3672 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3674 else
3675 ++iter;
3679 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3681 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3683 if (iter->second->GetId() == spellId)
3684 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3685 else
3686 ++iter;
3690 void Unit::RemoveAurasWithDispelType( DispelType type )
3692 // Create dispel mask by dispel type
3693 uint32 dispelMask = GetDispellMask(type);
3694 // Dispel all existing auras vs current dispel type
3695 AuraMap& auras = GetAuras();
3696 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3698 SpellEntry const* spell = itr->second->GetSpellProto();
3699 if( (1<<spell->Dispel) & dispelMask )
3701 // Dispel aura
3702 RemoveAurasDueToSpell(spell->Id);
3703 itr = auras.begin();
3705 else
3706 ++itr;
3710 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3712 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3713 if(iter != m_Auras.end())
3715 if (iter->second->modStackAmount(-1))
3716 RemoveAura(iter);
3720 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3722 for (int i=0; i<3; ++i)
3723 RemoveSingleAuraFromStack(spellId, i);
3726 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3728 for (int i = 0; i < 3; ++i)
3729 RemoveAura(spellId,i,except);
3732 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3734 for (int k=0; k < 3; ++k)
3736 spellEffectPair spair = spellEffectPair(spellId, k);
3737 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3739 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3741 RemoveAura(iter);
3742 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3744 else
3745 ++iter;
3750 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3752 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3754 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3755 RemoveAura(iter);
3756 else
3757 ++iter;
3761 void Unit::RemoveNotOwnSingleTargetAuras()
3763 // single target auras from other casters
3764 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3766 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3767 RemoveAura(iter);
3768 else
3769 ++iter;
3772 // single target auras at other targets
3773 AuraList& scAuras = GetSingleCastAuras();
3774 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3776 Aura* aura = *iter;
3777 if (aura->GetTarget()!=this)
3779 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3780 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3781 iter = scAuras.begin();
3783 else
3784 ++iter;
3789 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3791 Aura* Aur = i->second;
3792 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3794 Unit* caster = NULL;
3795 if (IsSingleTargetSpell(AurSpellInfo))
3797 caster = Aur->GetCaster();
3798 if(caster)
3800 AuraList& scAuras = caster->GetSingleCastAuras();
3801 scAuras.remove(Aur);
3803 else
3805 sLog.outError("Couldn't find the caster of the single target aura, may crash later!");
3806 assert(false);
3810 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3811 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3813 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3816 // Set remove mode
3817 Aur->SetRemoveMode(mode);
3818 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3819 // remove aura from list before to prevent deleting it before
3820 m_Auras.erase(i);
3821 ++m_removedAuras; // internal count used by unit update
3823 // Statue unsummoned at aura remove
3824 Totem* statue = NULL;
3825 bool caster_channeled = false;
3826 if(IsChanneledSpell(AurSpellInfo))
3828 if(!caster) // can be already located for IsSingleTargetSpell case
3829 caster = Aur->GetCaster();
3831 if(caster)
3833 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3834 statue = ((Totem*)caster);
3835 else
3836 caster_channeled = caster==this;
3840 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3841 Aur->ApplyModifier(false,true);
3842 Aur->_RemoveAura();
3843 delete Aur;
3845 if(caster_channeled)
3846 RemoveAurasAtChanneledTarget (AurSpellInfo);
3848 if(statue)
3849 statue->UnSummon();
3851 // only way correctly remove all auras from list
3852 if( m_Auras.empty() )
3853 i = m_Auras.end();
3854 else
3855 i = m_Auras.begin();
3858 void Unit::RemoveAllAuras()
3860 while (!m_Auras.empty())
3862 AuraMap::iterator iter = m_Auras.begin();
3863 RemoveAura(iter);
3867 void Unit::RemoveArenaAuras(bool onleave)
3869 // in join, remove positive buffs, on end, remove negative
3870 // used to remove positive visible auras in arenas
3871 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3873 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3874 && !iter->second->IsPassive() // don't remove passive auras
3875 && (!(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)
3876 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3877 RemoveAura(iter);
3878 else
3879 ++iter;
3883 void Unit::RemoveAllAurasOnDeath()
3885 // used just after dieing to remove all visible auras
3886 // and disable the mods for the passive ones
3887 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3889 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3890 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3891 else
3892 ++iter;
3896 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3898 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3899 if (iter != m_Auras.end())
3901 if (iter->second->GetAuraDuration() < delaytime)
3902 iter->second->SetAuraDuration(0);
3903 else
3904 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3905 iter->second->SendAuraUpdate(false);
3906 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3910 void Unit::_RemoveAllAuraMods()
3912 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3914 (*i).second->ApplyModifier(false);
3918 void Unit::_ApplyAllAuraMods()
3920 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3922 (*i).second->ApplyModifier(true);
3926 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3928 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3929 if (iter != m_Auras.end())
3930 return iter->second;
3931 return NULL;
3934 bool Unit::HasAura(uint32 spellId) const
3936 for (int i = 0; i < 3 ; ++i)
3938 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3939 if (iter != m_Auras.end())
3940 return true;
3942 return false;
3945 void Unit::AddDynObject(DynamicObject* dynObj)
3947 m_dynObjGUIDs.push_back(dynObj->GetGUID());
3950 void Unit::RemoveDynObject(uint32 spellid)
3952 if(m_dynObjGUIDs.empty())
3953 return;
3954 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3956 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3957 if(!dynObj)
3959 i = m_dynObjGUIDs.erase(i);
3961 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
3963 dynObj->Delete();
3964 i = m_dynObjGUIDs.erase(i);
3966 else
3967 ++i;
3971 void Unit::RemoveAllDynObjects()
3973 while(!m_dynObjGUIDs.empty())
3975 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3976 if(dynObj)
3977 dynObj->Delete();
3978 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
3982 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
3984 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3986 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
3987 if(!dynObj)
3989 i = m_dynObjGUIDs.erase(i);
3990 continue;
3993 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
3994 return dynObj;
3995 ++i;
3997 return NULL;
4000 DynamicObject * Unit::GetDynObject(uint32 spellId)
4002 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4004 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
4005 if(!dynObj)
4007 i = m_dynObjGUIDs.erase(i);
4008 continue;
4011 if (dynObj->GetSpellId() == spellId)
4012 return dynObj;
4013 ++i;
4015 return NULL;
4018 void Unit::AddGameObject(GameObject* gameObj)
4020 assert(gameObj && gameObj->GetOwnerGUID()==0);
4021 m_gameObj.push_back(gameObj);
4022 gameObj->SetOwnerGUID(GetGUID());
4025 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4027 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4029 // GO created by some spell
4030 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4032 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4033 // Need activate spell use for owner
4034 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4035 ((Player*)this)->SendCooldownEvent(createBySpell);
4037 gameObj->SetOwnerGUID(0);
4038 m_gameObj.remove(gameObj);
4039 if(del)
4041 gameObj->SetRespawnTime(0);
4042 gameObj->Delete();
4046 void Unit::RemoveGameObject(uint32 spellid, bool del)
4048 if(m_gameObj.empty())
4049 return;
4050 std::list<GameObject*>::iterator i, next;
4051 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4053 next = i;
4054 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4056 (*i)->SetOwnerGUID(0);
4057 if(del)
4059 (*i)->SetRespawnTime(0);
4060 (*i)->Delete();
4063 next = m_gameObj.erase(i);
4065 else
4066 ++next;
4070 void Unit::RemoveAllGameObjects()
4072 // remove references to unit
4073 for(std::list<GameObject*>::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4075 (*i)->SetOwnerGUID(0);
4076 (*i)->SetRespawnTime(0);
4077 (*i)->Delete();
4078 i = m_gameObj.erase(i);
4082 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4084 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4085 data.append(log->target->GetPackGUID());
4086 data.append(log->attacker->GetPackGUID());
4087 data << uint32(log->SpellID);
4088 data << uint32(log->damage); //damage amount
4089 data << uint32(0);
4090 data << uint8 (log->schoolMask); //damage school
4091 data << uint32(log->absorb); //AbsorbedDamage
4092 data << uint32(log->resist); //resist
4093 data << uint8 (log->phusicalLog); // damsge type? flag
4094 data << uint8 (log->unused); //unused
4095 data << uint32(log->blocked); //blocked
4096 data << uint32(log->HitInfo);
4097 data << uint8 (0); // flag to use extend data
4098 SendMessageToSet( &data, true );
4101 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4103 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
4104 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4105 data.append(target->GetPackGUID());
4106 data.append(GetPackGUID());
4107 data << uint32(SpellID);
4108 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
4109 data << uint32(0); // wotlk
4110 data << uint8(damageSchoolMask); // spell school
4111 data << uint32(AbsorbedDamage); // AbsorbedDamage
4112 data << uint32(Resist); // resist
4113 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
4114 data << uint8(0); // unk isFromAura
4115 data << uint32(Blocked); // blocked
4116 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
4117 data << uint8(0); // isDebug?
4118 SendMessageToSet( &data, true );
4121 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4123 // Not much to do if no flags are set.
4124 if (procAttacker)
4125 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4126 // Now go on with a victim's events'n'auras
4127 // Not much to do if no flags are set or there is no victim
4128 if(pVictim && pVictim->isAlive() && procVictim)
4129 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4132 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4134 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4135 data << uint32(spellID);
4136 data << uint64(GetGUID());
4137 data << uint8(0); // can be 0 or 1
4138 data << uint32(1); // target count
4139 // for(i = 0; i < target count; ++i)
4140 data << uint64(target->GetGUID()); // target GUID
4141 data << uint8(missInfo);
4142 // end loop
4143 SendMessageToSet(&data, true);
4146 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4148 uint32 count = 1;
4149 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4150 data << (uint32)damageInfo->HitInfo;
4151 data.append(GetPackGUID());
4152 data.append(damageInfo->target->GetPackGUID());
4153 data << (uint32)(damageInfo->damage); // Full damage
4154 data << uint32(0); // overkill value
4156 data << (uint8)count; // Sub damage count
4158 for(int i = 0; i < count; ++i)
4160 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4161 data << (float)damageInfo->damage; // sub damage
4162 data << (uint32)damageInfo->damage; // Sub Damage
4165 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4167 for(int i = 0; i < count; ++i)
4168 data << (uint32)damageInfo->absorb; // Absorb
4171 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4173 for(int i = 0; i < count; ++i)
4174 data << (uint32)damageInfo->resist; // Resist
4177 data << (uint8)damageInfo->TargetState;
4178 data << (uint32)0;
4179 data << (uint32)0;
4181 if(damageInfo->HitInfo & HITINFO_BLOCK)
4182 data << (uint32)damageInfo->blocked_amount;
4184 if(damageInfo->HitInfo & HITINFO_UNK3)
4185 data << uint32(0);
4187 if(damageInfo->HitInfo & HITINFO_UNK1)
4189 data << uint32(0);
4190 data << float(0);
4191 data << float(0);
4192 data << float(0);
4193 data << float(0);
4194 data << float(0);
4195 data << float(0);
4196 data << float(0);
4197 data << float(0);
4198 for(uint8 i = 0; i < 5; ++i)
4200 data << float(0);
4201 data << float(0);
4203 data << uint32(0);
4206 SendMessageToSet( &data, true );
4209 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4211 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4213 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4214 data << uint32(HitInfo); // flags
4215 data.append(GetPackGUID());
4216 data.append(target->GetPackGUID());
4217 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4218 data << uint32(0); // overkill value
4220 data << (uint8)SwingType; // count?
4222 // for(i = 0; i < SwingType; ++i)
4223 data << (uint32)damageSchoolMask;
4224 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4225 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4226 // end loop
4228 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4230 // for(i = 0; i < SwingType; ++i)
4231 data << uint32(AbsorbDamage);
4232 // end loop
4235 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4237 // for(i = 0; i < SwingType; ++i)
4238 data << uint32(Resist);
4239 // end loop
4242 data << (uint8)TargetState;
4243 data << (uint32)0;
4244 data << (uint32)0;
4246 if(HitInfo & HITINFO_BLOCK)
4248 data << uint32(BlockedAmount);
4251 if(HitInfo & HITINFO_UNK3)
4253 data << uint32(0);
4256 if(HitInfo & HITINFO_UNK1)
4258 data << uint32(0);
4259 data << float(0);
4260 data << float(0);
4261 data << float(0);
4262 data << float(0);
4263 data << float(0);
4264 data << float(0);
4265 data << float(0);
4266 data << float(0);
4267 for(uint8 i = 0; i < 5; ++i)
4269 data << float(0);
4270 data << float(0);
4272 data << uint32(0);
4275 SendMessageToSet( &data, true );
4278 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4280 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4282 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4283 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4285 uint32 triggered_spell_id = 0;
4286 Unit* target = pVictim;
4287 int32 basepoints0 = 0;
4289 switch(hasteSpell->SpellFamilyName)
4291 case SPELLFAMILY_ROGUE:
4293 switch(hasteSpell->Id)
4295 // Blade Flurry
4296 case 13877:
4297 case 33735:
4299 target = SelectNearbyTarget();
4300 if(!target)
4301 return false;
4302 basepoints0 = damage;
4303 triggered_spell_id = 22482;
4304 break;
4307 break;
4311 // processed charge only counting case
4312 if(!triggered_spell_id)
4313 return true;
4315 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4317 if(!triggerEntry)
4319 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4320 return false;
4323 // default case
4324 if(!target || target!=this && !target->isAlive())
4325 return false;
4327 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4328 return false;
4330 if(basepoints0)
4331 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4332 else
4333 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4335 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4336 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4338 return true;
4341 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4343 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4344 uint32 effIndex = triggeredByAura->GetEffIndex ();
4346 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4347 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4349 uint32 triggered_spell_id = 0;
4350 Unit* target = pVictim;
4351 int32 basepoints0 = 0;
4353 switch(dummySpell->SpellFamilyName)
4355 case SPELLFAMILY_GENERIC:
4357 switch (dummySpell->Id)
4359 // Eye for an Eye
4360 case 9799:
4361 case 25988:
4363 // prevent damage back from weapon special attacks
4364 if (!procSpell || procSpell->DmgClass != SPELL_DAMAGE_CLASS_MAGIC )
4365 return false;
4367 // return damage % to attacker but < 50% own total health
4368 basepoints0 = triggeredByAura->GetModifier()->m_amount*int32(damage)/100;
4369 if(basepoints0 > GetMaxHealth()/2)
4370 basepoints0 = GetMaxHealth()/2;
4372 triggered_spell_id = 25997;
4373 break;
4375 // Sweeping Strikes
4376 case 12328:
4377 case 18765:
4378 case 35429:
4380 // prevent chain of triggered spell from same triggered spell
4381 if(procSpell && procSpell->Id==26654)
4382 return false;
4384 target = SelectNearbyTarget();
4385 if(!target)
4386 return false;
4388 triggered_spell_id = 26654;
4389 break;
4391 // Unstable Power
4392 case 24658:
4394 if (!procSpell || procSpell->Id == 24659)
4395 return false;
4396 // Need remove one 24659 aura
4397 RemoveSingleSpellAurasFromStack(24659);
4398 return true;
4400 // Restless Strength
4401 case 24661:
4403 // Need remove one 24662 aura
4404 RemoveSingleSpellAurasFromStack(24662);
4405 return true;
4407 // Adaptive Warding (Frostfire Regalia set)
4408 case 28764:
4410 if(!procSpell)
4411 return false;
4413 // find Mage Armor
4414 bool found = false;
4415 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4416 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4418 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4420 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4422 found=true;
4423 break;
4427 if(!found)
4428 return false;
4430 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4432 case SPELL_SCHOOL_NORMAL:
4433 case SPELL_SCHOOL_HOLY:
4434 return false; // ignored
4435 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4436 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4437 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4438 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4439 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4440 default:
4441 return false;
4444 target = this;
4445 break;
4447 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4448 case 27539:
4450 if(!procSpell)
4451 return false;
4453 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4455 case SPELL_SCHOOL_NORMAL:
4456 return false; // ignore
4457 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4458 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4459 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4460 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4461 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4462 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4463 default:
4464 return false;
4467 target = this;
4468 break;
4470 // Mana Leech (Passive) (Priest Pet Aura)
4471 case 28305:
4473 // Cast on owner
4474 target = GetOwner();
4475 if(!target)
4476 return false;
4478 basepoints0 = int32(damage * 2.5f); // manaregen
4479 triggered_spell_id = 34650;
4480 break;
4482 // Mark of Malice
4483 case 33493:
4485 // Cast finish spell at last charge
4486 if (triggeredByAura->GetAuraCharges() > 1)
4487 return false;
4489 target = this;
4490 triggered_spell_id = 33494;
4491 break;
4493 // Twisted Reflection (boss spell)
4494 case 21063:
4495 triggered_spell_id = 21064;
4496 break;
4497 // Vampiric Aura (boss spell)
4498 case 38196:
4500 basepoints0 = 3 * damage; // 300%
4501 if (basepoints0 < 0)
4502 return false;
4504 triggered_spell_id = 31285;
4505 target = this;
4506 break;
4508 // Aura of Madness (Darkmoon Card: Madness trinket)
4509 //=====================================================
4510 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4511 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4512 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4513 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4514 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4515 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4516 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4517 // 41011 Martyr Complex: +35 stamina (All classes)
4518 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4519 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4520 case 39446:
4522 if(GetTypeId() != TYPEID_PLAYER)
4523 return false;
4525 // Select class defined buff
4526 switch (getClass())
4528 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4529 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4531 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4532 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4533 break;
4535 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4536 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4538 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4539 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4540 break;
4542 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4543 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4544 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4545 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4547 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4548 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4549 break;
4551 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4553 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4554 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4555 break;
4557 default:
4558 return false;
4561 target = this;
4562 if (roll_chance_i(10))
4563 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4564 break;
4567 // TODO: need find item for aura and triggered spells
4568 // Sunwell Exalted Caster Neck (??? neck)
4569 // cast ??? Light's Wrath if Exalted by Aldor
4570 // cast ??? Arcane Bolt if Exalted by Scryers*/
4571 case 46569:
4572 return false; // disable for while
4575 if(GetTypeId() != TYPEID_PLAYER)
4576 return false;
4578 // Get Aldor reputation rank
4579 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4581 target = this;
4582 triggered_spell_id = ???
4583 break;
4585 // Get Scryers reputation rank
4586 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4588 triggered_spell_id = ???
4589 break;
4591 return false;
4592 }/**/
4593 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4594 // cast 45479 Light's Wrath if Exalted by Aldor
4595 // cast 45429 Arcane Bolt if Exalted by Scryers
4596 case 45481:
4598 if(GetTypeId() != TYPEID_PLAYER)
4599 return false;
4601 // Get Aldor reputation rank
4602 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4604 target = this;
4605 triggered_spell_id = 45479;
4606 break;
4608 // Get Scryers reputation rank
4609 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4611 triggered_spell_id = 45429;
4612 break;
4614 return false;
4616 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4617 // cast 45480 Light's Strength if Exalted by Aldor
4618 // cast 45428 Arcane Strike if Exalted by Scryers
4619 case 45482:
4621 if(GetTypeId() != TYPEID_PLAYER)
4622 return false;
4624 // Get Aldor reputation rank
4625 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4627 target = this;
4628 triggered_spell_id = 45480;
4629 break;
4631 // Get Scryers reputation rank
4632 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4634 triggered_spell_id = 45428;
4635 break;
4637 return false;
4639 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4640 // cast 45431 Arcane Insight if Exalted by Aldor
4641 // cast 45432 Light's Ward if Exalted by Scryers
4642 case 45483:
4644 if(GetTypeId() != TYPEID_PLAYER)
4645 return false;
4647 // Get Aldor reputation rank
4648 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4650 target = this;
4651 triggered_spell_id = 45432;
4652 break;
4654 // Get Scryers reputation rank
4655 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4657 target = this;
4658 triggered_spell_id = 45431;
4659 break;
4661 return false;
4663 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4664 // cast 45478 Light's Salvation if Exalted by Aldor
4665 // cast 45430 Arcane Surge if Exalted by Scryers
4666 case 45484:
4668 if(GetTypeId() != TYPEID_PLAYER)
4669 return false;
4671 // Get Aldor reputation rank
4672 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4674 target = this;
4675 triggered_spell_id = 45478;
4676 break;
4678 // Get Scryers reputation rank
4679 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4681 triggered_spell_id = 45430;
4682 break;
4684 return false;
4686 // Living Seed
4687 case 48504:
4689 triggered_spell_id = 48503;
4690 basepoints0 = triggeredByAura->GetModifier()->m_amount;
4691 target = this;
4692 break;
4694 // Vampiric Touch (generic, used by some boss)
4695 case 52723:
4696 case 60501:
4698 triggered_spell_id = 52724;
4699 basepoints0 = damage / 2;
4700 target = this;
4701 break;
4703 // Divine purpose
4704 case 31871:
4705 case 31872:
4707 // Roll chane
4708 if (!roll_chance_i(triggeredByAura->GetModifier()->m_amount))
4709 return false;
4711 // Remove any stun effect on target
4712 AuraMap& Auras = pVictim->GetAuras();
4713 for(AuraMap::iterator iter = Auras.begin(); iter != Auras.end();)
4715 SpellEntry const *spell = iter->second->GetSpellProto();
4716 if( spell->Mechanic == MECHANIC_STUN ||
4717 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4719 pVictim->RemoveAurasDueToSpell(spell->Id);
4720 iter = Auras.begin();
4722 else
4723 ++iter;
4725 return true;
4728 break;
4730 case SPELLFAMILY_MAGE:
4732 // Magic Absorption
4733 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4735 if (getPowerType() != POWER_MANA)
4736 return false;
4738 // mana reward
4739 basepoints0 = (triggeredByAura->GetModifier()->m_amount * GetMaxPower(POWER_MANA) / 100);
4740 target = this;
4741 triggered_spell_id = 29442;
4742 break;
4744 // Master of Elements
4745 if (dummySpell->SpellIconID == 1920)
4747 if(!procSpell)
4748 return false;
4750 // mana cost save
4751 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4752 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
4753 if( basepoints0 <=0 )
4754 return false;
4756 target = this;
4757 triggered_spell_id = 29077;
4758 break;
4760 // Hot Streak
4761 if (dummySpell->SpellIconID == 2999)
4763 if (triggeredByAura->GetEffIndex()!=0)
4764 return true;
4765 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4766 if (!counter)
4767 return true;
4769 // Count spell criticals in a row in second aura
4770 Modifier *mod = counter->GetModifier();
4771 if (procEx & PROC_EX_CRITICAL_HIT)
4773 mod->m_amount *=2;
4774 if (mod->m_amount < 100) // not enough
4775 return true;
4776 // Crititcal counted -> roll chance
4777 if (roll_chance_i(triggeredByAura->GetModifier()->m_amount))
4778 CastSpell(this, 48108, true, castItem, triggeredByAura);
4780 mod->m_amount = 25;
4781 return true;
4783 // Burnout
4784 if (dummySpell->SpellIconID == 2998)
4786 if(!procSpell)
4787 return false;
4789 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4790 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
4791 if( basepoints0 <=0 )
4792 return false;
4793 triggered_spell_id = 44450;
4794 target = this;
4795 break;
4797 // Incanter's Regalia set (add trigger chance to Mana Shield)
4798 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4800 if(GetTypeId() != TYPEID_PLAYER)
4801 return false;
4803 target = this;
4804 triggered_spell_id = 37436;
4805 break;
4807 switch(dummySpell->Id)
4809 // Ignite
4810 case 11119:
4811 case 11120:
4812 case 12846:
4813 case 12847:
4814 case 12848:
4816 switch (dummySpell->Id)
4818 case 11119: basepoints0 = int32(0.04f*damage); break;
4819 case 11120: basepoints0 = int32(0.08f*damage); break;
4820 case 12846: basepoints0 = int32(0.12f*damage); break;
4821 case 12847: basepoints0 = int32(0.16f*damage); break;
4822 case 12848: basepoints0 = int32(0.20f*damage); break;
4823 default:
4824 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4825 return false;
4828 triggered_spell_id = 12654;
4829 break;
4831 // Combustion
4832 case 11129:
4834 //last charge and crit
4835 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4837 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4838 return true; // charge counting (will removed)
4841 CastSpell(this, 28682, true, castItem, triggeredByAura);
4842 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4845 break;
4847 case SPELLFAMILY_WARRIOR:
4849 // Retaliation
4850 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4852 // check attack comes not from behind
4853 if (!HasInArc(M_PI, pVictim))
4854 return false;
4856 triggered_spell_id = 22858;
4857 break;
4859 // Second Wind
4860 if (dummySpell->SpellIconID == 1697)
4862 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4863 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4864 return false;
4865 // Need stun or root mechanic
4866 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
4867 return false;
4869 switch (dummySpell->Id)
4871 case 29838: triggered_spell_id=29842; break;
4872 case 29834: triggered_spell_id=29841; break;
4873 case 42770: triggered_spell_id=42771; break;
4874 default:
4875 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4876 return false;
4879 target = this;
4880 break;
4882 // Damage Shield
4883 if (dummySpell->SpellIconID == 3214)
4885 triggered_spell_id = 59653;
4886 basepoints0 = GetShieldBlockValue() * triggeredByAura->GetModifier()->m_amount / 100;
4887 break;
4889 break;
4891 case SPELLFAMILY_WARLOCK:
4893 // Seed of Corruption
4894 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4896 Modifier* mod = triggeredByAura->GetModifier();
4897 // if damage is more than need or target die from damage deal finish spell
4898 if( mod->m_amount <= damage || GetHealth() <= damage )
4900 // remember guid before aura delete
4901 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4903 // Remove aura (before cast for prevent infinite loop handlers)
4904 RemoveAurasDueToSpell(triggeredByAura->GetId());
4906 // Cast finish spell (triggeredByAura already not exist!)
4907 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4908 return true; // no hidden cooldown
4911 // Damage counting
4912 mod->m_amount-=damage;
4913 return true;
4915 // Seed of Corruption (Mobs cast) - no die req
4916 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4918 Modifier* mod = triggeredByAura->GetModifier();
4919 // if damage is more than need deal finish spell
4920 if( mod->m_amount <= damage )
4922 // remember guid before aura delete
4923 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4925 // Remove aura (before cast for prevent infinite loop handlers)
4926 RemoveAurasDueToSpell(triggeredByAura->GetId());
4928 // Cast finish spell (triggeredByAura already not exist!)
4929 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
4930 return true; // no hidden cooldown
4932 // Damage counting
4933 mod->m_amount-=damage;
4934 return true;
4936 // Fel Synergy
4937 if (dummySpell->SpellIconID == 3222)
4939 target = GetPet();
4940 if (!target)
4941 return false;
4942 triggered_spell_id = 54181;
4943 basepoints0 = damage * triggeredByAura->GetModifier()->m_amount / 100;
4944 break;
4946 switch(dummySpell->Id)
4948 // Nightfall
4949 case 18094:
4950 case 18095:
4952 target = this;
4953 triggered_spell_id = 17941;
4954 break;
4956 //Soul Leech
4957 case 30293:
4958 case 30295:
4959 case 30296:
4961 // health
4962 basepoints0 = int32(damage*triggeredByAura->GetModifier()->m_amount/100);
4963 target = this;
4964 triggered_spell_id = 30294;
4965 break;
4967 // Shadowflame (Voidheart Raiment set bonus)
4968 case 37377:
4970 triggered_spell_id = 37379;
4971 break;
4973 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
4974 case 37381:
4976 target = GetPet();
4977 if(!target)
4978 return false;
4980 // heal amount
4981 basepoints0 = damage * triggeredByAura->GetModifier()->m_amount/100;
4982 triggered_spell_id = 37382;
4983 break;
4985 // Shadowflame Hellfire (Voidheart Raiment set bonus)
4986 case 39437:
4988 triggered_spell_id = 37378;
4989 break;
4992 break;
4994 case SPELLFAMILY_PRIEST:
4996 // Vampiric Touch
4997 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
4999 if(!pVictim || !pVictim->isAlive())
5000 return false;
5002 // pVictim is caster of aura
5003 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5004 return false;
5006 // energize amount
5007 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5008 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5009 return true; // no hidden cooldown
5011 // Divine Aegis
5012 if (dummySpell->SpellIconID == 2820)
5014 basepoints0 = damage * triggeredByAura->GetModifier()->m_amount/100;
5015 triggered_spell_id = 47753;
5016 break;
5018 switch(dummySpell->Id)
5020 // Vampiric Embrace
5021 case 15286:
5023 if(!pVictim || !pVictim->isAlive())
5024 return false;
5026 // pVictim is caster of aura
5027 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5028 return false;
5030 // heal amount
5031 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5032 pVictim->CastCustomSpell(pVictim,15290,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5033 return true; // no hidden cooldown
5035 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5036 case 40438:
5038 // Shadow Word: Pain
5039 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
5040 triggered_spell_id = 40441;
5041 // Renew
5042 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5043 triggered_spell_id = 40440;
5044 else
5045 return false;
5047 target = this;
5048 break;
5050 // Oracle Healing Bonus ("Garments of the Oracle" set)
5051 case 26169:
5053 // heal amount
5054 basepoints0 = int32(damage * 10/100);
5055 target = this;
5056 triggered_spell_id = 26170;
5057 break;
5059 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5060 case 39372:
5062 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5063 return false;
5065 // heal amount
5066 basepoints0 = damage * triggeredByAura->GetModifier()->m_amount/100;
5067 target = this;
5068 triggered_spell_id = 39373;
5069 break;
5071 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5072 case 28809:
5074 triggered_spell_id = 28810;
5075 break;
5078 break;
5080 case SPELLFAMILY_DRUID:
5082 switch(dummySpell->Id)
5084 // Healing Touch (Dreamwalker Raiment set)
5085 case 28719:
5087 // mana back
5088 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5089 target = this;
5090 triggered_spell_id = 28742;
5091 break;
5093 // Healing Touch Refund (Idol of Longevity trinket)
5094 case 28847:
5096 target = this;
5097 triggered_spell_id = 28848;
5098 break;
5100 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5101 case 37288:
5102 case 37295:
5104 target = this;
5105 triggered_spell_id = 37238;
5106 break;
5108 // Druid Tier 6 Trinket
5109 case 40442:
5111 float chance;
5113 // Starfire
5114 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
5116 triggered_spell_id = 40445;
5117 chance = 25.f;
5119 // Rejuvenation
5120 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5122 triggered_spell_id = 40446;
5123 chance = 25.f;
5125 // Mangle (cat/bear)
5126 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
5128 triggered_spell_id = 40452;
5129 chance = 40.f;
5131 else
5132 return false;
5134 if (!roll_chance_f(chance))
5135 return false;
5137 target = this;
5138 break;
5140 // Maim Interrupt
5141 case 44835:
5143 // Deadly Interrupt Effect
5144 triggered_spell_id = 32747;
5145 break;
5148 // Eclipse
5149 if (dummySpell->SpellIconID == 2856)
5151 if (!procSpell)
5152 return false;
5153 // Only 0 aura can proc
5154 if (triggeredByAura->GetEffIndex()!=0)
5155 return true;
5156 // Wrath crit
5157 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5159 if (!roll_chance_i(60))
5160 return false;
5161 triggered_spell_id = 48518;
5162 target = this;
5163 break;
5165 // Starfire crit
5166 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
5168 triggered_spell_id = 48517;
5169 target = this;
5170 break;
5172 return false;
5174 // Living Seed
5175 else if (dummySpell->SpellIconID == 2860)
5177 triggered_spell_id = 48504;
5178 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5179 break;
5181 break;
5183 case SPELLFAMILY_ROGUE:
5185 switch(dummySpell->Id)
5187 // Deadly Throw Interrupt
5188 case 32748:
5190 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5191 if(this == pVictim)
5192 return false;
5194 triggered_spell_id = 32747;
5195 break;
5198 // Cut to the Chase
5199 if( dummySpell->SpellIconID == 2909 )
5201 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5202 // lookup Slice and Dice
5203 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5204 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5206 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5207 if( spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5208 spellProto->SpellFamilyFlags & 0x0000000000040000LL)
5210 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5211 (*itr)->RefreshAura();
5212 return true;
5215 return false;
5217 // Deadly Brew
5218 if( dummySpell->SpellIconID == 2963 )
5220 triggered_spell_id = 25809;
5221 break;
5223 // Quick Recovery
5224 if( dummySpell->SpellIconID == 2116 )
5226 if(!procSpell)
5227 return false;
5229 // energy cost save
5230 basepoints0 = procSpell->manaCost * triggeredByAura->GetModifier()->m_amount/100;
5231 if(basepoints0 <= 0)
5232 return false;
5234 target = this;
5235 triggered_spell_id = 31663;
5236 break;
5238 break;
5240 case SPELLFAMILY_HUNTER:
5242 // Thrill of the Hunt
5243 if ( dummySpell->SpellIconID == 2236 )
5245 if(!procSpell)
5246 return false;
5248 // mana cost save
5249 basepoints0 = procSpell->manaCost * 40/100;
5250 if(basepoints0 <= 0)
5251 return false;
5253 target = this;
5254 triggered_spell_id = 34720;
5255 break;
5257 // Hunting Party
5258 if ( dummySpell->SpellIconID == 3406 )
5260 triggered_spell_id = 57669;
5261 target = this;
5262 return true;
5264 // Lock and Load
5265 if ( dummySpell->SpellIconID == 3579 )
5267 // Proc only from periodic (from trap activation proc another aura of this spell)
5268 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC))
5269 return false;
5270 if (!roll_chance_i(triggeredByAura->GetModifier()->m_amount))
5271 return false;
5272 triggered_spell_id = 56453;
5273 target = this;
5274 break;
5276 // Rapid Recuperation
5277 if ( dummySpell->SpellIconID == 3560 )
5279 // mane regen from Rapid Killing
5280 triggered_spell_id = 56654;
5281 target = this;
5282 break;
5284 break;
5286 case SPELLFAMILY_PALADIN:
5288 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5289 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && triggeredByAura->GetEffIndex()==0)
5291 triggered_spell_id = 25742;
5292 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5293 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5294 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5295 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5296 break;
5298 // Sacred Shield
5299 if (dummySpell->SpellFamilyFlags&0x0008000000000000LL)
5301 triggered_spell_id = 58597;
5302 target = this;
5303 break;
5305 switch(dummySpell->Id)
5307 // Judgement of Light
5308 case 20185:
5310 // Get judgement caster
5311 Unit *caster = triggeredByAura->GetCaster();
5312 if (!caster)
5313 return false;
5314 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5315 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5316 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5317 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5318 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
5319 return true;
5321 // Judgement of Wisdom
5322 case 20186:
5324 if (pVictim->getPowerType() == POWER_MANA)
5325 pVictim->CastSpell(pVictim, 20268, true, 0, triggeredByAura);
5326 return true;
5328 // Holy Power (Redemption Armor set)
5329 case 28789:
5331 if(!pVictim)
5332 return false;
5334 // Set class defined buff
5335 switch (pVictim->getClass())
5337 case CLASS_PALADIN:
5338 case CLASS_PRIEST:
5339 case CLASS_SHAMAN:
5340 case CLASS_DRUID:
5341 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5342 break;
5343 case CLASS_MAGE:
5344 case CLASS_WARLOCK:
5345 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5346 break;
5347 case CLASS_HUNTER:
5348 case CLASS_ROGUE:
5349 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5350 break;
5351 case CLASS_WARRIOR:
5352 triggered_spell_id = 28790; // Increases the friendly target's armor
5353 break;
5354 default:
5355 return false;
5357 break;
5359 // Seal of Vengeance (damage calc on apply aura)
5360 case 31801:
5362 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5363 return false;
5365 triggered_spell_id = 31803;
5366 break;
5368 // Spiritual Attunement
5369 case 31785:
5370 case 33776:
5372 // if healed by another unit (pVictim)
5373 if(this == pVictim)
5374 return false;
5376 // heal amount
5377 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5378 target = this;
5379 triggered_spell_id = 31786;
5380 break;
5382 // Seal of Blood do damage trigger
5383 case 31892:
5385 if (triggeredByAura->GetEffIndex() == 0) // 0 effect - is proc on enemy
5386 triggered_spell_id = 31893;
5387 else if (triggeredByAura->GetEffIndex() == 1) // 1 effect - is proc on self
5389 // add spell damage from prev effect (27%)
5390 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5391 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5392 target = this;
5393 triggered_spell_id = 32221;
5395 else
5396 return true;
5397 break;
5399 // Seal of the Martyr do damage trigger
5400 case 53720:
5402 if (triggeredByAura->GetEffIndex() == 0) // 0 effect - is proc on enemy
5403 triggered_spell_id = 53719;
5404 else if (triggeredByAura->GetEffIndex() == 1) // 1 effect - is proc on self
5406 // add spell damage from prev effect (27%)
5407 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5408 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5409 target = this;
5410 triggered_spell_id = 53718;
5412 else
5413 return true;
5414 break;
5416 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5417 case 40470:
5419 if( !procSpell )
5420 return false;
5422 float chance;
5424 // Flash of light/Holy light
5425 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5427 triggered_spell_id = 40471;
5428 chance = 15.f;
5430 // Judgement
5431 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5433 triggered_spell_id = 40472;
5434 chance = 50.f;
5436 else
5437 return false;
5439 if (!roll_chance_f(chance))
5440 return false;
5442 break;
5444 // Glyph of Divinity
5445 case 54939:
5447 // Lookup base amount mana restore
5448 for (int i=0; i<3;i++)
5449 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5451 int32 mana = procSpell->EffectBasePoints[i];
5452 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5453 break;
5455 return true;
5457 // Glyph of Flash of Light
5458 case 54936:
5460 triggered_spell_id = 54957;
5461 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5462 break;
5464 // Glyph of Holy Light
5465 case 54937:
5467 triggered_spell_id = 54968;
5468 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5469 break;
5472 break;
5474 case SPELLFAMILY_SHAMAN:
5476 switch(dummySpell->Id)
5478 // Totemic Power (The Earthshatterer set)
5479 case 28823:
5481 if( !pVictim )
5482 return false;
5484 // Set class defined buff
5485 switch (pVictim->getClass())
5487 case CLASS_PALADIN:
5488 case CLASS_PRIEST:
5489 case CLASS_SHAMAN:
5490 case CLASS_DRUID:
5491 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5492 break;
5493 case CLASS_MAGE:
5494 case CLASS_WARLOCK:
5495 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5496 break;
5497 case CLASS_HUNTER:
5498 case CLASS_ROGUE:
5499 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5500 break;
5501 case CLASS_WARRIOR:
5502 triggered_spell_id = 28827; // Increases the friendly target's armor
5503 break;
5504 default:
5505 return false;
5507 break;
5509 // Lesser Healing Wave (Totem of Flowing Water Relic)
5510 case 28849:
5512 target = this;
5513 triggered_spell_id = 28850;
5514 break;
5516 // Windfury Weapon (Passive) 1-5 Ranks
5517 case 33757:
5519 if(GetTypeId()!=TYPEID_PLAYER)
5520 return false;
5522 if(!castItem || !castItem->IsEquipped())
5523 return false;
5525 // custom cooldown processing case
5526 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5527 return false;
5529 // Now amount of extra power stored in 1 effect of Enchant spell
5530 // Get it by item enchant id
5531 uint32 spellId;
5532 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5534 case 283: spellId = 8232; break; // 1 Rank
5535 case 284: spellId = 8235; break; // 2 Rank
5536 case 525: spellId = 10486; break; // 3 Rank
5537 case 1669:spellId = 16362; break; // 4 Rank
5538 case 2636:spellId = 25505; break; // 5 Rank
5539 case 3785:spellId = 58801; break; // 6 Rank
5540 case 3786:spellId = 58803; break; // 7 Rank
5541 case 3787:spellId = 58804; break; // 8 Rank
5542 default:
5544 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5545 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5546 return false;
5550 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5551 if(!windfurySpellEntry)
5553 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5554 return false;
5557 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
5559 // Off-Hand case
5560 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5562 // Value gained from additional AP
5563 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5564 triggered_spell_id = 33750;
5566 // Main-Hand case
5567 else
5569 // Value gained from additional AP
5570 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5571 triggered_spell_id = 25504;
5574 // apply cooldown before cast to prevent processing itself
5575 if( cooldown )
5576 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5578 // Attack Twice
5579 for ( uint32 i = 0; i<2; ++i )
5580 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5582 return true;
5584 // Shaman Tier 6 Trinket
5585 case 40463:
5587 if( !procSpell )
5588 return false;
5590 float chance;
5591 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5593 triggered_spell_id = 40465; // Lightning Bolt
5594 chance = 15.f;
5596 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5598 triggered_spell_id = 40465; // Lesser Healing Wave
5599 chance = 10.f;
5601 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5603 triggered_spell_id = 40466; // Stormstrike
5604 chance = 50.f;
5606 else
5607 return false;
5609 if (!roll_chance_f(chance))
5610 return false;
5612 target = this;
5613 break;
5615 // Glyph of Healing Wave
5616 case 55440:
5618 // Not proc from self heals
5619 if (this==pVictim)
5620 return false;
5621 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5622 target = this;
5623 triggered_spell_id = 55533;
5624 break;
5626 // Spirit Hunt
5627 case 58877:
5629 // Cast on owner
5630 target = GetOwner();
5631 if(!target)
5632 return false;
5633 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5634 triggered_spell_id = 58879;
5635 break;
5638 // Ancestral Awakening
5639 if (dummySpell->SpellIconID == 2018)
5641 // TODO: frite dummy fot triggered spell
5642 triggered_spell_id = 52759;
5643 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5644 target = this;
5645 break;
5647 // Earth Shield
5648 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5650 basepoints0 = triggeredByAura->GetModifier()->m_amount;
5651 target = this;
5652 triggered_spell_id = 379;
5653 break;
5655 // Improved Water Shield
5656 if (dummySpell->SpellIconID == 2287)
5658 // lookup water shield
5659 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5660 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5662 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5663 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000002000000000LL)
5665 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
5666 CastSpell(this, spell, true, castItem, triggeredByAura);
5667 if ((*itr)->DropAuraCharge())
5668 RemoveAurasDueToSpell((*itr)->GetId());
5669 return true;
5672 return false;
5673 break;
5675 // Lightning Overload
5676 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5678 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5679 return false;
5681 // custom cooldown processing case
5682 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5683 return false;
5685 uint32 spellId = 0;
5686 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5687 switch (procSpell->Id)
5689 // Lightning Bolt
5690 case 403: spellId = 45284; break; // Rank 1
5691 case 529: spellId = 45286; break; // Rank 2
5692 case 548: spellId = 45287; break; // Rank 3
5693 case 915: spellId = 45288; break; // Rank 4
5694 case 943: spellId = 45289; break; // Rank 5
5695 case 6041: spellId = 45290; break; // Rank 6
5696 case 10391: spellId = 45291; break; // Rank 7
5697 case 10392: spellId = 45292; break; // Rank 8
5698 case 15207: spellId = 45293; break; // Rank 9
5699 case 15208: spellId = 45294; break; // Rank 10
5700 case 25448: spellId = 45295; break; // Rank 11
5701 case 25449: spellId = 45296; break; // Rank 12
5702 case 49237: spellId = 49239; break; // Rank 13
5703 case 49238: spellId = 49240; break; // Rank 14
5704 // Chain Lightning
5705 case 421: spellId = 45297; break; // Rank 1
5706 case 930: spellId = 45298; break; // Rank 2
5707 case 2860: spellId = 45299; break; // Rank 3
5708 case 10605: spellId = 45300; break; // Rank 4
5709 case 25439: spellId = 45301; break; // Rank 5
5710 case 25442: spellId = 45302; break; // Rank 6
5711 case 49268: spellId = 49270; break; // Rank 7
5712 case 49269: spellId = 49271; break; // Rank 8
5713 default:
5714 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5715 return false;
5717 // No thread generated mod
5718 // TODO: exist special flag in spell attributes for this, need found and use!
5719 SpellModifier *mod = new SpellModifier;
5720 mod->op = SPELLMOD_THREAT;
5721 mod->value = -100;
5722 mod->type = SPELLMOD_PCT;
5723 mod->spellId = dummySpell->Id;
5724 mod->mask = 0x0000000000000003LL;
5725 mod->mask2= 0LL;
5726 ((Player*)this)->AddSpellMod(mod, true);
5728 // Remove cooldown (Chain Lightning - have Category Recovery time)
5729 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5730 ((Player*)this)->RemoveSpellCooldown(spellId);
5732 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5734 ((Player*)this)->AddSpellMod(mod, false);
5736 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5737 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5739 return true;
5741 // Static Shock
5742 if(dummySpell->SpellIconID == 3059)
5744 // lookup Lightning Shield
5745 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5746 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5748 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5749 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000000000000400LL)
5751 uint32 spell = 0;
5752 switch ((*itr)->GetId())
5754 case 324: spell = 26364; break;
5755 case 325: spell = 26365; break;
5756 case 905: spell = 26366; break;
5757 case 945: spell = 26367; break;
5758 case 8134: spell = 26369; break;
5759 case 10431: spell = 26370; break;
5760 case 10432: spell = 26363; break;
5761 case 25469: spell = 26371; break;
5762 case 25472: spell = 26372; break;
5763 default:
5764 return false;
5766 CastSpell(this, spell, true, castItem, triggeredByAura);
5767 if ((*itr)->DropAuraCharge())
5768 RemoveAurasDueToSpell((*itr)->GetId());
5769 return true;
5772 return false;
5773 break;
5775 break;
5777 case SPELLFAMILY_DEATHKNIGHT:
5779 // Blood Aura
5780 if (dummySpell->SpellIconID == 2636)
5782 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
5783 return false;
5784 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5785 triggered_spell_id = 53168;
5786 break;
5788 // Butchery
5789 if (dummySpell->SpellIconID == 2664)
5791 basepoints0 = triggeredByAura->GetModifier()->m_amount;
5792 triggered_spell_id = 50163;
5793 target = this;
5794 break;
5796 // Dancing Rune Weapon
5797 if (dummySpell->Id == 49028)
5799 // 1 dummy aura for dismiss rune blade
5800 if (triggeredByAura->GetEffIndex()!=2)
5801 return false;
5802 // TODO: wite script for this "fights on its own, doing the same attacks"
5803 // NOTE: Trigger here on every attack and spell cast
5804 return false;
5806 // Mark of Blood
5807 if (dummySpell->Id == 49005)
5809 // TODO: need more info (cooldowns/PPM)
5810 triggered_spell_id = 50424;
5811 break;
5813 // Vendetta
5814 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
5816 basepoints0 = triggeredByAura->GetModifier()->m_amount * GetMaxHealth() / 100;
5817 triggered_spell_id = 50181;
5818 target = this;
5819 break;
5821 // Necrosis
5822 if (dummySpell->SpellIconID == 2709)
5824 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5825 triggered_spell_id = 51460;
5826 break;
5828 // Runic Power Back on Snare/Root
5829 if (dummySpell->Id == 61257)
5831 // only for spells and hit/crit (trigger start always) and not start from self casted spells
5832 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5833 return false;
5834 // Need snare or root mechanic
5835 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
5836 return false;
5837 triggered_spell_id = 61258;
5838 target = this;
5839 break;
5841 // Wandering Plague
5842 if (dummySpell->SpellIconID == 1614)
5844 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
5845 return false;
5846 basepoints0 = triggeredByAura->GetModifier()->m_amount * damage / 100;
5847 triggered_spell_id = 50526;
5848 break;
5850 break;
5852 default:
5853 break;
5856 // processed charge only counting case
5857 if(!triggered_spell_id)
5858 return true;
5860 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5862 if(!triggerEntry)
5864 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5865 return false;
5868 // default case
5869 if(!target || target!=this && !target->isAlive())
5870 return false;
5872 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5873 return false;
5875 if(basepoints0)
5876 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5877 else
5878 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5880 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5881 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5883 return true;
5886 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5888 // Get triggered aura spell info
5889 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5891 // Basepoints of trigger aura
5892 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5894 // Set trigger spell id, target, custom basepoints
5895 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
5896 Unit* target = NULL;
5897 int32 basepoints0 = 0;
5899 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
5900 basepoints0 = triggerAmount;
5902 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5903 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5905 // Try handle uncnown trigger spells
5906 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
5908 switch (auraSpellInfo->SpellFamilyName)
5910 case SPELLFAMILY_GENERIC:
5911 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
5912 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
5913 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
5914 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
5915 trigger_spell_id = 23781;
5916 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
5917 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
5919 // trigger_spell_id = 48877;
5921 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
5923 // trigger_spell_id = 59233;
5925 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
5927 // trigger_spell_id = 29471; // gain mana
5928 // 27526; // drain mana if possible
5930 //else if (auraSpellInfo->Id==50844) // Blood Mirror
5931 //else if (auraSpellInfo->Id==54476) // Blood Presence
5932 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
5933 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
5934 //else if (auraSpellInfo->Id==52856) // Charge
5935 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
5937 // Pct value stored in dummy
5938 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
5939 target = pVictim;
5940 break;
5942 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
5943 // trigger_spell_id = 41249;
5944 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
5945 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
5946 //else if (auraSpellInfo->Id==41054) // Copy Weapon
5947 // trigger_spell_id = 41055;
5948 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
5949 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
5950 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
5952 uint32 stat = 0;
5953 // strength
5954 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
5955 // agility
5956 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
5957 // intellect
5958 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
5959 // spirit
5960 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
5962 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
5963 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
5964 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
5965 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
5966 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
5967 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
5968 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
5969 trigger_spell_id = 33898;
5970 //else if (auraSpellInfo->Id==18943) // Double Attack
5971 //else if (auraSpellInfo->Id==19194) // Double Attack
5972 //else if (auraSpellInfo->Id==19817) // Double Attack
5973 //else if (auraSpellInfo->Id==19818) // Double Attack
5974 //else if (auraSpellInfo->Id==22835) // Drunken Rage
5975 // trigger_spell_id = 14822;
5977 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
5979 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
5981 case 34191:
5982 case 34329:
5983 case 34524:
5984 case 34582:
5985 case 36733:
5986 break;
5987 default:
5988 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
5989 return false;
5991 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
5992 switch (procSpell->School)
5994 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
5995 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
5996 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
5997 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
5998 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
5999 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6000 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6001 default:
6002 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6003 return false;
6007 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6008 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6009 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6010 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6011 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6012 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6013 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6014 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6015 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6016 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6017 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6018 //else if (auraSpellInfo->Id==40250) // Improved Duration
6019 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6020 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6021 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6022 // Mana Drain Trigger
6024 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6025 if (this && this->isAlive())
6026 CastSpell(this, 29471, true, castItem, triggeredByAura);
6027 if (pVictim && pVictim->isAlive())
6028 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6029 return true;
6031 //else if (auraSpellInfo->Id==55580) // Mana Link
6032 //else if (auraSpellInfo->Id==45903) // Offensive State
6033 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6034 //else if (auraSpellInfo->Id==43453) // Rune Ward
6035 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6036 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6037 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6038 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6039 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6040 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6041 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6042 //else if (auraSpellInfo->Id==35205) // Vanish
6043 //else if (auraSpellInfo->Id==42730) // Woe Strike
6044 //else if (auraSpellInfo->Id==59735) // Woe Strike
6045 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6046 break;
6047 case SPELLFAMILY_MAGE:
6048 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6050 switch (auraSpellInfo->Id)
6052 case 31641: // Rank 1
6053 case 31642: // Rank 2
6054 trigger_spell_id = 31643;
6055 break;
6056 default:
6057 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6058 return false;
6061 break;
6062 case SPELLFAMILY_WARRIOR:
6063 if (auraSpellInfo->Id == 50421) // Scent of Blood
6064 trigger_spell_id = 50422;
6065 break;
6066 case SPELLFAMILY_WARLOCK:
6068 // Pyroclasm
6069 if (auraSpellInfo->SpellIconID == 1137)
6071 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6072 return false;
6073 // Calculate spell tick count for spells
6074 uint32 tick = 1; // Default tick = 1
6076 // Hellfire have 15 tick
6077 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
6078 tick = 15;
6079 // Rain of Fire have 4 tick
6080 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
6081 tick = 4;
6082 else
6083 return false;
6085 // Calculate chance = baseChance / tick
6086 float chance = 0;
6087 switch (auraSpellInfo->Id)
6089 case 18096: chance = 13.0f / tick; break;
6090 case 18073: chance = 26.0f / tick; break;
6092 // Roll chance
6093 if (!roll_chance_f(chance))
6094 return false;
6096 trigger_spell_id = 18093;
6098 // Drain Soul
6099 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
6101 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6102 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6104 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6106 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
6107 // Drain Soul
6108 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
6109 break;
6112 // Not remove charge (aura removed on death in any cases)
6113 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6114 return false;
6116 // Nether Protection
6117 else if (auraSpellInfo->SpellIconID == 1985)
6119 if (!procSpell)
6120 return false;
6121 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6123 case SPELL_SCHOOL_NORMAL:
6124 case SPELL_SCHOOL_HOLY:
6125 return false; // ignore
6126 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6127 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6128 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6129 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6130 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6131 default:
6132 return false;
6135 break;
6137 case SPELLFAMILY_PRIEST:
6139 // Greater Heal Refund
6140 if (auraSpellInfo->Id==37594)
6141 trigger_spell_id = 37595;
6142 // Blessed Recovery
6143 else if (auraSpellInfo->SpellIconID == 1875)
6145 switch (auraSpellInfo->Id)
6147 case 27811: trigger_spell_id = 27813; break;
6148 case 27815: trigger_spell_id = 27817; break;
6149 case 27816: trigger_spell_id = 27818; break;
6150 default:
6151 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6152 return false;
6154 basepoints0 = damage * triggerAmount / 100 / 3;
6155 target = this;
6157 break;
6159 case SPELLFAMILY_DRUID:
6161 // Druid Forms Trinket
6162 if (auraSpellInfo->Id==37336)
6164 switch(m_form)
6166 case FORM_NONE: trigger_spell_id = 37344;break;
6167 case FORM_CAT: trigger_spell_id = 37341;break;
6168 case FORM_BEAR:
6169 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6170 case FORM_TREE: trigger_spell_id = 37342;break;
6171 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6172 default:
6173 return false;
6176 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6177 // trigger_spell_id = ????;
6178 // Leader of the Pack
6179 else if (auraSpellInfo->Id == 24932)
6181 if (triggerAmount == 0)
6182 return false;
6183 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6184 trigger_spell_id = 34299;
6186 break;
6188 case SPELLFAMILY_HUNTER:
6189 break;
6190 case SPELLFAMILY_PALADIN:
6193 // Blessed Life
6194 if (auraSpellInfo->SpellIconID == 2137)
6196 switch (auraSpellInfo->Id)
6198 case 31828: // Rank 1
6199 case 31829: // Rank 2
6200 case 31830: // Rank 3
6201 break;
6202 default:
6203 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6204 return false;
6208 // Healing Discount
6209 if (auraSpellInfo->Id==37705)
6211 trigger_spell_id = 37706;
6212 target = this;
6214 // Soul Preserver
6215 if (auraSpellInfo->Id==60510)
6217 trigger_spell_id = 60515;
6218 target = this;
6220 // Illumination
6221 else if (auraSpellInfo->SpellIconID==241)
6223 if(!procSpell)
6224 return false;
6225 // procspell is triggered spell but we need mana cost of original casted spell
6226 uint32 originalSpellId = procSpell->Id;
6227 // Holy Shock heal
6228 if(procSpell->SpellFamilyFlags & 0x0001000000000000LL)
6230 switch(procSpell->Id)
6232 case 25914: originalSpellId = 20473; break;
6233 case 25913: originalSpellId = 20929; break;
6234 case 25903: originalSpellId = 20930; break;
6235 case 27175: originalSpellId = 27174; break;
6236 case 33074: originalSpellId = 33072; break;
6237 case 48820: originalSpellId = 48824; break;
6238 case 48821: originalSpellId = 48825; break;
6239 default:
6240 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6241 return false;
6244 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6245 if(!originalSpell)
6247 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6248 return false;
6250 // percent stored in effect 1 (class scripts) base points
6251 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6252 basepoints0 = cost*(auraSpellInfo->EffectBasePoints[1]+1)/100;
6253 trigger_spell_id = 20272;
6254 target = this;
6256 // Lightning Capacitor
6257 else if (auraSpellInfo->Id==37657)
6259 if(!pVictim || !pVictim->isAlive())
6260 return false;
6261 // stacking
6262 CastSpell(this, 37658, true, NULL, triggeredByAura);
6264 Aura * dummy = GetDummyAura(37658);
6265 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6266 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6267 return false;
6269 RemoveAurasDueToSpell(37658);
6270 trigger_spell_id = 37661;
6271 target = pVictim;
6273 // Thunder Capacitor
6274 else if (auraSpellInfo->Id == 54841)
6276 if(!pVictim || !pVictim->isAlive())
6277 return false;
6278 // stacking
6279 CastSpell(this, 54842, true, NULL, triggeredByAura);
6281 // counting
6282 Aura * dummy = GetDummyAura(54842);
6283 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6284 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6285 return false;
6287 RemoveAurasDueToSpell(54842);
6288 trigger_spell_id = 54843;
6289 target = pVictim;
6291 break;
6293 case SPELLFAMILY_SHAMAN:
6295 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6296 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
6298 switch(auraSpellInfo->Id)
6300 case 324: // Rank 1
6301 trigger_spell_id = 26364; break;
6302 case 325: // Rank 2
6303 trigger_spell_id = 26365; break;
6304 case 905: // Rank 3
6305 trigger_spell_id = 26366; break;
6306 case 945: // Rank 4
6307 trigger_spell_id = 26367; break;
6308 case 8134: // Rank 5
6309 trigger_spell_id = 26369; break;
6310 case 10431: // Rank 6
6311 trigger_spell_id = 26370; break;
6312 case 10432: // Rank 7
6313 trigger_spell_id = 26363; break;
6314 case 25469: // Rank 8
6315 trigger_spell_id = 26371; break;
6316 case 25472: // Rank 9
6317 trigger_spell_id = 26372; break;
6318 default:
6319 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6320 return false;
6323 // Lightning Shield (The Ten Storms set)
6324 else if (auraSpellInfo->Id == 23551)
6326 trigger_spell_id = 23552;
6327 target = pVictim;
6329 // Damage from Lightning Shield (The Ten Storms set)
6330 else if (auraSpellInfo->Id == 23552)
6331 trigger_spell_id = 27635;
6332 // Mana Surge (The Earthfury set)
6333 else if (auraSpellInfo->Id == 23572)
6335 if(!procSpell)
6336 return false;
6337 basepoints0 = procSpell->manaCost * 35 / 100;
6338 trigger_spell_id = 23571;
6339 target = this;
6341 // Nature's Guardian
6342 else if (auraSpellInfo->SpellIconID == 2013)
6344 // Check health condition - should drop to less 30% (damage deal after this!)
6345 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6346 return false;
6348 if(pVictim && pVictim->isAlive())
6349 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6351 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6352 trigger_spell_id = 31616;
6353 target = this;
6355 break;
6357 case SPELLFAMILY_DEATHKNIGHT:
6359 // Acclimation
6360 if (auraSpellInfo->SpellIconID == 1930)
6362 if (!procSpell)
6363 return false;
6364 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6366 case SPELL_SCHOOL_NORMAL:
6367 return false; // ignore
6368 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6369 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6370 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6371 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6372 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6373 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6374 default:
6375 return false;
6378 // Blood Presence
6379 else if (auraSpellInfo->Id == 48266)
6381 if (GetTypeId() != TYPEID_PLAYER)
6382 return false;
6383 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6384 return false;
6385 trigger_spell_id = 50475;
6386 basepoints0 = damage * triggerAmount / 100;
6388 break;
6390 default:
6391 break;
6395 // All ok. Check current trigger spell
6396 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6397 if ( triggerEntry == NULL )
6399 // Not cast unknown spell
6400 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6401 return false;
6404 // not allow proc extra attack spell at extra attack
6405 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6406 return false;
6408 // Costum requirements (not listed in procEx) Warning! damage dealing after this
6409 // Custom triggered spells
6410 switch (auraSpellInfo->Id)
6412 // Persistent Shield (Scarab Brooch trinket)
6413 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6414 case 26467:
6416 basepoints0 = damage * 15 / 100;
6417 target = pVictim;
6418 trigger_spell_id = 26470;
6419 break;
6421 // Cheat Death
6422 case 28845:
6424 // When your health drops below 20% ....
6425 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6426 return false;
6427 break;
6429 // Deadly Swiftness (Rank 1)
6430 case 31255:
6432 // whenever you deal damage to a target who is below 20% health.
6433 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6434 return false;
6436 target = this;
6437 trigger_spell_id = 22588;
6439 // Greater Heal Refund (Avatar Raiment set)
6440 case 37594:
6442 // Not give if target alredy have full health
6443 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6444 return false;
6445 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6446 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6447 return false;
6448 break;
6450 // Bonus Healing (Crystal Spire of Karabor mace)
6451 case 40971:
6453 // If your target is below $s1% health
6454 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6455 return false;
6456 break;
6458 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6459 case 45057:
6461 // reduce you below $s1% health
6462 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6463 return false;
6464 break;
6468 // Costum basepoints/target for exist spell
6469 // dummy basepoints or other customs
6470 switch(trigger_spell_id)
6472 // Cast positive spell on enemy target
6473 case 7099: // Curse of Mending
6474 case 39647: // Curse of Mending
6475 case 29494: // Temptation
6476 case 20233: // Improved Lay on Hands (cast on target)
6478 target = pVictim;
6479 break;
6481 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
6482 case 15250: // Rogue Setup
6484 if(!pVictim || pVictim != getVictim()) // applied only for main target
6485 return false;
6486 break; // continue normal case
6488 // Finish movies that add combo
6489 case 14189: // Seal Fate (Netherblade set)
6490 case 14157: // Ruthlessness
6492 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6493 break;
6495 // Shamanistic Rage triggered spell
6496 case 30824:
6498 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6499 trigger_spell_id = 30824;
6500 break;
6502 // Enlightenment (trigger only from mana cost spells)
6503 case 35095:
6505 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6506 return false;
6507 break;
6509 // Brain Freeze
6510 case 57761:
6512 if(!procSpell)
6513 return false;
6514 // For trigger from Blizzard need exist Improved Blizzard
6515 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && procSpell->SpellFamilyFlags & 0x0000000000000080)
6517 bool found = false;
6518 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6519 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6521 int32 script = (*i)->GetModifier()->m_miscvalue;
6522 if(script==836 || script==988 || script==989)
6524 found=true;
6525 break;
6528 if(!found)
6529 return false;
6531 break;
6533 // Astral Shift
6534 case 52179:
6536 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6537 return false;
6539 // Need stun, fear or silence mechanic
6540 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
6541 return false;
6542 break;
6544 // Burning Determination
6545 case 54748:
6547 if(!procSpell)
6548 return false;
6549 // Need Interrupt or Silenced mechanic
6550 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
6551 return false;
6552 break;
6556 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6557 return false;
6559 // try detect target manually if not set
6560 if ( target == NULL )
6561 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6563 // default case
6564 if(!target || target!=this && !target->isAlive())
6565 return false;
6567 if(basepoints0)
6568 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6569 else
6570 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6572 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6573 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6575 return true;
6578 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6580 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6582 if(!pVictim || !pVictim->isAlive())
6583 return false;
6585 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6586 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6588 uint32 triggered_spell_id = 0;
6590 switch(scriptId)
6592 case 836: // Improved Blizzard (Rank 1)
6594 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6595 return false;
6596 triggered_spell_id = 12484;
6597 break;
6599 case 988: // Improved Blizzard (Rank 2)
6601 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6602 return false;
6603 triggered_spell_id = 12485;
6604 break;
6606 case 989: // Improved Blizzard (Rank 3)
6608 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6609 return false;
6610 triggered_spell_id = 12486;
6611 break;
6613 case 4086: // Improved Mend Pet (Rank 1)
6614 case 4087: // Improved Mend Pet (Rank 2)
6616 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6617 if(!roll_chance_i(chance))
6618 return false;
6620 triggered_spell_id = 24406;
6621 break;
6623 case 4533: // Dreamwalker Raiment 2 pieces bonus
6625 // Chance 50%
6626 if (!roll_chance_i(50))
6627 return false;
6629 switch (pVictim->getPowerType())
6631 case POWER_MANA: triggered_spell_id = 28722; break;
6632 case POWER_RAGE: triggered_spell_id = 28723; break;
6633 case POWER_ENERGY: triggered_spell_id = 28724; break;
6634 default:
6635 return false;
6637 break;
6639 case 4537: // Dreamwalker Raiment 6 pieces bonus
6640 triggered_spell_id = 28750; // Blessing of the Claw
6641 break;
6642 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6643 triggered_spell_id = 37445; // Mana Surge
6644 break;
6645 case 8152: // Serendipity
6647 // if heal your target over maximum health
6648 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6649 return false;
6650 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6651 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
6652 CastCustomSpell(this, 47762, &basepoints0, 0, 0, true, 0, triggeredByAura);
6653 return true;
6657 // not processed
6658 if(!triggered_spell_id)
6659 return false;
6661 // standard non-dummy case
6662 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6664 if(!triggerEntry)
6666 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6667 return false;
6670 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6671 return false;
6673 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6675 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6676 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6678 return true;
6681 void Unit::setPowerType(Powers new_powertype)
6683 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6685 if(GetTypeId() == TYPEID_PLAYER)
6687 if(((Player*)this)->GetGroup())
6688 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6690 else if(((Creature*)this)->isPet())
6692 Pet *pet = ((Pet*)this);
6693 if(pet->isControlled())
6695 Unit *owner = GetOwner();
6696 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6697 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6701 switch(new_powertype)
6703 default:
6704 case POWER_MANA:
6705 break;
6706 case POWER_RAGE:
6707 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6708 SetPower( POWER_RAGE,0);
6709 break;
6710 case POWER_FOCUS:
6711 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6712 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6713 break;
6714 case POWER_ENERGY:
6715 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6716 SetPower( POWER_ENERGY,0);
6717 break;
6718 case POWER_HAPPINESS:
6719 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6720 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6721 break;
6725 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6727 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6728 if(!entry)
6730 static uint64 guid = 0; // prevent repeating spam same faction problem
6732 if(GetGUID() != guid)
6734 if(GetTypeId() == TYPEID_PLAYER)
6735 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6736 else
6737 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6738 guid = GetGUID();
6741 return entry;
6744 bool Unit::IsHostileTo(Unit const* unit) const
6746 // always non-hostile to self
6747 if(unit==this)
6748 return false;
6750 // always non-hostile to GM in GM mode
6751 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6752 return false;
6754 // always hostile to enemy
6755 if(getVictim()==unit || unit->getVictim()==this)
6756 return true;
6758 // test pet/charm masters instead pers/charmeds
6759 Unit const* testerOwner = GetCharmerOrOwner();
6760 Unit const* targetOwner = unit->GetCharmerOrOwner();
6762 // always hostile to owner's enemy
6763 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6764 return true;
6766 // always hostile to enemy owner
6767 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6768 return true;
6770 // always hostile to owner of owner's enemy
6771 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6772 return true;
6774 Unit const* tester = testerOwner ? testerOwner : this;
6775 Unit const* target = targetOwner ? targetOwner : unit;
6777 // always non-hostile to target with common owner, or to owner/pet
6778 if(tester==target)
6779 return false;
6781 // special cases (Duel, etc)
6782 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6784 Player const* pTester = (Player const*)tester;
6785 Player const* pTarget = (Player const*)target;
6787 // Duel
6788 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6789 return true;
6791 // Group
6792 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6793 return false;
6795 // Sanctuary
6796 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6797 return false;
6799 // PvP FFA state
6800 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))
6801 return true;
6803 //= PvP states
6804 // Green/Blue (can't attack)
6805 if(pTester->GetTeam()==pTarget->GetTeam())
6806 return false;
6808 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6809 return pTester->IsPvP() && pTarget->IsPvP();
6812 // faction base cases
6813 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6814 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6815 if(!tester_faction || !target_faction)
6816 return false;
6818 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6819 return true;
6821 // PvC forced reaction and reputation case
6822 if(tester->GetTypeId()==TYPEID_PLAYER)
6824 // forced reaction
6825 ForcedReactions::const_iterator forceItr = ((Player*)tester)->m_forcedReactions.find(target_faction->faction);
6826 if(forceItr!=((Player*)tester)->m_forcedReactions.end())
6827 return forceItr->second <= REP_HOSTILE;
6829 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6830 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6831 if(raw_target_faction->reputationListID >=0)
6832 if(FactionState const* factionState = ((Player*)tester)->GetFactionState(raw_target_faction))
6833 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6835 // CvP forced reaction and reputation case
6836 else if(target->GetTypeId()==TYPEID_PLAYER)
6838 // forced reaction
6839 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
6840 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
6841 return forceItr->second <= REP_HOSTILE;
6843 // apply reputation state
6844 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6845 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6846 return ((Player const*)target)->GetReputationRank(raw_tester_faction) <= REP_HOSTILE;
6849 // common faction based case (CvC,PvC,CvP)
6850 return tester_faction->IsHostileTo(*target_faction);
6853 bool Unit::IsFriendlyTo(Unit const* unit) const
6855 // always friendly to self
6856 if(unit==this)
6857 return true;
6859 // always friendly to GM in GM mode
6860 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6861 return true;
6863 // always non-friendly to enemy
6864 if(getVictim()==unit || unit->getVictim()==this)
6865 return false;
6867 // test pet/charm masters instead pers/charmeds
6868 Unit const* testerOwner = GetCharmerOrOwner();
6869 Unit const* targetOwner = unit->GetCharmerOrOwner();
6871 // always non-friendly to owner's enemy
6872 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6873 return false;
6875 // always non-friendly to enemy owner
6876 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6877 return false;
6879 // always non-friendly to owner of owner's enemy
6880 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6881 return false;
6883 Unit const* tester = testerOwner ? testerOwner : this;
6884 Unit const* target = targetOwner ? targetOwner : unit;
6886 // always friendly to target with common owner, or to owner/pet
6887 if(tester==target)
6888 return true;
6890 // special cases (Duel)
6891 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6893 Player const* pTester = (Player const*)tester;
6894 Player const* pTarget = (Player const*)target;
6896 // Duel
6897 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
6898 return false;
6900 // Group
6901 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6902 return true;
6904 // Sanctuary
6905 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6906 return true;
6908 // PvP FFA state
6909 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))
6910 return false;
6912 //= PvP states
6913 // Green/Blue (non-attackable)
6914 if(pTester->GetTeam()==pTarget->GetTeam())
6915 return true;
6917 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
6918 return !pTarget->IsPvP();
6921 // faction base cases
6922 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6923 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6924 if(!tester_faction || !target_faction)
6925 return false;
6927 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6928 return false;
6930 // PvC forced reaction and reputation case
6931 if(tester->GetTypeId()==TYPEID_PLAYER)
6933 // forced reaction
6934 ForcedReactions::const_iterator forceItr = ((Player const*)tester)->m_forcedReactions.find(target_faction->faction);
6935 if(forceItr!=((Player const*)tester)->m_forcedReactions.end())
6936 return forceItr->second >= REP_FRIENDLY;
6938 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
6939 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6940 if(raw_target_faction->reputationListID >=0)
6941 if(FactionState const* FactionState = ((Player*)tester)->GetFactionState(raw_target_faction))
6942 return !(FactionState->Flags & FACTION_FLAG_AT_WAR);
6944 // CvP forced reaction and reputation case
6945 else if(target->GetTypeId()==TYPEID_PLAYER)
6947 // forced reaction
6948 ForcedReactions::const_iterator forceItr = ((Player const*)target)->m_forcedReactions.find(tester_faction->faction);
6949 if(forceItr!=((Player const*)target)->m_forcedReactions.end())
6950 return forceItr->second >= REP_FRIENDLY;
6952 // apply reputation state
6953 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
6954 if(raw_tester_faction->reputationListID >=0 )
6955 return ((Player const*)target)->GetReputationRank(raw_tester_faction) >= REP_FRIENDLY;
6958 // common faction based case (CvC,PvC,CvP)
6959 return tester_faction->IsFriendlyTo(*target_faction);
6962 bool Unit::IsHostileToPlayers() const
6964 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
6965 if(!my_faction)
6966 return false;
6968 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
6969 if(raw_faction && raw_faction->reputationListID >=0 )
6970 return false;
6972 return my_faction->IsHostileToPlayers();
6975 bool Unit::IsNeutralToAll() const
6977 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
6978 if(!my_faction)
6979 return true;
6981 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
6982 if(raw_faction && raw_faction->reputationListID >=0 )
6983 return false;
6985 return my_faction->IsNeutralToAll();
6988 bool Unit::Attack(Unit *victim, bool meleeAttack)
6990 if(!victim || victim == this)
6991 return false;
6993 // dead units can neither attack nor be attacked
6994 if(!isAlive() || !victim->isAlive())
6995 return false;
6997 // player cannot attack in mount state
6998 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
6999 return false;
7001 // nobody can attack GM in GM-mode
7002 if(victim->GetTypeId()==TYPEID_PLAYER)
7004 if(((Player*)victim)->isGameMaster())
7005 return false;
7007 else
7009 if(((Creature*)victim)->IsInEvadeMode())
7010 return false;
7013 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7014 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7015 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7017 if (m_attacking)
7019 if (m_attacking == victim)
7021 // switch to melee attack from ranged/magic
7022 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7024 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7025 SendAttackStart(victim);
7026 return true;
7028 return false;
7030 AttackStop();
7033 //Set our target
7034 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7036 if(meleeAttack)
7037 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7038 m_attacking = victim;
7039 m_attacking->_addAttacker(this);
7041 if(m_attacking->GetTypeId()==TYPEID_UNIT && ((Creature*)m_attacking)->AI())
7042 ((Creature*)m_attacking)->AI()->AttackedBy(this);
7044 if(GetTypeId()==TYPEID_UNIT)
7046 WorldPacket data(SMSG_AI_REACTION, 12);
7047 data << uint64(GetGUID());
7048 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7049 ((WorldObject*)this)->SendMessageToSet(&data, true);
7051 ((Creature*)this)->CallAssistance();
7052 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7055 // delay offhand weapon attack to next attack time
7056 if(haveOffhandWeapon())
7057 resetAttackTimer(OFF_ATTACK);
7059 if(meleeAttack)
7060 SendAttackStart(victim);
7062 return true;
7065 bool Unit::AttackStop()
7067 if (!m_attacking)
7068 return false;
7070 Unit* victim = m_attacking;
7072 m_attacking->_removeAttacker(this);
7073 m_attacking = NULL;
7075 //Clear our target
7076 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7078 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7080 InterruptSpell(CURRENT_MELEE_SPELL);
7082 if( GetTypeId()==TYPEID_UNIT )
7084 // reset call assistance
7085 ((Creature*)this)->SetNoCallAssistance(false);
7088 SendAttackStop(victim);
7090 return true;
7093 void Unit::CombatStop(bool cast)
7095 if(cast& IsNonMeleeSpellCasted(false))
7096 InterruptNonMeleeSpells(false);
7098 AttackStop();
7099 RemoveAllAttackers();
7100 if( GetTypeId()==TYPEID_PLAYER )
7101 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7102 ClearInCombat();
7105 void Unit::CombatStopWithPets(bool cast)
7107 CombatStop(cast);
7108 if(Pet* pet = GetPet())
7109 pet->CombatStop(cast);
7110 if(Unit* charm = GetCharm())
7111 charm->CombatStop(cast);
7112 if(GetTypeId()==TYPEID_PLAYER)
7114 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
7115 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
7116 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7117 guardian->CombatStop(cast);
7121 bool Unit::isAttackingPlayer() const
7123 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7124 return true;
7126 Pet* pet = GetPet();
7127 if(pet && pet->isAttackingPlayer())
7128 return true;
7130 Unit* charmed = GetCharm();
7131 if(charmed && charmed->isAttackingPlayer())
7132 return true;
7134 for (int8 i = 0; i < MAX_TOTEM; i++)
7136 if(m_TotemSlot[i])
7138 Creature *totem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
7139 if(totem && totem->isAttackingPlayer())
7140 return true;
7144 return false;
7147 void Unit::RemoveAllAttackers()
7149 while (!m_attackers.empty())
7151 AttackerSet::iterator iter = m_attackers.begin();
7152 if(!(*iter)->AttackStop())
7154 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7155 m_attackers.erase(iter);
7160 void Unit::ModifyAuraState(AuraState flag, bool apply)
7162 if (apply)
7164 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
7166 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7167 if(GetTypeId() == TYPEID_PLAYER)
7169 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
7170 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
7172 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
7173 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
7174 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
7175 if (spellInfo->CasterAuraState == flag)
7176 CastSpell(this, itr->first, true, NULL);
7181 else
7183 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
7185 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7186 Unit::AuraMap& tAuras = GetAuras();
7187 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
7189 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
7190 if (spellProto->CasterAuraState == flag)
7192 // exceptions (applied at state but not removed at state change)
7193 // Rampage
7194 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
7196 ++itr;
7197 continue;
7200 RemoveAura(itr);
7202 else
7203 ++itr;
7209 Unit *Unit::GetOwner() const
7211 uint64 ownerid = GetOwnerGUID();
7212 if(!ownerid)
7213 return NULL;
7214 return ObjectAccessor::GetUnit(*this, ownerid);
7217 Unit *Unit::GetCharmer() const
7219 if(uint64 charmerid = GetCharmerGUID())
7220 return ObjectAccessor::GetUnit(*this, charmerid);
7221 return NULL;
7224 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7226 uint64 guid = GetCharmerOrOwnerGUID();
7227 if(IS_PLAYER_GUID(guid))
7228 return ObjectAccessor::GetPlayer(*this, guid);
7230 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7233 Pet* Unit::GetPet() const
7235 if(uint64 pet_guid = GetPetGUID())
7237 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7238 return pet;
7240 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7241 const_cast<Unit*>(this)->SetPet(0);
7244 return NULL;
7247 Unit* Unit::GetCharm() const
7249 if(uint64 charm_guid = GetCharmGUID())
7251 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7252 return pet;
7254 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7255 const_cast<Unit*>(this)->SetCharm(0);
7258 return NULL;
7261 void Unit::SetPet(Pet* pet)
7263 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7265 // FIXME: hack, speed must be set only at follow
7266 if(pet)
7267 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7268 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7271 void Unit::SetCharm(Unit* pet)
7273 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7275 if(GetTypeId() == TYPEID_PLAYER)
7276 ((Player*)this)->m_mover = pet ? pet : this;
7279 void Unit::UnsummonAllTotems()
7281 for (int8 i = 0; i < MAX_TOTEM; ++i)
7283 if(!m_TotemSlot[i])
7284 continue;
7286 Creature *OldTotem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
7287 if (OldTotem && OldTotem->isTotem())
7288 ((Totem*)OldTotem)->UnSummon();
7292 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
7294 // we guess size
7295 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
7296 data.append(pVictim->GetPackGUID());
7297 data.append(GetPackGUID());
7298 data << uint32(SpellID);
7299 data << uint32(Damage);
7300 data << uint32(0); // over healing?
7301 data << uint8(critical ? 1 : 0);
7302 data << uint8(0); // unused in client?
7303 SendMessageToSet(&data, true);
7306 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
7308 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
7309 data.append(pVictim->GetPackGUID());
7310 data.append(GetPackGUID());
7311 data << uint32(SpellID);
7312 data << uint32(powertype);
7313 data << uint32(Damage);
7314 SendMessageToSet(&data, true);
7317 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype)
7319 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
7320 return pdamage;
7322 int32 BonusDamage = 0;
7323 if( GetTypeId()==TYPEID_UNIT )
7325 // Pets just add their bonus damage to their spell damage
7326 // note that their spell damage is just gain of their own auras
7327 if (((Creature*)this)->isPet())
7329 BonusDamage = ((Pet*)this)->GetBonusDamage();
7331 // For totems get damage bonus from owner (statue isn't totem in fact)
7332 else if (((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7334 if(Unit* owner = GetOwner())
7335 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
7339 // Damage Done
7340 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
7342 // Taken/Done fixed damage bonus auras
7343 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto))+BonusDamage;
7344 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7346 // Damage over Time spells bonus calculation
7347 float DotFactor = 1.0f;
7348 if(damagetype == DOT)
7350 int32 DotDuration = GetSpellDuration(spellProto);
7351 // 200% limit
7352 if(DotDuration > 0)
7354 if(DotDuration > 30000) DotDuration = 30000;
7355 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7356 int x = 0;
7357 for(int j = 0; j < 3; j++)
7359 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7360 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
7361 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7363 x = j;
7364 break;
7367 int DotTicks = 6;
7368 if(spellProto->EffectAmplitude[x] != 0)
7369 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7370 if(DotTicks)
7372 DoneAdvertisedBenefit /= DotTicks;
7373 TakenAdvertisedBenefit /= DotTicks;
7378 // Taken/Done total percent damage auras
7379 float DoneTotalMod = 1.0f;
7380 float TakenTotalMod = 1.0f;
7382 // ..done
7383 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7384 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
7386 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
7387 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7388 // -1 == any item class (not wand then)
7389 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7390 // 0 == any inventory type (not wand then)
7392 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7396 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7397 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7398 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7399 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7400 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7402 // ..taken
7403 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7404 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7405 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
7406 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7408 // .. taken pct: scripted (increases damage of * against targets *)
7409 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7410 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7412 switch((*i)->GetModifier()->m_miscvalue)
7414 //Molten Fury
7415 case 4920: case 4919:
7416 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7417 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f; break;
7421 // .. taken pct: dummy auras
7422 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7423 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
7425 switch((*i)->GetSpellProto()->SpellIconID)
7427 //Cheat Death
7428 case 2109:
7429 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) )
7431 if(pVictim->GetTypeId() != TYPEID_PLAYER)
7432 continue;
7433 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
7434 if (mod < (*i)->GetModifier()->m_amount)
7435 mod = (*i)->GetModifier()->m_amount;
7436 TakenTotalMod *= (mod+100.0f)/100.0f;
7438 break;
7439 //Mangle
7440 case 2312:
7441 for(int j=0;j<3;j++)
7443 if(GetEffectMechanic(spellProto, j)==MECHANIC_BLEED)
7445 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7446 break;
7449 break;
7453 // Distribute Damage over multiple effects, reduce by AoE
7454 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7456 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7457 for(int j = 0; j < 3; ++j)
7459 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7460 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7462 CastingTime /= 2;
7463 break;
7467 switch(spellProto->SpellFamilyName)
7469 case SPELLFAMILY_MAGE:
7470 // Ignite - do not modify, it is (8*Rank)% damage of procing Spell
7471 if(spellProto->Id==12654)
7473 return pdamage;
7475 // Ice Lance
7476 else if((spellProto->SpellFamilyFlags & 0x20000LL) && spellProto->SpellIconID == 186)
7478 CastingTime /= 3; // applied 1/3 bonuses in case generic target
7479 if(pVictim->isFrozen()) // and compensate this for frozen target.
7480 TakenTotalMod *= 3.0f;
7482 // Pyroblast - 115% of Fire Damage, DoT - 20% of Fire Damage
7483 else if((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 184 )
7485 DotFactor = damagetype == DOT ? 0.2f : 1.0f;
7486 CastingTime = damagetype == DOT ? 3500 : 4025;
7488 // Fireball - 100% of Fire Damage, DoT - 0% of Fire Damage
7489 else if((spellProto->SpellFamilyFlags & 0x1LL) && spellProto->SpellIconID == 185)
7491 CastingTime = 3500;
7492 DotFactor = damagetype == DOT ? 0.0f : 1.0f;
7494 // Molten armor
7495 else if (spellProto->SpellFamilyFlags & 0x0000000800000000LL)
7497 CastingTime = 0;
7499 // Arcane Missiles triggered spell
7500 else if ((spellProto->SpellFamilyFlags & 0x200000LL) && spellProto->SpellIconID == 225)
7502 CastingTime = 1000;
7504 // Blizzard triggered spell
7505 else if ((spellProto->SpellFamilyFlags & 0x80080LL) && spellProto->SpellIconID == 285)
7507 CastingTime = 500;
7509 break;
7510 case SPELLFAMILY_WARLOCK:
7511 // Life Tap
7512 if((spellProto->SpellFamilyFlags & 0x40000LL) && spellProto->SpellIconID == 208)
7514 CastingTime = 2800; // 80% from +shadow damage
7515 DoneTotalMod = 1.0f;
7516 TakenTotalMod = 1.0f;
7518 // Dark Pact
7519 else if((spellProto->SpellFamilyFlags & 0x80000000LL) && spellProto->SpellIconID == 154 && GetPetGUID())
7521 CastingTime = 3360; // 96% from +shadow damage
7522 DoneTotalMod = 1.0f;
7523 TakenTotalMod = 1.0f;
7525 // Soul Fire - 115% of Fire Damage
7526 else if((spellProto->SpellFamilyFlags & 0x8000000000LL) && spellProto->SpellIconID == 184)
7528 CastingTime = 4025;
7530 // Curse of Agony - 120% of Shadow Damage
7531 else if((spellProto->SpellFamilyFlags & 0x0000000400LL) && spellProto->SpellIconID == 544)
7533 DotFactor = 1.2f;
7535 // Drain Mana - 0% of Shadow Damage
7536 else if((spellProto->SpellFamilyFlags & 0x10LL) && spellProto->SpellIconID == 548)
7538 CastingTime = 0;
7540 // Drain Soul 214.3%
7541 else if ((spellProto->SpellFamilyFlags & 0x4000LL) && spellProto->SpellIconID == 113 )
7543 CastingTime = 7500;
7545 // Hellfire
7546 else if ((spellProto->SpellFamilyFlags & 0x40LL) && spellProto->SpellIconID == 937)
7548 CastingTime = damagetype == DOT ? 5000 : 500; // self damage seems to be so
7550 // Unstable Affliction - 180%
7551 else if (spellProto->Id == 31117 && spellProto->SpellIconID == 232)
7553 CastingTime = 6300;
7555 // Corruption 93%
7556 else if ((spellProto->SpellFamilyFlags & 0x2LL) && spellProto->SpellIconID == 313)
7558 DotFactor = 0.93f;
7560 break;
7561 case SPELLFAMILY_PALADIN:
7562 // Consecration - 95% of Holy Damage
7563 if((spellProto->SpellFamilyFlags & 0x20LL) && spellProto->SpellIconID == 51)
7565 DotFactor = 0.95f;
7566 CastingTime = 3500;
7568 // Judgement of Righteousness - 32%
7569 else if (spellProto->SpellFamilyFlags & 0x0000000000000400LL)
7571 CastingTime = 1120;
7573 // Seal of Vengeance - 17% per Fully Stacked Tick - 5 Applications
7574 else if ((spellProto->SpellFamilyFlags & 0x80000000000LL) && spellProto->SpellIconID == 2292)
7576 DotFactor = 0.17f;
7577 CastingTime = 3500;
7579 // Holy shield - 5% of Holy Damage
7580 else if ((spellProto->SpellFamilyFlags & 0x4000000000LL) && spellProto->SpellIconID == 453)
7582 CastingTime = 175;
7584 // Blessing of Sanctuary - 0%
7585 else if ((spellProto->SpellFamilyFlags & 0x10000000LL) && spellProto->SpellIconID == 29)
7587 CastingTime = 0;
7589 break;
7590 case SPELLFAMILY_SHAMAN:
7591 // totem attack
7592 if (spellProto->SpellFamilyFlags & 0x000040000000LL)
7594 if (spellProto->SpellIconID == 33) // Fire Nova totem attack must be 21.4%(untested)
7595 CastingTime = 749; // ignore CastingTime and use as modifier
7596 else if (spellProto->SpellIconID == 680) // Searing Totem attack 8%
7597 CastingTime = 280; // ignore CastingTime and use as modifier
7598 else if (spellProto->SpellIconID == 37) // Magma totem attack must be 6.67%(untested)
7599 CastingTime = 234; // ignore CastingTimePenalty and use as modifier
7601 // Lightning Shield (and proc shield from T2 8 pieces bonus ) 33% per charge
7602 else if( (spellProto->SpellFamilyFlags & 0x00000000400LL) || spellProto->Id == 23552)
7603 CastingTime = 1155; // ignore CastingTimePenalty and use as modifier
7604 break;
7605 case SPELLFAMILY_PRIEST:
7606 // Mana Burn - 0% of Shadow Damage
7607 if((spellProto->SpellFamilyFlags & 0x10LL) && spellProto->SpellIconID == 212)
7609 CastingTime = 0;
7611 // Mind Flay - 59% of Shadow Damage
7612 else if((spellProto->SpellFamilyFlags & 0x800000LL) && spellProto->SpellIconID == 548)
7614 CastingTime = 2065;
7616 // Holy Fire - 86.71%, DoT - 16.5%
7617 else if ((spellProto->SpellFamilyFlags & 0x100000LL) && spellProto->SpellIconID == 156)
7619 DotFactor = damagetype == DOT ? 0.165f : 1.0f;
7620 CastingTime = damagetype == DOT ? 3500 : 3035;
7622 // Shadowguard - 28% per charge
7623 else if ((spellProto->SpellFamilyFlags & 0x2000000LL) && spellProto->SpellIconID == 19)
7625 CastingTime = 980;
7627 // Touch of Weakeness - 10%
7628 else if ((spellProto->SpellFamilyFlags & 0x80000LL) && spellProto->SpellIconID == 1591)
7630 CastingTime = 350;
7632 // Reflective Shield (back damage) - 0% (other spells fit to check not have damage effects/auras)
7633 else if (spellProto->SpellFamilyFlags == 0 && spellProto->SpellIconID == 566)
7635 CastingTime = 0;
7637 // Holy Nova - 14%
7638 else if ((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 1874)
7640 CastingTime = 500;
7642 break;
7643 case SPELLFAMILY_DRUID:
7644 // Hurricane triggered spell
7645 if((spellProto->SpellFamilyFlags & 0x400000LL) && spellProto->SpellIconID == 220)
7647 CastingTime = 500;
7649 break;
7650 case SPELLFAMILY_WARRIOR:
7651 case SPELLFAMILY_HUNTER:
7652 case SPELLFAMILY_ROGUE:
7653 CastingTime = 0;
7654 break;
7655 default:
7656 break;
7659 float LvlPenalty = CalculateLevelPenalty(spellProto);
7661 // Spellmod SpellDamage
7662 float SpellModSpellDamage = 100.0f;
7664 if(Player* modOwner = GetSpellModOwner())
7665 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7667 SpellModSpellDamage /= 100.0f;
7669 float DoneActualBenefit = DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * SpellModSpellDamage * LvlPenalty;
7670 float TakenActualBenefit = TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
7672 float tmpDamage = (float(pdamage)+DoneActualBenefit)*DoneTotalMod;
7674 // Add flat bonus from spell damage versus
7675 tmpDamage += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7677 // apply spellmod to Done damage
7678 if(Player* modOwner = GetSpellModOwner())
7679 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7681 tmpDamage = (tmpDamage+TakenActualBenefit)*TakenTotalMod;
7683 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7684 tmpDamage *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7686 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7689 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7691 int32 DoneAdvertisedBenefit = 0;
7693 // ..done
7694 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7695 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7696 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7697 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7698 // -1 == any item class (not wand then)
7699 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7700 // 0 == any inventory type (not wand then)
7701 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7703 if (GetTypeId() == TYPEID_PLAYER)
7705 // Base value
7706 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellDamageBonus();
7708 // Damage bonus from stats
7709 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7710 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7712 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7714 // stat used stored in miscValueB for this aura
7715 Stats usedStat = Stats((*i)->GetMiscBValue());
7716 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7719 // ... and attack power
7720 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7721 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7722 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7723 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7726 return DoneAdvertisedBenefit;
7729 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7731 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7733 int32 TakenAdvertisedBenefit = 0;
7734 // ..done (for creature type by mask) in taken
7735 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7736 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7737 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7738 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7740 // ..taken
7741 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7742 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7743 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7744 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7746 return TakenAdvertisedBenefit;
7749 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7751 // not critting spell
7752 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7753 return false;
7755 float crit_chance = 0.0f;
7756 switch(spellProto->DmgClass)
7758 case SPELL_DAMAGE_CLASS_NONE:
7759 return false;
7760 case SPELL_DAMAGE_CLASS_MAGIC:
7762 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7763 crit_chance = 0.0f;
7764 // For other schools
7765 else if (GetTypeId() == TYPEID_PLAYER)
7766 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7767 else
7769 crit_chance = m_baseSpellCritChance;
7770 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7772 // taken
7773 if (pVictim && !IsPositiveSpell(spellProto->Id))
7775 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7776 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7777 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7778 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7779 // Modify by player victim resilience
7780 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7781 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7782 // scripted (increase crit chance ... against ... target by x%
7783 if(pVictim->isFrozen()) // Shatter
7785 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7786 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7788 switch((*i)->GetModifier()->m_miscvalue)
7790 case 849: crit_chance+= 17.0f; break; //Shatter Rank 1
7791 case 910: crit_chance+= 34.0f; break; //Shatter Rank 2
7792 case 911: crit_chance+= 50.0f; break; //Shatter Rank 3
7796 // Glyph of Shadowburn
7797 if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK &&
7798 spellProto->SpellFamilyFlags & 0x0000000000000080LL &&
7799 pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7801 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7802 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7803 if((*i)->GetModifier()->m_miscvalue == 7917)
7804 crit_chance+=(*i)->GetModifier()->m_amount;
7806 // Sacred Shield
7807 if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN &&
7808 spellProto->SpellFamilyFlags & 0x0000000040000000LL)
7810 Aura *aura = pVictim->GetDummyAura(58597);
7811 if (aura && aura->GetCasterGUID() == GetGUID())
7812 crit_chance+=aura->GetModifier()->m_amount;
7815 break;
7817 case SPELL_DAMAGE_CLASS_MELEE:
7818 case SPELL_DAMAGE_CLASS_RANGED:
7820 if (pVictim)
7822 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7823 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7825 break;
7827 default:
7828 return false;
7830 // percent done
7831 // only players use intelligence for critical chance computations
7832 if(Player* modOwner = GetSpellModOwner())
7833 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7835 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7836 if (roll_chance_f(crit_chance))
7837 return true;
7838 return false;
7841 uint32 Unit::SpellCriticalBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7843 // Calculate critical bonus
7844 int32 crit_bonus;
7845 switch(spellProto->DmgClass)
7847 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7848 case SPELL_DAMAGE_CLASS_RANGED:
7849 // TODO: write here full calculation for melee/ranged spells
7850 crit_bonus = damage;
7851 break;
7852 default:
7853 crit_bonus = damage / 2; // for spells is 50%
7854 break;
7857 // adds additional damage to crit_bonus (from talents)
7858 if(Player* modOwner = GetSpellModOwner())
7859 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
7861 if(pVictim)
7863 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7864 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7867 if(crit_bonus > 0)
7868 damage += crit_bonus;
7870 return damage;
7873 uint32 Unit::SpellHealingBonus(SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, Unit *pVictim)
7875 // For totems get healing bonus from owner (statue isn't totem in fact)
7876 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7877 if(Unit* owner = GetOwner())
7878 return owner->SpellHealingBonus(spellProto, healamount, damagetype, pVictim);
7880 // Healing Done
7882 // These Spells are doing fixed amount of healing (TODO found less hack-like check)
7883 if (spellProto->Id == 15290 || spellProto->Id == 39373 ||
7884 spellProto->Id == 33778 || spellProto->Id == 379 ||
7885 spellProto->Id == 38395 || spellProto->Id == 40972)
7886 return healamount;
7888 int32 AdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
7889 uint32 CastingTime = GetSpellCastTime(spellProto);
7891 // Healing Taken
7892 AdvertisedBenefit += SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7894 // Blessing of Light dummy effects healing taken from Holy Light and Flash of Light
7895 if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && (spellProto->SpellFamilyFlags & 0x00000000C0000000LL))
7897 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
7898 for(AuraList::const_iterator i = mDummyAuras.begin();i != mDummyAuras.end(); ++i)
7900 if((*i)->GetSpellProto()->SpellVisual[0] == 9180)
7902 // Flash of Light
7903 if ((spellProto->SpellFamilyFlags & 0x0000000040000000LL) && (*i)->GetEffIndex() == 1)
7904 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7905 // Holy Light
7906 else if ((spellProto->SpellFamilyFlags & 0x0000000080000000LL) && (*i)->GetEffIndex() == 0)
7907 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
7912 float ActualBenefit = 0.0f;
7914 if (AdvertisedBenefit != 0)
7916 // Healing over Time spells
7917 float DotFactor = 1.0f;
7918 if(damagetype == DOT)
7920 int32 DotDuration = GetSpellDuration(spellProto);
7921 if(DotDuration > 0)
7923 // 200% limit
7924 if(DotDuration > 30000) DotDuration = 30000;
7925 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7926 int x = 0;
7927 for(int j = 0; j < 3; j++)
7929 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7930 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_HEAL ||
7931 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7933 x = j;
7934 break;
7937 int DotTicks = 6;
7938 if(spellProto->EffectAmplitude[x] != 0)
7939 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7940 if(DotTicks)
7941 AdvertisedBenefit /= DotTicks;
7945 // distribute healing to all effects, reduce AoE damage
7946 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7948 // 0% bonus for damage and healing spells for leech spells from healing bonus
7949 for(int j = 0; j < 3; ++j)
7951 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7952 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7954 CastingTime = 0;
7955 break;
7959 // Exception
7960 switch (spellProto->SpellFamilyName)
7962 case SPELLFAMILY_SHAMAN:
7963 // Healing stream from totem (add 6% per tick from hill bonus owner)
7964 if (spellProto->SpellFamilyFlags & 0x000000002000LL)
7965 CastingTime = 210;
7966 // Earth Shield 30% per charge
7967 else if (spellProto->SpellFamilyFlags & 0x40000000000LL)
7968 CastingTime = 1050;
7969 break;
7970 case SPELLFAMILY_DRUID:
7971 // Lifebloom
7972 if (spellProto->SpellFamilyFlags & 0x1000000000LL)
7974 CastingTime = damagetype == DOT ? 3500 : 1200;
7975 DotFactor = damagetype == DOT ? 0.519f : 1.0f;
7977 // Tranquility triggered spell
7978 else if (spellProto->SpellFamilyFlags & 0x80LL)
7979 CastingTime = 667;
7980 // Rejuvenation
7981 else if (spellProto->SpellFamilyFlags & 0x10LL)
7982 DotFactor = 0.845f;
7983 // Regrowth
7984 else if (spellProto->SpellFamilyFlags & 0x40LL)
7986 DotFactor = damagetype == DOT ? 0.705f : 1.0f;
7987 CastingTime = damagetype == DOT ? 3500 : 1010;
7989 break;
7990 case SPELLFAMILY_PRIEST:
7991 // Holy Nova - 14%
7992 if ((spellProto->SpellFamilyFlags & 0x8000000LL) && spellProto->SpellIconID == 1874)
7993 CastingTime = 500;
7994 break;
7995 case SPELLFAMILY_PALADIN:
7996 // Seal and Judgement of Light
7997 if ( spellProto->SpellFamilyFlags & 0x100040000LL )
7998 CastingTime = 0;
7999 break;
8000 case SPELLFAMILY_WARRIOR:
8001 case SPELLFAMILY_ROGUE:
8002 case SPELLFAMILY_HUNTER:
8003 CastingTime = 0;
8004 break;
8007 float LvlPenalty = CalculateLevelPenalty(spellProto);
8009 // Spellmod SpellDamage
8010 float SpellModSpellDamage = 100.0f;
8012 if(Player* modOwner = GetSpellModOwner())
8013 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
8015 SpellModSpellDamage /= 100.0f;
8017 ActualBenefit = (float)AdvertisedBenefit * ((float)CastingTime / 3500.0f) * DotFactor * SpellModSpellDamage * LvlPenalty;
8020 // use float as more appropriate for negative values and percent applying
8021 float heal = healamount + ActualBenefit;
8023 // TODO: check for ALL/SPELLS type
8024 // Healing done percent
8025 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
8026 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
8027 heal *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
8029 // apply spellmod to Done amount
8030 if(Player* modOwner = GetSpellModOwner())
8031 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8033 // Healing Wave cast
8034 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
8036 // Search for Healing Way on Victim (stack up to 3 time)
8037 int32 pctMod = 0;
8038 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8039 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8040 if((*itr)->GetId() == 29203)
8041 pctMod += (*itr)->GetModifier()->m_amount;
8042 // Apply bonus
8043 if (pctMod)
8044 heal = heal * (100 + pctMod) / 100;
8047 // Healing taken percent
8048 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8049 if(minval)
8050 heal *= (100.0f + minval) / 100.0f;
8052 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8053 if(maxval)
8054 heal *= (100.0f + maxval) / 100.0f;
8056 if (heal < 0) heal = 0;
8058 return uint32(heal);
8061 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8063 int32 AdvertisedBenefit = 0;
8065 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8066 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8067 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8068 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8070 // Healing bonus of spirit, intellect and strength
8071 if (GetTypeId() == TYPEID_PLAYER)
8073 // Base value
8074 AdvertisedBenefit +=((Player*)this)->GetBaseSpellHealingBonus();
8076 // Healing bonus from stats
8077 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8078 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8080 // stat used dependent from misc value (stat index)
8081 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8082 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8085 // ... and attack power
8086 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8087 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8088 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8089 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8091 return AdvertisedBenefit;
8094 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8096 int32 AdvertisedBenefit = 0;
8097 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8098 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8099 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8100 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8101 return AdvertisedBenefit;
8104 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8106 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8107 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8108 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8109 if(itr->type & shoolMask)
8110 return true;
8112 //If m_immuneToDamage type contain magic, IMMUNE damage.
8113 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8114 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8115 if(itr->type & shoolMask)
8116 return true;
8118 return false;
8121 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8123 if (!spellInfo)
8124 return false;
8126 //FIX ME this hack: don't get feared if stunned
8127 if (spellInfo->Mechanic == MECHANIC_FEAR )
8129 if ( hasUnitState(UNIT_STAT_STUNNED) )
8130 return true;
8133 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8134 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8135 if(itr->type == spellInfo->Dispel)
8136 return true;
8138 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8139 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8141 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8142 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8143 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8144 (itr->type & GetSpellSchoolMask(spellInfo)) )
8145 return true;
8148 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8149 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8151 if(itr->type == spellInfo->Mechanic)
8153 return true;
8157 return false;
8160 bool Unit::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
8162 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8163 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8164 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8165 if(itr->type == effect)
8166 return true;
8168 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8169 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8170 if(itr->type == mechanic)
8171 return true;
8173 return false;
8176 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8178 if(!spellInfo)
8179 return false;
8181 uint32 family = spellInfo->SpellFamilyName;
8182 uint64 flags = spellInfo->SpellFamilyFlags;
8184 if((family == 5 && flags == 256) || //Searing Pain
8185 (family == 6 && flags == 8192) || //Mind Blast
8186 (family == 11 && flags == 1048576)) //Earth Shock
8187 return true;
8189 return false;
8192 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8194 if(!pVictim)
8195 return;
8197 if(*pdamage == 0)
8198 return;
8200 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8202 // Taken/Done fixed damage bonus auras
8203 int32 DoneFlatBenefit = 0;
8204 int32 TakenFlatBenefit = 0;
8206 // ..done (for creature type by mask) in taken
8207 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8208 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8209 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8210 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
8212 // ..done
8213 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
8215 // ..done (base at attack power for marked target and base at attack power for creature type)
8216 int32 APbonus = 0;
8217 if(attType == RANGED_ATTACK)
8219 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
8221 // ..done (base at attack power and creature type)
8222 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
8223 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8224 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8225 APbonus += (*i)->GetModifier()->m_amount;
8227 else
8229 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
8231 // ..done (base at attack power and creature type)
8232 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
8233 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8234 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8235 APbonus += (*i)->GetModifier()->m_amount;
8238 if (APbonus!=0) // Can be negative
8240 bool normalized = false;
8241 if(spellProto)
8243 for (uint8 i = 0; i<3;i++)
8245 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
8247 normalized = true;
8248 break;
8253 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
8256 // ..taken
8257 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8258 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8259 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8260 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
8262 if(attType!=RANGED_ATTACK)
8263 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
8264 else
8265 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
8267 // Done/Taken total percent damage auras
8268 float DoneTotalMod = 1;
8269 float TakenTotalMod = 1;
8271 // ..done
8272 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
8273 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
8275 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8276 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8277 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8278 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8280 // ..taken
8281 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8282 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8283 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8284 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8286 // .. taken pct: dummy auras
8287 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8288 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
8290 switch((*i)->GetSpellProto()->SpellIconID)
8292 //Cheat Death
8293 case 2109:
8294 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
8296 if(pVictim->GetTypeId() != TYPEID_PLAYER)
8297 continue;
8298 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
8299 if (mod < (*i)->GetModifier()->m_amount)
8300 mod = (*i)->GetModifier()->m_amount;
8301 TakenTotalMod *= (mod+100.0f)/100.0f;
8303 break;
8304 //Mangle
8305 case 2312:
8306 if(spellProto==NULL)
8307 break;
8308 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
8309 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
8310 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8311 break;
8315 // .. taken pct: class scripts
8316 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8317 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
8319 switch((*i)->GetMiscValue())
8321 case 6427: case 6428: // Dirty Deeds
8322 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8324 Aura* eff0 = GetAura((*i)->GetId(),0);
8325 if(!eff0 || (*i)->GetEffIndex()!=1)
8327 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
8328 continue;
8331 // effect 0 have expected value but in negative state
8332 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
8334 break;
8338 if(attType != RANGED_ATTACK)
8340 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
8341 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
8342 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8344 else
8346 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
8347 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
8348 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8351 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
8353 // apply spellmod to Done damage
8354 if(spellProto)
8356 if(Player* modOwner = GetSpellModOwner())
8357 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
8360 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
8362 // bonus result can be negative
8363 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
8366 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
8368 if (apply)
8370 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
8372 next = itr; ++next;
8373 if(itr->type == type)
8375 m_spellImmune[op].erase(itr);
8376 next = m_spellImmune[op].begin();
8379 SpellImmune Immune;
8380 Immune.spellId = spellId;
8381 Immune.type = type;
8382 m_spellImmune[op].push_back(Immune);
8384 else
8386 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
8388 if(itr->spellId == spellId)
8390 m_spellImmune[op].erase(itr);
8391 break;
8398 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
8400 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
8402 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
8403 RemoveAurasWithDispelType(type);
8406 float Unit::GetWeaponProcChance() const
8408 // normalized proc chance for weapon attack speed
8409 // (odd formula...)
8410 if(isAttackReady(BASE_ATTACK))
8411 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
8412 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
8413 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
8414 return 0;
8417 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
8419 // proc per minute chance calculation
8420 if (PPM <= 0) return 0.0f;
8421 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
8422 return result;
8425 void Unit::Mount(uint32 mount)
8427 if(!mount)
8428 return;
8430 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
8432 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
8434 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8436 // unsummon pet
8437 if(GetTypeId() == TYPEID_PLAYER)
8439 Pet* pet = GetPet();
8440 if(pet)
8442 if(pet->isControlled())
8444 ((Player*)this)->SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
8445 ((Player*)this)->SetOldPetSpell(pet->GetUInt32Value(UNIT_CREATED_BY_SPELL));
8448 ((Player*)this)->RemovePet(NULL,PET_SAVE_NOT_IN_SLOT);
8450 else
8451 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8455 void Unit::Unmount()
8457 if(!IsMounted())
8458 return;
8460 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8462 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8463 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8465 // only resummon old pet if the player is already added to a map
8466 // this prevents adding a pet to a not created map which would otherwise cause a crash
8467 // (it could probably happen when logging in after a previous crash)
8468 if(GetTypeId() == TYPEID_PLAYER && IsInWorld() && ((Player*)this)->GetTemporaryUnsummonedPetNumber() && isAlive())
8470 Pet* NewPet = new Pet;
8471 if(!NewPet->LoadPetFromDB((Player*)this, 0, ((Player*)this)->GetTemporaryUnsummonedPetNumber(), true))
8472 delete NewPet;
8474 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8478 void Unit::SetInCombatWith(Unit* enemy)
8480 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8481 if(eOwner->IsPvP())
8483 SetInCombatState(true);
8484 return;
8487 //check for duel
8488 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8490 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8491 if(((Player const*)eOwner)->duel->opponent == myOwner)
8493 SetInCombatState(true);
8494 return;
8497 SetInCombatState(false);
8500 void Unit::SetInCombatState(bool PvP)
8502 // only alive units can be in combat
8503 if(!isAlive())
8504 return;
8506 if(PvP)
8507 m_CombatTimer = 5000;
8508 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8510 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8511 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8514 void Unit::ClearInCombat()
8516 m_CombatTimer = 0;
8517 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8519 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8520 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8522 // Player's state will be cleared in Player::UpdateContestedPvP
8523 if(GetTypeId()!=TYPEID_PLAYER)
8524 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8527 bool Unit::isTargetableForAttack() const
8529 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8530 return false;
8532 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8533 return false;
8535 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8538 int32 Unit::ModifyHealth(int32 dVal)
8540 int32 gain = 0;
8542 if(dVal==0)
8543 return 0;
8545 int32 curHealth = (int32)GetHealth();
8547 int32 val = dVal + curHealth;
8548 if(val <= 0)
8550 SetHealth(0);
8551 return -curHealth;
8554 int32 maxHealth = (int32)GetMaxHealth();
8556 if(val < maxHealth)
8558 SetHealth(val);
8559 gain = val - curHealth;
8561 else if(curHealth != maxHealth)
8563 SetHealth(maxHealth);
8564 gain = maxHealth - curHealth;
8567 return gain;
8570 int32 Unit::ModifyPower(Powers power, int32 dVal)
8572 int32 gain = 0;
8574 if(dVal==0)
8575 return 0;
8577 int32 curPower = (int32)GetPower(power);
8579 int32 val = dVal + curPower;
8580 if(val <= 0)
8582 SetPower(power,0);
8583 return -curPower;
8586 int32 maxPower = (int32)GetMaxPower(power);
8588 if(val < maxPower)
8590 SetPower(power,val);
8591 gain = val - curPower;
8593 else if(curPower != maxPower)
8595 SetPower(power,maxPower);
8596 gain = maxPower - curPower;
8599 return gain;
8602 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8604 if(!u)
8605 return false;
8607 // Always can see self
8608 if (u==this)
8609 return true;
8611 // player visible for other player if not logout and at same transport
8612 // including case when player is out of world
8613 bool at_same_transport =
8614 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8615 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8616 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8617 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8619 // not in world
8620 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8621 return false;
8623 // forbidden to seen (at GM respawn command)
8624 if(m_Visibility==VISIBILITY_RESPAWN)
8625 return false;
8627 // always seen by owner
8628 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8629 return true;
8631 // Grid dead/alive checks
8632 if( u->GetTypeId()==TYPEID_PLAYER)
8634 // non visible at grid for any stealth state
8635 if(!IsVisibleInGridForPlayer((Player *)u))
8636 return false;
8638 // if player is dead then he can't detect anyone in any cases
8639 if(!u->isAlive())
8640 detect = false;
8642 else
8644 // all dead creatures/players not visible for any creatures
8645 if(!u->isAlive() || !isAlive())
8646 return false;
8649 // different visible distance checks
8650 if(u->isInFlight()) // what see player in flight
8652 // use object grey distance for all (only see objects any way)
8653 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8654 return false;
8656 else if(!isAlive()) // distance for show body
8658 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8659 return false;
8661 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8663 if(u->GetTypeId()==TYPEID_PLAYER)
8665 // Players far than max visible distance for player or not in our map are not visible too
8666 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8667 return false;
8669 else
8671 // Units far than max visible distance for creature or not in our map are not visible too
8672 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8673 return false;
8676 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8678 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8679 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8680 return false;
8682 else // distance for show creature
8684 // Units far than max visible distance for creature or not in our map are not visible too
8685 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8686 return false;
8689 // Visible units, always are visible for all units, except for units under invisibility
8690 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0)
8691 return true;
8693 // GMs see any players, not higher GMs and all units
8694 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8696 if(GetTypeId() == TYPEID_PLAYER)
8697 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8698 else
8699 return true;
8702 // non faction visibility non-breakable for non-GMs
8703 if (m_Visibility == VISIBILITY_OFF)
8704 return false;
8706 // raw invisibility
8707 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8709 // detectable invisibility case
8710 if( invisible && (
8711 // Invisible units, always are visible for units under same invisibility type
8712 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8713 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8714 u->canDetectInvisibilityOf(this) ||
8715 // Units that can detect invisibility always are visible for units that can be detected
8716 canDetectInvisibilityOf(u) ))
8718 invisible = false;
8721 // special cases for always overwrite invisibility/stealth
8722 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8724 // non-hostile case
8725 if (!u->IsHostileTo(this))
8727 // 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)
8728 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8730 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8731 return true;
8733 // else apply same rules as for hostile case (detecting check for stealth)
8736 // hostile case
8737 else
8739 // Hunter mark functionality
8740 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8741 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8742 if((*iter)->GetCasterGUID()==u->GetGUID())
8743 return true;
8745 // else apply detecting check for stealth
8748 // none other cases for detect invisibility, so invisible
8749 if(invisible)
8750 return false;
8752 // else apply stealth detecting check
8755 // unit got in stealth in this moment and must ignore old detected state
8756 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8757 return false;
8759 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8760 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8761 return true;
8763 // NOW ONLY STEALTH CASE
8765 // stealth and detected and visible for some seconds
8766 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8767 return true;
8769 //if in non-detect mode then invisible for unit
8770 if (!detect)
8771 return false;
8773 // Special cases
8775 // If is attacked then stealth is lost, some creature can use stealth too
8776 if( !getAttackers().empty() )
8777 return true;
8779 // If there is collision rogue is seen regardless of level difference
8780 // TODO: check sizes in DB
8781 float distance = GetDistance(u);
8782 if (distance < 0.24f)
8783 return true;
8785 //If a mob or player is stunned he will not be able to detect stealth
8786 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8787 return false;
8789 // Creature can detect target only in aggro radius
8790 if(u->GetTypeId() != TYPEID_PLAYER)
8792 //Always invisible from back and out of aggro range
8793 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
8794 if(!isInFront)
8795 return false;
8797 else
8799 //Always invisible from back
8800 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
8801 if(!isInFront)
8802 return false;
8805 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
8806 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
8808 //Calculation if target is in front
8810 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
8811 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
8813 //Visible distance is modified by
8814 //-Level Diff (every level diff = 1.0f in visible distance)
8815 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
8817 //This allows to check talent tree and will add addition stealth dependent on used points)
8818 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
8819 if(stealthMod < 0)
8820 stealthMod = 0;
8822 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
8823 //based on wowwiki every 5 mod we have 1 more level diff in calculation
8824 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
8826 if(distance > visibleDistance)
8827 return false;
8830 // Now check is target visible with LoS
8831 float ox,oy,oz;
8832 u->GetPosition(ox,oy,oz);
8833 return IsWithinLOS(ox,oy,oz);
8836 void Unit::SetVisibility(UnitVisibility x)
8838 m_Visibility = x;
8840 if(IsInWorld())
8842 Map *m = GetMap();
8844 if(GetTypeId()==TYPEID_PLAYER)
8845 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8846 else
8847 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8851 bool Unit::canDetectInvisibilityOf(Unit const* u) const
8853 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
8855 for(uint32 i = 0; i < 10; ++i)
8857 if(((1 << i) & mask)==0)
8858 continue;
8860 // find invisibility level
8861 uint32 invLevel = 0;
8862 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
8863 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
8864 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
8865 invLevel = (*itr)->GetModifier()->m_amount;
8867 // find invisibility detect level
8868 uint32 detectLevel = 0;
8869 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
8870 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
8871 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
8872 detectLevel = (*itr)->GetModifier()->m_amount;
8874 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
8876 detectLevel = ((Player*)this)->GetDrunkValue();
8879 if(invLevel <= detectLevel)
8880 return true;
8884 return false;
8887 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
8889 int32 main_speed_mod = 0;
8890 float stack_bonus = 1.0f;
8891 float non_stack_bonus = 1.0f;
8893 switch(mtype)
8895 case MOVE_WALK:
8896 return;
8897 case MOVE_RUN:
8899 if (IsMounted()) // Use on mount auras
8901 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
8902 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
8903 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
8905 else
8907 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
8908 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
8909 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
8911 break;
8913 case MOVE_RUN_BACK:
8914 return;
8915 case MOVE_SWIM:
8917 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
8918 break;
8920 case MOVE_SWIM_BACK:
8921 return;
8922 case MOVE_FLIGHT:
8924 if (IsMounted()) // Use on mount auras
8925 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
8926 else // Use not mount (shapeshift for example) auras (should stack)
8927 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
8928 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
8929 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
8930 break;
8932 case MOVE_FLIGHT_BACK:
8933 return;
8934 default:
8935 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
8936 return;
8939 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
8940 // now we ready for speed calculation
8941 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
8943 switch(mtype)
8945 case MOVE_RUN:
8946 case MOVE_SWIM:
8947 case MOVE_FLIGHT:
8949 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
8950 // TODO: possible affect only on MOVE_RUN
8951 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
8953 // Use speed from aura
8954 float max_speed = normalization / baseMoveSpeed[mtype];
8955 if (speed > max_speed)
8956 speed = max_speed;
8958 break;
8960 default:
8961 break;
8964 // Apply strongest slow aura mod to speed
8965 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
8966 if (slow)
8967 speed *=(100.0f + slow)/100.0f;
8968 SetSpeed(mtype, speed, forced);
8971 float Unit::GetSpeed( UnitMoveType mtype ) const
8973 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
8976 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
8978 if (rate < 0)
8979 rate = 0.0f;
8981 // Update speed only on change
8982 if (m_speed_rate[mtype] == rate)
8983 return;
8985 m_speed_rate[mtype] = rate;
8987 propagateSpeedChange();
8989 WorldPacket data;
8990 if(!forced)
8992 switch(mtype)
8994 case MOVE_WALK:
8995 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
8996 break;
8997 case MOVE_RUN:
8998 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
8999 break;
9000 case MOVE_RUN_BACK:
9001 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9002 break;
9003 case MOVE_SWIM:
9004 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9005 break;
9006 case MOVE_SWIM_BACK:
9007 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9008 break;
9009 case MOVE_TURN_RATE:
9010 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9011 break;
9012 case MOVE_FLIGHT:
9013 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9014 break;
9015 case MOVE_FLIGHT_BACK:
9016 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9017 break;
9018 case MOVE_PITCH_RATE:
9019 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9020 break;
9021 default:
9022 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9023 return;
9026 data.append(GetPackGUID());
9027 data << uint32(0); // movement flags
9028 data << uint16(0); // unk flags
9029 data << uint32(getMSTime());
9030 data << float(GetPositionX());
9031 data << float(GetPositionY());
9032 data << float(GetPositionZ());
9033 data << float(GetOrientation());
9034 data << uint32(0); // fall time
9035 data << float(GetSpeed(mtype));
9036 SendMessageToSet( &data, true );
9038 else
9040 if(GetTypeId() == TYPEID_PLAYER)
9042 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9043 // and do it only for real sent packets and use run for run/mounted as client expected
9044 ++((Player*)this)->m_forced_speed_changes[mtype];
9047 switch(mtype)
9049 case MOVE_WALK:
9050 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9051 break;
9052 case MOVE_RUN:
9053 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9054 break;
9055 case MOVE_RUN_BACK:
9056 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9057 break;
9058 case MOVE_SWIM:
9059 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9060 break;
9061 case MOVE_SWIM_BACK:
9062 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9063 break;
9064 case MOVE_TURN_RATE:
9065 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9066 break;
9067 case MOVE_FLIGHT:
9068 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9069 break;
9070 case MOVE_FLIGHT_BACK:
9071 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9072 break;
9073 case MOVE_PITCH_RATE:
9074 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9075 break;
9076 default:
9077 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9078 return;
9080 data.append(GetPackGUID());
9081 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9082 if (mtype == MOVE_RUN)
9083 data << uint8(0); // new 2.1.0
9084 data << float(GetSpeed(mtype));
9085 SendMessageToSet( &data, true );
9087 if(Pet* pet = GetPet())
9088 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9091 void Unit::SetHover(bool on)
9093 if(on)
9094 CastSpell(this,11010,true);
9095 else
9096 RemoveAurasDueToSpell(11010);
9099 void Unit::setDeathState(DeathState s)
9101 if (s != ALIVE && s!= JUST_ALIVED)
9103 CombatStop();
9104 DeleteThreatList();
9105 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9107 if(IsNonMeleeSpellCasted(false))
9108 InterruptNonMeleeSpells(false);
9111 if (s == JUST_DIED)
9113 RemoveAllAurasOnDeath();
9114 UnsummonAllTotems();
9116 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9117 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9118 // remove aurastates allowing special moves
9119 ClearAllReactives();
9120 ClearDiminishings();
9122 else if(s == JUST_ALIVED)
9124 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9127 if (m_deathState != ALIVE && s == ALIVE)
9129 //_ApplyAllAuraMods();
9131 m_deathState = s;
9134 /*########################################
9135 ######## ########
9136 ######## AGGRO SYSTEM ########
9137 ######## ########
9138 ########################################*/
9139 bool Unit::CanHaveThreatList() const
9141 // only creatures can have threat list
9142 if( GetTypeId() != TYPEID_UNIT )
9143 return false;
9145 // only alive units can have threat list
9146 if( !isAlive() )
9147 return false;
9149 // totems can not have threat list
9150 if( ((Creature*)this)->isTotem() )
9151 return false;
9153 // vehicles can not have threat list
9154 if( ((Creature*)this)->isVehicle() )
9155 return false;
9157 // pets can not have a threat list, unless they are controlled by a creature
9158 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9159 return false;
9161 return true;
9164 //======================================================================
9166 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9168 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9169 return threat;
9171 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9173 return threat * m_threatModifier[school];
9176 //======================================================================
9178 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9180 // Only mobs can manage threat lists
9181 if(CanHaveThreatList())
9182 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9185 //======================================================================
9187 void Unit::DeleteThreatList()
9189 m_ThreatManager.clearReferences();
9192 //======================================================================
9194 void Unit::TauntApply(Unit* taunter)
9196 assert(GetTypeId()== TYPEID_UNIT);
9198 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9199 return;
9201 if(!CanHaveThreatList())
9202 return;
9204 Unit *target = getVictim();
9205 if(target && target == taunter)
9206 return;
9208 SetInFront(taunter);
9209 if (((Creature*)this)->AI())
9210 ((Creature*)this)->AI()->AttackStart(taunter);
9212 m_ThreatManager.tauntApply(taunter);
9215 //======================================================================
9217 void Unit::TauntFadeOut(Unit *taunter)
9219 assert(GetTypeId()== TYPEID_UNIT);
9221 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9222 return;
9224 if(!CanHaveThreatList())
9225 return;
9227 Unit *target = getVictim();
9228 if(!target || target != taunter)
9229 return;
9231 if(m_ThreatManager.isThreatListEmpty())
9233 if(((Creature*)this)->AI())
9234 ((Creature*)this)->AI()->EnterEvadeMode();
9235 return;
9238 m_ThreatManager.tauntFadeOut(taunter);
9239 target = m_ThreatManager.getHostilTarget();
9241 if (target && target != taunter)
9243 SetInFront(target);
9244 if (((Creature*)this)->AI())
9245 ((Creature*)this)->AI()->AttackStart(target);
9249 //======================================================================
9251 bool Unit::SelectHostilTarget()
9253 //function provides main threat functionality
9254 //next-victim-selection algorithm and evade mode are called
9255 //threat list sorting etc.
9257 assert(GetTypeId()== TYPEID_UNIT);
9259 //This function only useful once AI has been initialized
9260 if (!((Creature*)this)->AI())
9261 return false;
9263 Unit* target = NULL;
9265 // First checking if we have some taunt on us
9266 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
9267 if ( !tauntAuras.empty() )
9269 Unit* caster;
9271 // The last taunt aura caster is alive an we are happy to attack him
9272 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
9273 return true;
9274 else if (tauntAuras.size() > 1)
9276 // We do not have last taunt aura caster but we have more taunt auras,
9277 // so find first available target
9279 // Auras are pushed_back, last caster will be on the end
9280 AuraList::const_iterator aura = --tauntAuras.end();
9283 --aura;
9284 if ( (caster = (*aura)->GetCaster()) &&
9285 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
9287 target = caster;
9288 break;
9290 }while (aura != tauntAuras.begin());
9294 if ( !target && !m_ThreatManager.isThreatListEmpty() )
9295 // No taunt aura or taunt aura caster is dead standart target selection
9296 target = m_ThreatManager.getHostilTarget();
9298 if(target)
9300 if(!hasUnitState(UNIT_STAT_STUNNED))
9301 SetInFront(target);
9302 ((Creature*)this)->AI()->AttackStart(target);
9303 return true;
9306 // no target but something prevent go to evade mode
9307 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
9308 return false;
9310 // last case when creature don't must go to evade mode:
9311 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
9312 // for example at owner command to pet attack some far away creature
9313 // Note: creature not have targeted movement generator but have attacker in this case
9314 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
9316 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
9318 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
9319 return false;
9323 // enter in evade mode in other case
9324 ((Creature*)this)->AI()->EnterEvadeMode();
9326 return false;
9329 //======================================================================
9330 //======================================================================
9331 //======================================================================
9333 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
9335 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9337 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9339 int32 level = int32(getLevel());
9340 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
9341 level = (int32)spellProto->maxLevel;
9342 else if (level < (int32)spellProto->baseLevel)
9343 level = (int32)spellProto->baseLevel;
9344 level-= (int32)spellProto->spellLevel;
9346 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
9347 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
9348 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
9349 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
9350 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
9352 // range can have possitive and negative values, so order its for irand
9353 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
9354 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
9355 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
9357 int32 value = basePoints + randvalue;
9358 //random damage
9359 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
9360 value += (int32)(comboDamage * comboPoints);
9362 if(Player* modOwner = GetSpellModOwner())
9364 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
9365 switch(effect_index)
9367 case 0:
9368 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
9369 break;
9370 case 1:
9371 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
9372 break;
9373 case 2:
9374 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
9375 break;
9379 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
9380 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
9381 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
9382 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
9384 return value;
9387 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
9389 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9391 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9393 int32 minduration = GetSpellDuration(spellProto);
9394 int32 maxduration = GetSpellMaxDuration(spellProto);
9396 int32 duration;
9398 if( minduration != -1 && minduration != maxduration )
9399 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
9400 else
9401 duration = minduration;
9403 if (duration > 0)
9405 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
9406 // Find total mod value (negative bonus)
9407 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
9408 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
9409 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
9410 // Find max mod (negative bonus)
9411 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
9413 int32 durationMod = 0;
9414 // Select strongest negative mod
9415 if (durationMod_always > durationMod_not_stack)
9416 durationMod = durationMod_not_stack;
9417 else
9418 durationMod = durationMod_always;
9420 if (durationMod != 0)
9421 duration = int32(int64(duration) * (100+durationMod) /100);
9423 if (duration < 0) duration = 0;
9426 return duration;
9429 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
9431 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9433 if(i->DRGroup != group)
9434 continue;
9436 if(!i->hitCount)
9437 return DIMINISHING_LEVEL_1;
9439 if(!i->hitTime)
9440 return DIMINISHING_LEVEL_1;
9442 // If last spell was casted more than 15 seconds ago - reset the count.
9443 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
9445 i->hitCount = DIMINISHING_LEVEL_1;
9446 return DIMINISHING_LEVEL_1;
9448 // or else increase the count.
9449 else
9451 return DiminishingLevels(i->hitCount);
9454 return DIMINISHING_LEVEL_1;
9457 void Unit::IncrDiminishing(DiminishingGroup group)
9459 // Checking for existing in the table
9460 bool IsExist = false;
9461 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9463 if(i->DRGroup != group)
9464 continue;
9466 IsExist = true;
9467 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
9468 i->hitCount += 1;
9470 break;
9473 if(!IsExist)
9474 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9477 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9479 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9480 return;
9482 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9483 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9485 // test pet/charm masters instead pets/charmeds
9486 Unit const* targetOwner = GetCharmerOrOwner();
9487 Unit const* casterOwner = caster->GetCharmerOrOwner();
9489 Unit const* target = targetOwner ? targetOwner : this;
9490 Unit const* source = casterOwner ? casterOwner : caster;
9492 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9493 duration = 10000;
9496 float mod = 1.0f;
9498 // Some diminishings applies to mobs too (for example, Stun)
9499 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9501 DiminishingLevels diminish = Level;
9502 switch(diminish)
9504 case DIMINISHING_LEVEL_1: break;
9505 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9506 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9507 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9508 default: break;
9512 duration = int32(duration * mod);
9515 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9517 // Checking for existing in the table
9518 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9520 if(i->DRGroup != group)
9521 continue;
9523 i->hitTime = getMSTime();
9525 if(apply)
9526 i->stack += 1;
9527 else if(i->stack)
9528 i->stack -= 1;
9530 break;
9534 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9536 return ObjectAccessor::GetUnit(object,guid);
9539 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9541 return isVisibleForOrDetect(u, false, inVisibleList, false);
9544 uint32 Unit::GetCreatureType() const
9546 if(GetTypeId() == TYPEID_PLAYER)
9548 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(((Player*)this)->m_form);
9549 if(ssEntry && ssEntry->creatureType > 0)
9550 return ssEntry->creatureType;
9551 else
9552 return CREATURE_TYPE_HUMANOID;
9554 else
9555 return ((Creature*)this)->GetCreatureInfo()->type;
9558 /*#######################################
9559 ######## ########
9560 ######## STAT SYSTEM ########
9561 ######## ########
9562 #######################################*/
9564 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9566 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9568 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9569 return false;
9572 float val = 1.0f;
9574 switch(modifierType)
9576 case BASE_VALUE:
9577 case TOTAL_VALUE:
9578 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9579 break;
9580 case BASE_PCT:
9581 case TOTAL_PCT:
9582 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9583 amount = -200.0f;
9585 val = (100.0f + amount) / 100.0f;
9586 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9587 break;
9589 default:
9590 break;
9593 if(!CanModifyStats())
9594 return false;
9596 switch(unitMod)
9598 case UNIT_MOD_STAT_STRENGTH:
9599 case UNIT_MOD_STAT_AGILITY:
9600 case UNIT_MOD_STAT_STAMINA:
9601 case UNIT_MOD_STAT_INTELLECT:
9602 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9604 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9605 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9607 case UNIT_MOD_MANA:
9608 case UNIT_MOD_RAGE:
9609 case UNIT_MOD_FOCUS:
9610 case UNIT_MOD_ENERGY:
9611 case UNIT_MOD_HAPPINESS:
9612 case UNIT_MOD_RUNE:
9613 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9615 case UNIT_MOD_RESISTANCE_HOLY:
9616 case UNIT_MOD_RESISTANCE_FIRE:
9617 case UNIT_MOD_RESISTANCE_NATURE:
9618 case UNIT_MOD_RESISTANCE_FROST:
9619 case UNIT_MOD_RESISTANCE_SHADOW:
9620 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9622 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9623 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9625 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9626 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9627 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9629 default:
9630 break;
9633 return true;
9636 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9638 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9640 sLog.outError("ERROR: trial to access non existed modifier value from UnitMods!");
9641 return 0.0f;
9644 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9645 return 0.0f;
9647 return m_auraModifiersGroup[unitMod][modifierType];
9650 float Unit::GetTotalStatValue(Stats stat) const
9652 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9654 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9655 return 0.0f;
9657 // value = ((base_value * base_pct) + total_value) * total_pct
9658 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9659 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9660 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9661 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9663 return value;
9666 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9668 if(unitMod >= UNIT_MOD_END)
9670 sLog.outError("ERROR: trial to access non existed UnitMods in GetTotalAuraModValue()!");
9671 return 0.0f;
9674 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9675 return 0.0f;
9677 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9678 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9679 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9680 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9682 return value;
9685 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9687 SpellSchools school = SPELL_SCHOOL_NORMAL;
9689 switch(unitMod)
9691 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9692 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9693 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9694 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9695 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9696 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9698 default:
9699 break;
9702 return school;
9705 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9707 Stats stat = STAT_STRENGTH;
9709 switch(unitMod)
9711 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9712 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9713 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9714 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9715 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9717 default:
9718 break;
9721 return stat;
9724 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9726 switch(unitMod)
9728 case UNIT_MOD_MANA: return POWER_MANA;
9729 case UNIT_MOD_RAGE: return POWER_RAGE;
9730 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9731 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9732 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9733 case UNIT_MOD_RUNE: return POWER_RUNE;
9734 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9737 return POWER_MANA;
9740 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9742 UnitMods unitMod = (attType == RANGED_ATTACK) ? UNIT_MOD_ATTACK_POWER_RANGED : UNIT_MOD_ATTACK_POWER;
9744 float val = GetTotalAuraModValue(unitMod);
9745 if(val < 0.0f)
9746 val = 0.0f;
9748 return val;
9751 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9753 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9754 return 0.0f;
9756 return m_weaponDamage[attType][type];
9759 void Unit::SetLevel(uint32 lvl)
9761 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9763 // group update
9764 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9765 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9768 void Unit::SetHealth(uint32 val)
9770 uint32 maxHealth = GetMaxHealth();
9771 if(maxHealth < val)
9772 val = maxHealth;
9774 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9776 // group update
9777 if(GetTypeId() == TYPEID_PLAYER)
9779 if(((Player*)this)->GetGroup())
9780 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9782 else if(((Creature*)this)->isPet())
9784 Pet *pet = ((Pet*)this);
9785 if(pet->isControlled())
9787 Unit *owner = GetOwner();
9788 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9789 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
9794 void Unit::SetMaxHealth(uint32 val)
9796 uint32 health = GetHealth();
9797 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
9799 // group update
9800 if(GetTypeId() == TYPEID_PLAYER)
9802 if(((Player*)this)->GetGroup())
9803 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
9805 else if(((Creature*)this)->isPet())
9807 Pet *pet = ((Pet*)this);
9808 if(pet->isControlled())
9810 Unit *owner = GetOwner();
9811 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9812 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
9816 if(val < health)
9817 SetHealth(val);
9820 void Unit::SetPower(Powers power, uint32 val)
9822 if(GetPower(power) == val)
9823 return;
9825 uint32 maxPower = GetMaxPower(power);
9826 if(maxPower < val)
9827 val = maxPower;
9829 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
9831 WorldPacket data(SMSG_POWER_UPDATE);
9832 data.append(GetPackGUID());
9833 data << uint8(power);
9834 data << uint32(val);
9835 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
9837 // group update
9838 if(GetTypeId() == TYPEID_PLAYER)
9840 if(((Player*)this)->GetGroup())
9841 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9843 else if(((Creature*)this)->isPet())
9845 Pet *pet = ((Pet*)this);
9846 if(pet->isControlled())
9848 Unit *owner = GetOwner();
9849 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9850 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9853 // Update the pet's character sheet with happiness damage bonus
9854 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
9856 pet->UpdateDamagePhysical(BASE_ATTACK);
9861 void Unit::SetMaxPower(Powers power, uint32 val)
9863 uint32 cur_power = GetPower(power);
9864 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
9866 // group update
9867 if(GetTypeId() == TYPEID_PLAYER)
9869 if(((Player*)this)->GetGroup())
9870 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9872 else if(((Creature*)this)->isPet())
9874 Pet *pet = ((Pet*)this);
9875 if(pet->isControlled())
9877 Unit *owner = GetOwner();
9878 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9879 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
9883 if(val < cur_power)
9884 SetPower(power, val);
9887 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
9889 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
9891 // group update
9892 if(GetTypeId() == TYPEID_PLAYER)
9894 if(((Player*)this)->GetGroup())
9895 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9897 else if(((Creature*)this)->isPet())
9899 Pet *pet = ((Pet*)this);
9900 if(pet->isControlled())
9902 Unit *owner = GetOwner();
9903 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9904 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9909 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
9911 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
9913 // group update
9914 if(GetTypeId() == TYPEID_PLAYER)
9916 if(((Player*)this)->GetGroup())
9917 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
9919 else if(((Creature*)this)->isPet())
9921 Pet *pet = ((Pet*)this);
9922 if(pet->isControlled())
9924 Unit *owner = GetOwner();
9925 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9926 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
9931 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
9933 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
9934 if(apply)
9935 tAuraProcTriggerDamage.push_back(aura);
9936 else
9937 tAuraProcTriggerDamage.remove(aura);
9940 uint32 Unit::GetCreatePowers( Powers power ) const
9942 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
9943 switch(power)
9945 case POWER_MANA: return GetCreateMana();
9946 case POWER_RAGE: return 1000;
9947 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
9948 case POWER_ENERGY: return 100;
9949 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
9950 case POWER_RUNIC_POWER: return 1000;
9953 return 0;
9956 void Unit::AddToWorld()
9958 Object::AddToWorld();
9961 void Unit::RemoveFromWorld()
9963 // cleanup
9964 if(IsInWorld())
9966 RemoveNotOwnSingleTargetAuras();
9969 Object::RemoveFromWorld();
9972 void Unit::CleanupsBeforeDelete()
9974 if(m_uint32Values) // only for fully created object
9976 InterruptNonMeleeSpells(true);
9977 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
9978 CombatStop();
9979 ClearComboPointHolders();
9980 DeleteThreatList();
9981 getHostilRefManager().setOnlineOfflineState(false);
9982 RemoveAllAuras();
9983 RemoveAllGameObjects();
9984 RemoveAllDynObjects();
9985 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
9987 RemoveFromWorld();
9990 CharmInfo* Unit::InitCharmInfo(Unit *charm)
9992 if(!m_charmInfo)
9993 m_charmInfo = new CharmInfo(charm);
9994 return m_charmInfo;
9997 CharmInfo::CharmInfo(Unit* unit)
9998 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10000 for(int i =0; i<4; ++i)
10002 m_charmspells[i].spellId = 0;
10003 m_charmspells[i].active = ACT_DISABLED;
10007 void CharmInfo::InitPetActionBar()
10009 // the first 3 SpellOrActions are attack, follow and stay
10010 for(uint32 i = 0; i < 3; i++)
10012 PetActionBar[i].Type = ACT_COMMAND;
10013 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
10015 PetActionBar[i + 7].Type = ACT_REACTION;
10016 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
10018 for(uint32 i=0; i < 4; i++)
10020 PetActionBar[i + 3].Type = ACT_DISABLED;
10021 PetActionBar[i + 3].SpellOrAction = 0;
10025 void CharmInfo::InitEmptyActionBar()
10027 for(uint32 x = 1; x < 10; ++x)
10029 PetActionBar[x].Type = ACT_PASSIVE;
10030 PetActionBar[x].SpellOrAction = 0;
10032 PetActionBar[0].Type = ACT_COMMAND;
10033 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
10036 void CharmInfo::InitPossessCreateSpells()
10038 if(m_unit->GetTypeId() == TYPEID_PLAYER)
10039 return;
10041 InitEmptyActionBar(); //charm action bar
10043 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10045 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10046 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10047 else
10048 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10052 void CharmInfo::InitCharmCreateSpells()
10054 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10056 InitEmptyActionBar();
10057 return;
10060 InitPetActionBar();
10062 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10064 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10065 m_charmspells[x].spellId = spellId;
10067 if(!spellId)
10068 continue;
10070 if (IsPassiveSpell(spellId))
10072 m_unit->CastSpell(m_unit, spellId, true);
10073 m_charmspells[x].active = ACT_PASSIVE;
10075 else
10077 ActiveStates newstate;
10078 bool onlyselfcast = true;
10079 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10081 if(!spellInfo) onlyselfcast = false;
10082 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10084 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10085 onlyselfcast = false;
10088 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10089 newstate = ACT_DISABLED;
10090 else
10091 newstate = ACT_PASSIVE;
10093 AddSpellToAB(0, spellId, newstate);
10098 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
10100 for(uint8 i = 0; i < 10; i++)
10102 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
10104 PetActionBar[i].SpellOrAction = newid;
10105 if(!oldid)
10107 if(newstate == ACT_DECIDE)
10108 PetActionBar[i].Type = ACT_DISABLED;
10109 else
10110 PetActionBar[i].Type = newstate;
10113 return true;
10116 return false;
10119 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10121 if(IsPassiveSpell(spellid))
10122 return;
10124 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10126 if(spellid == m_charmspells[x].spellId)
10128 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
10133 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10135 m_petnumber = petnumber;
10136 if(statwindow)
10137 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10138 else
10139 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10142 bool Unit::isFrozen() const
10144 return HasAuraState(AURA_STATE_FROZEN);
10147 struct ProcTriggeredData
10149 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
10150 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
10151 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
10153 SpellProcEventEntry const *spellProcEvent;
10154 Aura* triggeredByAura;
10155 Unit::spellEffectPair triggeredByAura_SpellPair;
10158 typedef std::list< ProcTriggeredData > ProcTriggeredList;
10159 typedef std::list< uint32> RemoveSpellList;
10161 // List of auras that CAN be trigger but may not exist in spell_proc_event
10162 // in most case need for drop charges
10163 // in some types of aura need do additional check
10164 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
10165 bool InitTriggerAuraData()
10167 for (int i=0;i<TOTAL_AURAS;i++)
10169 isTriggerAura[i]=false;
10170 isNonTriggerAura[i] = false;
10172 isTriggerAura[SPELL_AURA_DUMMY] = true;
10173 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
10174 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
10175 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
10176 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
10177 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
10178 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
10179 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
10180 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
10181 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
10182 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
10183 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
10184 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED] = true;
10185 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
10186 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
10187 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
10188 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
10189 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
10190 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
10191 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
10192 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
10193 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
10194 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
10195 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
10196 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
10197 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
10198 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
10199 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
10201 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
10202 isNonTriggerAura[SPELL_AURA_RESIST_PUSHBACK]=true;
10204 return true;
10207 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
10209 uint32 procEx = PROC_EX_NONE;
10210 // Check victim state
10211 if (missCondition!=SPELL_MISS_NONE)
10212 switch (missCondition)
10214 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
10215 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
10216 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
10217 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
10218 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
10219 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
10220 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
10221 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
10222 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
10223 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
10224 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
10225 default:
10226 break;
10228 else
10230 // On block
10231 if (damageInfo->blocked)
10232 procEx|=PROC_EX_BLOCK;
10233 // On absorb
10234 if (damageInfo->absorb)
10235 procEx|=PROC_EX_ABSORB;
10236 // On crit
10237 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
10238 procEx|=PROC_EX_CRITICAL_HIT;
10239 else
10240 procEx|=PROC_EX_NORMAL_HIT;
10242 return procEx;
10245 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
10247 // For melee/ranged based attack need update skills and set some Aura states
10248 if (procFlag & MELEE_BASED_TRIGGER_MASK)
10250 // Update skills here for players
10251 if (GetTypeId() == TYPEID_PLAYER)
10253 // On melee based hit/miss/resist need update skill (for victim and attacker)
10254 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
10256 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
10257 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
10259 // Update defence if player is victim and parry/dodge/block
10260 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
10261 ((Player*)this)->UpdateDefense();
10263 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
10264 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
10266 // for victim
10267 if (isVictim)
10269 // if victim and dodge attack
10270 if (procExtra&PROC_EX_DODGE)
10272 //Update AURA_STATE on dodge
10273 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
10275 ModifyAuraState(AURA_STATE_DEFENSE, true);
10276 StartReactiveTimer( REACTIVE_DEFENSE );
10279 // if victim and parry attack
10280 if (procExtra & PROC_EX_PARRY)
10282 // For Hunters only Counterattack (skip Mongoose bite)
10283 if (getClass() == CLASS_HUNTER)
10285 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
10286 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
10288 else
10290 ModifyAuraState(AURA_STATE_DEFENSE, true);
10291 StartReactiveTimer( REACTIVE_DEFENSE );
10294 // if and victim block attack
10295 if (procExtra & PROC_EX_BLOCK)
10297 ModifyAuraState(AURA_STATE_DEFENSE,true);
10298 StartReactiveTimer( REACTIVE_DEFENSE );
10301 else //For attacker
10303 // Overpower on victim dodge
10304 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
10306 ((Player*)this)->AddComboPoints(pTarget, 1);
10307 StartReactiveTimer( REACTIVE_OVERPOWER );
10313 RemoveSpellList removedSpells;
10314 ProcTriggeredList procTriggered;
10315 // Fill procTriggered list
10316 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
10318 SpellProcEventEntry const* spellProcEvent = NULL;
10319 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
10320 continue;
10322 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
10325 // Nothing found
10326 if (procTriggered.empty())
10327 return;
10329 // Handle effects proceed this time
10330 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
10332 // Some auras can be deleted in function called in this loop (except first, ofc)
10333 // Until storing auars in std::multimap to hard check deleting by another way
10334 if(i != procTriggered.begin())
10336 bool found = false;
10337 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10338 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10339 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10341 if(itr->second==i->triggeredByAura)
10343 found = true;
10344 break;
10347 if(!found)
10349 // 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);
10350 // sLog.outDebug("It can be deleted one from early proccesed auras:");
10351 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
10352 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
10353 // sLog.outDebug(" <end of list>");
10354 continue;
10358 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
10359 Aura *triggeredByAura = i->triggeredByAura;
10360 Modifier *auraModifier = triggeredByAura->GetModifier();
10361 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
10362 uint32 effIndex = triggeredByAura->GetEffIndex();
10363 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
10364 // For players set spell cooldown if need
10365 uint32 cooldown = 0;
10366 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
10367 cooldown = spellProcEvent->cooldown;
10369 switch(auraModifier->m_auraname)
10371 case SPELL_AURA_PROC_TRIGGER_SPELL:
10373 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
10374 // Don`t drop charge or add cooldown for not started trigger
10375 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10376 continue;
10377 break;
10379 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
10381 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());
10382 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
10383 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
10384 SendSpellNonMeleeDamageLog(&damageInfo);
10385 DealSpellDamage(&damageInfo, true);
10386 break;
10388 case SPELL_AURA_MANA_SHIELD:
10389 case SPELL_AURA_DUMMY:
10391 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());
10392 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10393 continue;
10394 break;
10396 case SPELL_AURA_MOD_HASTE:
10398 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());
10399 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10400 continue;
10401 break;
10403 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
10405 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());
10406 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
10407 continue;
10408 break;
10410 case SPELL_AURA_PRAYER_OF_MENDING:
10412 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
10413 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
10415 HandleMeandingAuraProc(triggeredByAura);
10416 break;
10418 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
10420 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());
10422 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10423 continue;
10424 break;
10426 case SPELL_AURA_MOD_CASTING_SPEED:
10427 // Skip melee hits or instant cast spells
10428 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
10429 continue;
10430 break;
10431 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
10432 // Skip Melee hits and spells ws wrong school
10433 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
10434 continue;
10435 break;
10436 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
10437 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
10438 // Skip melee hits and spells ws wrong school or zero cost
10439 if (procSpell == NULL ||
10440 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
10441 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
10442 continue;
10443 break;
10444 case SPELL_AURA_MECHANIC_IMMUNITY:
10445 // Compare mechanic
10446 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10447 continue;
10448 break;
10449 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
10450 // Compare mechanic
10451 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10452 continue;
10453 break;
10454 default:
10455 // nothing do, just charges counter
10456 break;
10458 // Remove charge (aura can be removed by triggers)
10459 if(useCharges)
10461 // need found aura on drop (can be dropped by triggers)
10462 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10463 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10464 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10466 // If last charge dropped add spell to remove list
10467 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
10469 removedSpells.push_back(triggeredByAura->GetId());
10470 break;
10475 if (!removedSpells.empty())
10477 // Sort spells and remove dublicates
10478 removedSpells.sort();
10479 removedSpells.unique();
10480 // Remove auras from removedAuras
10481 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
10482 RemoveAurasDueToSpell(*i);
10486 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10488 return SPELL_SCHOOL_MASK_NORMAL;
10491 Player* Unit::GetSpellModOwner()
10493 if(GetTypeId()==TYPEID_PLAYER)
10494 return (Player*)this;
10495 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10497 Unit* owner = GetOwner();
10498 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10499 return (Player*)owner;
10501 return NULL;
10504 ///----------Pet responses methods-----------------
10505 void Unit::SendPetCastFail(uint32 spellid, uint8 msg)
10507 Unit *owner = GetCharmerOrOwner();
10508 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10509 return;
10511 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
10512 data << uint8(0); // cast count?
10513 data << uint32(spellid);
10514 data << uint8(msg);
10515 // uint32 for some reason
10516 // uint32 for some reason
10517 ((Player*)owner)->GetSession()->SendPacket(&data);
10520 void Unit::SendPetActionFeedback (uint8 msg)
10522 Unit* owner = GetOwner();
10523 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10524 return;
10526 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10527 data << uint8(msg);
10528 ((Player*)owner)->GetSession()->SendPacket(&data);
10531 void Unit::SendPetTalk (uint32 pettalk)
10533 Unit* owner = GetOwner();
10534 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10535 return;
10537 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
10538 data << uint64(GetGUID());
10539 data << uint32(pettalk);
10540 ((Player*)owner)->GetSession()->SendPacket(&data);
10543 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10545 Unit* owner = GetOwner();
10546 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10547 return;
10549 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10550 data << uint64(GetGUID());
10551 data << uint8(0x0); // flags (0x1, 0x2)
10552 data << uint32(spellid);
10553 data << uint32(cooltime);
10555 ((Player*)owner)->GetSession()->SendPacket(&data);
10558 void Unit::SendPetClearCooldown (uint32 spellid)
10560 Unit* owner = GetOwner();
10561 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10562 return;
10564 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10565 data << uint32(spellid);
10566 data << uint64(GetGUID());
10567 ((Player*)owner)->GetSession()->SendPacket(&data);
10570 void Unit::SendPetAIReaction(uint64 guid)
10572 Unit* owner = GetOwner();
10573 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10574 return;
10576 WorldPacket data(SMSG_AI_REACTION, 12);
10577 data << uint64(guid) << uint32(00000002);
10578 ((Player*)owner)->GetSession()->SendPacket(&data);
10581 ///----------End of Pet responses methods----------
10583 void Unit::StopMoving()
10585 clearUnitState(UNIT_STAT_MOVING);
10587 // send explicit stop packet
10588 // rely on vmaps here because for example stormwind is in air
10589 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10590 //if (fabs(GetPositionZ() - z) < 2.0f)
10591 // Relocate(GetPositionX(), GetPositionY(), z);
10592 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10594 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10596 // update position and orientation;
10597 WorldPacket data;
10598 BuildHeartBeatMsg(&data);
10599 SendMessageToSet(&data,false);
10602 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10604 if( apply )
10606 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10607 return;
10609 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10611 GetMotionMaster()->MovementExpired(false);
10612 CastStop(GetGUID()==casterGUID ? spellID : 0);
10614 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10616 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10618 else
10620 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10622 GetMotionMaster()->MovementExpired(false);
10624 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10626 // restore appropriate movement generator
10627 if(getVictim())
10628 GetMotionMaster()->MoveChase(getVictim());
10629 else
10630 GetMotionMaster()->Initialize();
10632 // attack caster if can
10633 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10634 if(caster && caster != getVictim() && ((Creature*)this)->AI())
10635 ((Creature*)this)->AI()->AttackStart(caster);
10639 if (GetTypeId() == TYPEID_PLAYER)
10640 ((Player*)this)->SetClientControl(this, !apply);
10643 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10645 if( apply )
10647 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10649 CastStop(GetGUID()==casterGUID ? spellID : 0);
10651 GetMotionMaster()->MoveConfused();
10653 else
10655 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10657 GetMotionMaster()->MovementExpired(false);
10659 if (GetTypeId() == TYPEID_UNIT)
10661 // if in combat restore movement generator
10662 if(getVictim())
10663 GetMotionMaster()->MoveChase(getVictim());
10667 if(GetTypeId() == TYPEID_PLAYER)
10668 ((Player*)this)->SetClientControl(this, !apply);
10671 bool Unit::IsSitState() const
10673 uint8 s = getStandState();
10674 return s == PLAYER_STATE_SIT_CHAIR || s == PLAYER_STATE_SIT_LOW_CHAIR ||
10675 s == PLAYER_STATE_SIT_MEDIUM_CHAIR || s == PLAYER_STATE_SIT_HIGH_CHAIR ||
10676 s == PLAYER_STATE_SIT;
10679 bool Unit::IsStandState() const
10681 uint8 s = getStandState();
10682 return !IsSitState() && s != PLAYER_STATE_SLEEP && s != PLAYER_STATE_KNEEL;
10685 void Unit::SetStandState(uint8 state)
10687 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10689 if (IsStandState())
10690 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10692 if(GetTypeId()==TYPEID_PLAYER)
10694 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10695 data << (uint8)state;
10696 ((Player*)this)->GetSession()->SendPacket(&data);
10700 bool Unit::IsPolymorphed() const
10702 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10705 void Unit::SetDisplayId(uint32 modelId)
10707 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10709 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10711 Pet *pet = ((Pet*)this);
10712 if(!pet->isControlled())
10713 return;
10714 Unit *owner = GetOwner();
10715 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10716 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10720 void Unit::ClearComboPointHolders()
10722 while(!m_ComboPointHolders.empty())
10724 uint32 lowguid = *m_ComboPointHolders.begin();
10726 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10727 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10728 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10729 else
10730 m_ComboPointHolders.erase(lowguid); // or remove manually
10734 void Unit::ClearAllReactives()
10736 for(int i=0; i < MAX_REACTIVE; ++i)
10737 m_reactiveTimer[i] = 0;
10739 if (HasAuraState( AURA_STATE_DEFENSE))
10740 ModifyAuraState(AURA_STATE_DEFENSE, false);
10741 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10742 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10743 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10744 ((Player*)this)->ClearComboPoints();
10747 void Unit::UpdateReactives( uint32 p_time )
10749 for(int i = 0; i < MAX_REACTIVE; ++i)
10751 ReactiveType reactive = ReactiveType(i);
10753 if(!m_reactiveTimer[reactive])
10754 continue;
10756 if ( m_reactiveTimer[reactive] <= p_time)
10758 m_reactiveTimer[reactive] = 0;
10760 switch ( reactive )
10762 case REACTIVE_DEFENSE:
10763 if (HasAuraState(AURA_STATE_DEFENSE))
10764 ModifyAuraState(AURA_STATE_DEFENSE, false);
10765 break;
10766 case REACTIVE_HUNTER_PARRY:
10767 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10768 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10769 break;
10770 case REACTIVE_OVERPOWER:
10771 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10772 ((Player*)this)->ClearComboPoints();
10773 break;
10774 default:
10775 break;
10778 else
10780 m_reactiveTimer[reactive] -= p_time;
10785 Unit* Unit::SelectNearbyTarget() const
10787 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
10788 Cell cell(p);
10789 cell.data.Part.reserved = ALL_DISTRICT;
10790 cell.SetNoCreate();
10792 std::list<Unit *> targets;
10795 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
10796 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(targets, u_check);
10798 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
10799 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
10801 CellLock<GridReadGuard> cell_lock(cell, p);
10802 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
10803 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
10806 // remove current target
10807 if(getVictim())
10808 targets.remove(getVictim());
10810 // remove not LoS targets
10811 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
10813 if(!IsWithinLOSInMap(*tIter))
10815 std::list<Unit *>::iterator tIter2 = tIter;
10816 ++tIter;
10817 targets.erase(tIter2);
10819 else
10820 ++tIter;
10823 // no appropriate targets
10824 if(targets.empty())
10825 return NULL;
10827 // select random
10828 uint32 rIdx = urand(0,targets.size()-1);
10829 std::list<Unit *>::const_iterator tcIter = targets.begin();
10830 for(uint32 i = 0; i < rIdx; ++i)
10831 ++tcIter;
10833 return *tcIter;
10836 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
10838 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
10840 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
10841 return true;
10843 return false;
10846 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
10848 if(val > 0)
10850 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
10851 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
10853 else
10855 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
10856 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
10860 void Unit::ApplyCastTimePercentMod(float val, bool apply )
10862 if(val > 0)
10863 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
10864 else
10865 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
10868 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
10870 // Not apply this to creature casted spells with casttime==0
10871 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
10872 return 3500;
10874 if (CastingTime > 7000) CastingTime = 7000;
10875 if (CastingTime < 1500) CastingTime = 1500;
10877 if(damagetype == DOT && !IsChanneledSpell(spellProto))
10878 CastingTime = 3500;
10880 int32 overTime = 0;
10881 uint8 effects = 0;
10882 bool DirectDamage = false;
10883 bool AreaEffect = false;
10885 for ( uint32 i=0; i<3;i++)
10887 switch ( spellProto->Effect[i] )
10889 case SPELL_EFFECT_SCHOOL_DAMAGE:
10890 case SPELL_EFFECT_POWER_DRAIN:
10891 case SPELL_EFFECT_HEALTH_LEECH:
10892 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
10893 case SPELL_EFFECT_POWER_BURN:
10894 case SPELL_EFFECT_HEAL:
10895 DirectDamage = true;
10896 break;
10897 case SPELL_EFFECT_APPLY_AURA:
10898 switch ( spellProto->EffectApplyAuraName[i] )
10900 case SPELL_AURA_PERIODIC_DAMAGE:
10901 case SPELL_AURA_PERIODIC_HEAL:
10902 case SPELL_AURA_PERIODIC_LEECH:
10903 if ( GetSpellDuration(spellProto) )
10904 overTime = GetSpellDuration(spellProto);
10905 break;
10906 default:
10907 // -5% per additional effect
10908 ++effects;
10909 break;
10911 default:
10912 break;
10915 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
10916 AreaEffect = true;
10919 // Combined Spells with Both Over Time and Direct Damage
10920 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
10922 // mainly for DoTs which are 3500 here otherwise
10923 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
10924 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
10925 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
10926 // Portion to Over Time
10927 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
10929 if ( damagetype == DOT )
10930 CastingTime = uint32(CastingTime * PtOT);
10931 else if ( PtOT < 1.0f )
10932 CastingTime = uint32(CastingTime * (1 - PtOT));
10933 else
10934 CastingTime = 0;
10937 // Area Effect Spells receive only half of bonus
10938 if ( AreaEffect )
10939 CastingTime /= 2;
10941 // -5% of total per any additional effect
10942 for ( uint8 i=0; i<effects; ++i)
10944 if ( CastingTime > 175 )
10946 CastingTime -= 175;
10948 else
10950 CastingTime = 0;
10951 break;
10955 return CastingTime;
10958 void Unit::UpdateAuraForGroup(uint8 slot)
10960 if(GetTypeId() == TYPEID_PLAYER)
10962 Player* player = (Player*)this;
10963 if(player->GetGroup())
10965 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
10966 player->SetAuraUpdateMask(slot);
10969 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10971 Pet *pet = ((Pet*)this);
10972 if(pet->isControlled())
10974 Unit *owner = GetOwner();
10975 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10977 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
10978 pet->SetAuraUpdateMask(slot);
10984 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
10986 if (!normalized || GetTypeId() != TYPEID_PLAYER)
10987 return float(GetAttackTime(attType))/1000.0f;
10989 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
10990 if (!Weapon)
10991 return 2.4; // fist attack
10993 switch (Weapon->GetProto()->InventoryType)
10995 case INVTYPE_2HWEAPON:
10996 return 3.3;
10997 case INVTYPE_RANGED:
10998 case INVTYPE_RANGEDRIGHT:
10999 case INVTYPE_THROWN:
11000 return 2.8;
11001 case INVTYPE_WEAPON:
11002 case INVTYPE_WEAPONMAINHAND:
11003 case INVTYPE_WEAPONOFFHAND:
11004 default:
11005 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11009 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11011 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11012 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11013 if ((*itr)->GetId() == spell_id)
11014 return *itr;
11016 return NULL;
11019 bool Unit::IsUnderLastManaUseEffect() const
11021 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
11024 void Unit::SetContestedPvP(Player *attackedPlayer)
11026 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11028 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11029 return;
11031 player->SetContestedPvPTimer(30000);
11032 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11034 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11035 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11036 // call MoveInLineOfSight for nearby contested guards
11037 SetVisibility(GetVisibility());
11039 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11041 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11042 // call MoveInLineOfSight for nearby contested guards
11043 SetVisibility(GetVisibility());
11047 void Unit::AddPetAura(PetAura const* petSpell)
11049 m_petAuras.insert(petSpell);
11050 if(Pet* pet = GetPet())
11051 pet->CastPetAura(petSpell);
11054 void Unit::RemovePetAura(PetAura const* petSpell)
11056 m_petAuras.erase(petSpell);
11057 if(Pet* pet = GetPet())
11058 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11061 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11063 Pet* pet = new Pet(HUNTER_PET);
11065 if(!pet->CreateBaseAtCreature(creatureTarget))
11067 delete pet;
11068 return NULL;
11071 pet->SetOwnerGUID(GetGUID());
11072 pet->SetCreatorGUID(GetGUID());
11073 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
11074 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11076 if(GetTypeId()==TYPEID_PLAYER)
11077 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11079 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11080 pet->SetFreeTalentPoints(pet->GetMaxTalentPointsForLevel(level));
11082 if(!pet->InitStatsForLevel(level))
11084 sLog.outError("ERROR: Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11085 delete pet;
11086 return NULL;
11089 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11090 // this enables pet details window (Shift+P)
11091 pet->AIM_Initialize();
11092 pet->InitPetCreateSpells();
11093 pet->SetHealth(pet->GetMaxHealth());
11095 return pet;
11098 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11100 SpellEntry const* spellProto = aura->GetSpellProto ();
11102 // Get proc Event Entry
11103 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11105 // Aura info stored here
11106 Modifier *mod = aura->GetModifier();
11107 // Skip this auras
11108 if (isNonTriggerAura[mod->m_auraname])
11109 return false;
11110 // If not trigger by default and spellProcEvent==NULL - skip
11111 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11112 return false;
11114 // Get EventProcFlag
11115 uint32 EventProcFlag;
11116 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
11117 EventProcFlag = spellProcEvent->procFlags;
11118 else
11119 EventProcFlag = spellProto->procFlags; // else get from spell proto
11120 // Continue if no trigger exist
11121 if (!EventProcFlag)
11122 return false;
11124 // Check spellProcEvent data requirements
11125 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
11126 return false;
11128 // In most cases req get honor or XP from kill
11129 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
11131 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
11132 // Shadow Word: Death - can trigger from every kill
11133 if (aura->GetId() == 32409)
11134 allow = true;
11135 if (!allow)
11136 return false;
11138 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
11139 // But except periodic triggers (can triggered from self)
11140 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
11141 return false;
11143 // Check if current equipment allows aura to proc
11144 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
11146 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
11148 Item *item = NULL;
11149 if(attType == BASE_ATTACK)
11150 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
11151 else if (attType == OFF_ATTACK)
11152 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11153 else
11154 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
11156 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
11157 return false;
11159 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11160 return false;
11162 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
11164 // Check if player is wearing shield
11165 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11166 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11167 return false;
11170 // Get chance from spell
11171 float chance = (float)spellProto->procChance;
11172 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
11173 if(spellProcEvent && spellProcEvent->customChance)
11174 chance = spellProcEvent->customChance;
11175 // If PPM exist calculate chance from PPM
11176 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
11178 uint32 WeaponSpeed = GetAttackTime(attType);
11179 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
11181 // Apply chance modifer aura
11182 if(Player* modOwner = GetSpellModOwner())
11183 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
11185 return roll_chance_f(chance);
11188 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
11190 // aura can be deleted at casts
11191 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
11192 uint32 effIdx = triggeredByAura->GetEffIndex();
11193 int32 heal = triggeredByAura->GetModifier()->m_amount;
11194 uint64 caster_guid = triggeredByAura->GetCasterGUID();
11196 // jumps
11197 int32 jumps = triggeredByAura->GetAuraCharges()-1;
11199 // current aura expire
11200 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
11202 // next target selection
11203 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
11205 float radius;
11206 if (spellProto->EffectRadiusIndex[effIdx])
11207 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
11208 else
11209 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
11211 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
11213 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
11215 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
11217 // aura will applied from caster, but spell casted from current aura holder
11218 SpellModifier *mod = new SpellModifier;
11219 mod->op = SPELLMOD_CHARGES;
11220 mod->value = jumps-5; // negative
11221 mod->type = SPELLMOD_FLAT;
11222 mod->spellId = spellProto->Id;
11223 mod->mask = spellProto->SpellFamilyFlags;
11224 mod->mask2 = spellProto->SpellFamilyFlags2;
11226 caster->AddSpellMod(mod, true);
11227 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
11228 caster->AddSpellMod(mod, false);
11233 // heal
11234 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
11235 return true;
11238 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
11240 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
11242 if(!IS_UNIT_GUID(target_guid))
11243 return;
11245 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
11246 if(!target)
11247 return;
11249 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
11251 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
11252 target->RemoveAura(iter);
11253 else
11254 ++iter;