[7272] Trailing whitespace cleaning
[getmangos.git] / src / game / Spell.cpp
blob99b3df7b43513f3549f5d9487d5a842d751be081
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 "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "SpellAuras.h"
37 #include "Group.h"
38 #include "UpdateData.h"
39 #include "MapManager.h"
40 #include "ObjectAccessor.h"
41 #include "CellImpl.h"
42 #include "Policies/SingletonImp.h"
43 #include "SharedDefines.h"
44 #include "LootMgr.h"
45 #include "VMapFactory.h"
46 #include "BattleGround.h"
47 #include "Util.h"
49 #define SPELL_CHANNEL_UPDATE_INTERVAL 1000
51 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
53 bool IsQuestTameSpell(uint32 spellId)
55 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
56 if (!spellproto) return false;
58 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
59 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
62 SpellCastTargets::SpellCastTargets()
64 m_unitTarget = NULL;
65 m_itemTarget = NULL;
66 m_GOTarget = NULL;
68 m_unitTargetGUID = 0;
69 m_GOTargetGUID = 0;
70 m_CorpseTargetGUID = 0;
71 m_itemTargetGUID = 0;
72 m_itemTargetEntry = 0;
74 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
75 m_strTarget = "";
76 m_targetMask = 0;
79 SpellCastTargets::~SpellCastTargets()
83 void SpellCastTargets::setUnitTarget(Unit *target)
85 if (!target)
86 return;
88 m_destX = target->GetPositionX();
89 m_destY = target->GetPositionY();
90 m_destZ = target->GetPositionZ();
91 m_unitTarget = target;
92 m_unitTargetGUID = target->GetGUID();
93 m_targetMask |= TARGET_FLAG_UNIT;
96 void SpellCastTargets::setDestination(float x, float y, float z)
98 m_destX = x;
99 m_destY = y;
100 m_destZ = z;
101 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
104 void SpellCastTargets::setSource(float x, float y, float z)
106 m_srcX = x;
107 m_srcY = y;
108 m_srcZ = z;
109 m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
112 void SpellCastTargets::setGOTarget(GameObject *target)
114 m_GOTarget = target;
115 m_GOTargetGUID = target->GetGUID();
116 // m_targetMask |= TARGET_FLAG_OBJECT;
119 void SpellCastTargets::setItemTarget(Item* item)
121 if(!item)
122 return;
124 m_itemTarget = item;
125 m_itemTargetGUID = item->GetGUID();
126 m_itemTargetEntry = item->GetEntry();
127 m_targetMask |= TARGET_FLAG_ITEM;
130 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
132 m_CorpseTargetGUID = corpse->GetGUID();
135 void SpellCastTargets::Update(Unit* caster)
137 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
138 m_unitTarget = m_unitTargetGUID ?
139 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
140 NULL;
142 m_itemTarget = NULL;
143 if(caster->GetTypeId()==TYPEID_PLAYER)
145 if(m_targetMask & TARGET_FLAG_ITEM)
146 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
147 else
149 Player* pTrader = ((Player*)caster)->GetTrader();
150 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
151 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
153 if(m_itemTarget)
154 m_itemTargetEntry = m_itemTarget->GetEntry();
158 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
160 if(data->rpos()+4 > data->size())
161 return false;
163 *data >> m_targetMask;
165 if(m_targetMask == TARGET_FLAG_SELF)
167 m_destX = caster->GetPositionX();
168 m_destY = caster->GetPositionY();
169 m_destZ = caster->GetPositionZ();
170 m_unitTarget = caster;
171 m_unitTargetGUID = caster->GetGUID();
172 return true;
175 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
176 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
177 if(!data->readPackGUID(m_unitTargetGUID))
178 return false;
180 if( m_targetMask & ( TARGET_FLAG_OBJECT ))
181 if(!data->readPackGUID(m_GOTargetGUID))
182 return false;
184 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
185 if(!data->readPackGUID(m_itemTargetGUID))
186 return false;
188 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
189 if(!data->readPackGUID(m_CorpseTargetGUID))
190 return false;
192 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
194 if(data->rpos()+4+4+4 > data->size())
195 return false;
197 *data >> m_srcX >> m_srcY >> m_srcZ;
198 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
199 return false;
202 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
204 if(data->rpos()+1+4+4+4 > data->size())
205 return false;
207 if(!data->readPackGUID(m_unitTargetGUID))
208 return false;
210 *data >> m_destX >> m_destY >> m_destZ;
211 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
212 return false;
215 if( m_targetMask & TARGET_FLAG_STRING )
217 if(data->rpos()+1 > data->size())
218 return false;
220 *data >> m_strTarget;
223 // find real units/GOs
224 Update(caster);
225 return true;
228 void SpellCastTargets::write ( WorldPacket * data )
230 *data << uint32(m_targetMask);
232 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
234 if(m_targetMask & TARGET_FLAG_UNIT)
236 if(m_unitTarget)
237 data->append(m_unitTarget->GetPackGUID());
238 else
239 *data << uint8(0);
241 else if( m_targetMask & TARGET_FLAG_OBJECT )
243 if(m_GOTarget)
244 data->append(m_GOTarget->GetPackGUID());
245 else
246 *data << uint8(0);
248 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
249 data->appendPackGUID(m_CorpseTargetGUID);
250 else
251 *data << uint8(0);
254 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
256 if(m_itemTarget)
257 data->append(m_itemTarget->GetPackGUID());
258 else
259 *data << uint8(0);
262 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
263 *data << m_srcX << m_srcY << m_srcZ;
265 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
267 if(m_unitTarget)
268 data->append(m_unitTarget->GetPackGUID());
269 else
270 *data << uint8(0);
272 *data << m_destX << m_destY << m_destZ;
275 if( m_targetMask & TARGET_FLAG_STRING )
276 *data << m_strTarget;
279 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
281 ASSERT( Caster != NULL && info != NULL );
282 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
284 m_spellInfo = info;
285 m_caster = Caster;
286 m_selfContainer = NULL;
287 m_triggeringContainer = triggeringContainer;
288 m_referencedFromCurrentSpell = false;
289 m_executedCurrently = false;
290 m_delayStart = 0;
291 m_delayAtDamageCount = 0;
293 m_applyMultiplierMask = 0;
295 // Get data for type of attack
296 switch (m_spellInfo->DmgClass)
298 case SPELL_DAMAGE_CLASS_MELEE:
299 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
300 m_attackType = OFF_ATTACK;
301 else
302 m_attackType = BASE_ATTACK;
303 break;
304 case SPELL_DAMAGE_CLASS_RANGED:
305 m_attackType = RANGED_ATTACK;
306 break;
307 default:
308 // Wands
309 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
310 m_attackType = RANGED_ATTACK;
311 else
312 m_attackType = BASE_ATTACK;
313 break;
316 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
318 if(m_attackType == RANGED_ATTACK)
320 // wand case
321 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
323 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
324 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
327 // Set health leech amount to zero
328 m_healthLeech = 0;
330 if(originalCasterGUID)
331 m_originalCasterGUID = originalCasterGUID;
332 else
333 m_originalCasterGUID = m_caster->GetGUID();
335 if(m_originalCasterGUID==m_caster->GetGUID())
336 m_originalCaster = m_caster;
337 else
339 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
340 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
343 for(int i=0; i <3; ++i)
344 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
346 m_spellState = SPELL_STATE_NULL;
348 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
349 m_TriggerSpells.clear();
350 m_IsTriggeredSpell = triggered;
351 //m_AreaAura = false;
352 m_CastItem = NULL;
354 unitTarget = NULL;
355 itemTarget = NULL;
356 gameObjTarget = NULL;
357 focusObject = NULL;
358 m_cast_count = 0;
359 m_glyphIndex = 0;
360 m_preCastSpell = 0;
361 m_triggeredByAuraSpell = NULL;
363 //Auto Shot & Shoot (wand)
364 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
366 m_runesState = 0;
367 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
368 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
369 m_timer = 0; // will set to castime in prepare
371 m_needAliveTargetMask = 0;
373 // determine reflection
374 m_canReflect = false;
376 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED))
378 for(int j=0;j<3;j++)
380 if (m_spellInfo->Effect[j]==0)
381 continue;
383 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
384 m_canReflect = true;
385 else
386 m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NEGATIVE) ? true : false;
388 if(m_canReflect)
389 continue;
390 else
391 break;
395 CleanupTargetList();
398 Spell::~Spell()
402 void Spell::FillTargetMap()
404 // TODO: ADD the correct target FILLS!!!!!!
406 for(uint32 i=0;i<3;i++)
408 // not call for empty effect.
409 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
410 if(m_spellInfo->Effect[i]==0)
411 continue;
413 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
414 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
415 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
416 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
417 continue;
419 // TODO: find a way so this is not needed?
420 // for area auras always add caster as target (needed for totems for example)
421 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
422 AddUnitTarget(m_caster, i);
424 std::list<Unit*> tmpUnitMap;
426 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
427 // but need it support in some know cases
428 switch(m_spellInfo->EffectImplicitTargetA[i])
430 case TARGET_CASTER_COORDINATES:
431 // Note: this hack with search required until GO casting not implemented
432 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
433 // currently each enemy selected explicitly and self cast damage
434 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
436 if(m_targets.getUnitTarget())
437 tmpUnitMap.push_back(m_targets.getUnitTarget());
439 else
441 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
442 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
444 break;
445 case TARGET_TABLE_X_Y_Z_COORDINATES:
446 // Only if target A, for target B (used in teleports) dest select in effect
447 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
448 break;
449 default:
450 switch(m_spellInfo->EffectImplicitTargetB[i])
452 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
453 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
454 break;
455 default:
456 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
457 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
458 break;
460 break;
463 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
464 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
466 // add here custom effects that need default target.
467 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
468 switch(m_spellInfo->Effect[i])
470 case SPELL_EFFECT_DUMMY:
472 switch(m_spellInfo->Id)
474 case 20577: // Cannibalize
476 // non-standard target selection
477 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
478 float max_range = GetSpellMaxRange(srange);
480 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
481 Cell cell(p);
482 cell.data.Part.reserved = ALL_DISTRICT;
483 cell.SetNoCreate();
485 WorldObject* result = NULL;
487 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
488 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(m_caster, result, u_check);
490 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
491 CellLock<GridReadGuard> cell_lock(cell, p);
492 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
494 if(!result)
496 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
497 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
500 if(result)
502 switch(result->GetTypeId())
504 case TYPEID_UNIT:
505 case TYPEID_PLAYER:
506 tmpUnitMap.push_back((Unit*)result);
507 break;
508 case TYPEID_CORPSE:
509 m_targets.setCorpseTarget((Corpse*)result);
510 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
511 tmpUnitMap.push_back(owner);
512 break;
515 else
517 // clear cooldown at fail
518 if(m_caster->GetTypeId()==TYPEID_PLAYER)
520 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
522 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
523 data << uint32(m_spellInfo->Id);
524 data << uint64(m_caster->GetGUID());
525 ((Player*)m_caster)->GetSession()->SendPacket(&data);
528 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
529 finish(false);
531 break;
533 default:
534 if(m_targets.getUnitTarget())
535 tmpUnitMap.push_back(m_targets.getUnitTarget());
536 break;
538 break;
540 case SPELL_EFFECT_RESURRECT:
541 case SPELL_EFFECT_PARRY:
542 case SPELL_EFFECT_BLOCK:
543 case SPELL_EFFECT_CREATE_ITEM:
544 case SPELL_EFFECT_TRIGGER_SPELL:
545 case SPELL_EFFECT_TRIGGER_MISSILE:
546 case SPELL_EFFECT_LEARN_SPELL:
547 case SPELL_EFFECT_SKILL_STEP:
548 case SPELL_EFFECT_PROFICIENCY:
549 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
550 case SPELL_EFFECT_SELF_RESURRECT:
551 case SPELL_EFFECT_REPUTATION:
552 if(m_targets.getUnitTarget())
553 tmpUnitMap.push_back(m_targets.getUnitTarget());
554 break;
555 case SPELL_EFFECT_SUMMON_PLAYER:
556 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
558 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
559 if(target)
560 tmpUnitMap.push_back(target);
562 break;
563 case SPELL_EFFECT_RESURRECT_NEW:
564 if(m_targets.getUnitTarget())
565 tmpUnitMap.push_back(m_targets.getUnitTarget());
566 if(m_targets.getCorpseTargetGUID())
568 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
569 if(corpse)
571 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
572 if(owner)
573 tmpUnitMap.push_back(owner);
576 break;
577 case SPELL_EFFECT_SUMMON:
578 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
580 if(m_targets.getUnitTarget())
581 tmpUnitMap.push_back(m_targets.getUnitTarget());
583 else
584 tmpUnitMap.push_back(m_caster);
585 break;
586 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
587 case SPELL_EFFECT_TRANS_DOOR:
588 case SPELL_EFFECT_ADD_FARSIGHT:
589 case SPELL_EFFECT_APPLY_GLYPH:
590 case SPELL_EFFECT_STUCK:
591 case SPELL_EFFECT_FEED_PET:
592 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
593 case SPELL_EFFECT_SKILL:
594 tmpUnitMap.push_back(m_caster);
595 break;
596 case SPELL_EFFECT_LEARN_PET_SPELL:
597 if(Pet* pet = m_caster->GetPet())
598 tmpUnitMap.push_back(pet);
599 break;
600 case SPELL_EFFECT_ENCHANT_ITEM:
601 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
602 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
603 case SPELL_EFFECT_DISENCHANT:
604 case SPELL_EFFECT_PROSPECTING:
605 case SPELL_EFFECT_MILLING:
606 if(m_targets.getItemTarget())
607 AddItemTarget(m_targets.getItemTarget(), i);
608 break;
609 case SPELL_EFFECT_APPLY_AURA:
610 switch(m_spellInfo->EffectApplyAuraName[i])
612 case SPELL_AURA_ADD_FLAT_MODIFIER: // some spell mods auras have 0 target modes instead expected TARGET_SELF(1) (and present for other ranks for same spell for example)
613 case SPELL_AURA_ADD_PCT_MODIFIER:
614 tmpUnitMap.push_back(m_caster);
615 break;
616 default: // apply to target in other case
617 if(m_targets.getUnitTarget())
618 tmpUnitMap.push_back(m_targets.getUnitTarget());
619 break;
621 break;
622 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
623 // AreaAura
624 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
625 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
626 break;
627 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
628 if(m_targets.getUnitTarget())
630 tmpUnitMap.push_back(m_targets.getUnitTarget());
632 else if (m_targets.getCorpseTargetGUID())
634 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
635 if(corpse)
637 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
638 if(owner)
639 tmpUnitMap.push_back(owner);
642 break;
643 default:
644 break;
648 if(m_caster->GetTypeId() == TYPEID_PLAYER)
650 Player *me = (Player*)m_caster;
651 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
653 Unit *owner = (*itr)->GetOwner();
654 Unit *u = owner ? owner : (*itr);
655 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
657 me->UpdatePvP(true);
658 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
659 break;
664 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
666 if (!CheckTarget (*itr, i))
668 itr = tmpUnitMap.erase(itr);
669 continue;
671 else
672 ++itr;
675 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
676 AddUnitTarget((*iunit), i);
680 void Spell::prepareDataForTriggerSystem()
682 //==========================================================================================
683 // Now fill data for trigger system, need know:
684 // Ñan spell trigger another or not ( m_canTrigger )
685 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
686 //==========================================================================================
687 // Fill flag can spell trigger or not
688 // TODO: possible exist spell attribute for this
689 m_canTrigger = false;
691 if (m_CastItem)
692 m_canTrigger = false; // Do not trigger from item cast spell
693 else if (!m_IsTriggeredSpell)
694 m_canTrigger = true; // Normal cast - can trigger
695 else if (!m_triggeredByAuraSpell)
696 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
698 if (!m_canTrigger) // Exceptions (some periodic triggers)
700 switch (m_spellInfo->SpellFamilyName)
702 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
703 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
704 break;
705 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
706 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
707 break;
708 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
709 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
710 break;
711 case SPELLFAMILY_ROGUE: // For poisons need do it
712 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
713 break;
714 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot
715 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000214LL ||
716 m_spellInfo->SpellFamilyFlags2 & 0x200) m_canTrigger = true;
717 break;
718 case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it
719 if (m_spellInfo->SpellFamilyFlags & 0x0001000900B80400LL) m_canTrigger = true;
720 break;
724 // Get data for type of attack and fill base info for trigger
725 switch (m_spellInfo->DmgClass)
727 case SPELL_DAMAGE_CLASS_MELEE:
728 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
729 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
730 break;
731 case SPELL_DAMAGE_CLASS_RANGED:
732 // Auto attack
733 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
735 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
736 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
738 else // Ranged spell attack
740 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
741 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
743 break;
744 default:
745 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
747 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
748 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
750 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
752 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
753 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
755 else // Negative spell
757 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
758 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
760 break;
762 // Hunter traps spells (for Entrapment trigger)
763 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
764 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x000020000000001CLL)
765 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
768 void Spell::CleanupTargetList()
770 m_UniqueTargetInfo.clear();
771 m_UniqueGOTargetInfo.clear();
772 m_UniqueItemInfo.clear();
773 m_delayMoment = 0;
776 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
778 if( m_spellInfo->Effect[effIndex]==0 )
779 return;
781 // Check for effect immune skip if immuned
782 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
784 uint64 targetGUID = pVictim->GetGUID();
786 // Lookup target in already in list
787 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
789 if (targetGUID == ihit->targetGUID) // Found in list
791 if (!immuned)
792 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
793 return;
797 // This is new target calculate data for him
799 // Get spell hit result on target
800 TargetInfo target;
801 target.targetGUID = targetGUID; // Store target GUID
802 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
803 target.processed = false; // Effects not apply on target
805 // Calculate hit result
806 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
808 // Spell have speed - need calculate incoming time
809 if (m_spellInfo->speed > 0.0f)
811 // calculate spell incoming interval
812 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
813 if (dist < 5.0f) dist = 5.0f;
814 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
816 // Calculate minimum incoming time
817 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
818 m_delayMoment = target.timeDelay;
820 else
821 target.timeDelay = 0LL;
823 // If target reflect spell back to caster
824 if (target.missCondition==SPELL_MISS_REFLECT)
826 // Calculate reflected spell result on caster
827 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
829 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
830 target.reflectResult = SPELL_MISS_PARRY;
832 // Increase time interval for reflected spells by 1.5
833 target.timeDelay+=target.timeDelay>>1;
835 else
836 target.reflectResult = SPELL_MISS_NONE;
838 // Add target to list
839 m_UniqueTargetInfo.push_back(target);
842 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
844 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
845 if (unit)
846 AddUnitTarget(unit, effIndex);
849 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
851 if( m_spellInfo->Effect[effIndex]==0 )
852 return;
854 uint64 targetGUID = pVictim->GetGUID();
856 // Lookup target in already in list
857 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
859 if (targetGUID == ihit->targetGUID) // Found in list
861 ihit->effectMask |= 1<<effIndex; // Add only effect mask
862 return;
866 // This is new target calculate data for him
868 GOTargetInfo target;
869 target.targetGUID = targetGUID;
870 target.effectMask = 1<<effIndex;
871 target.processed = false; // Effects not apply on target
873 // Spell have speed - need calculate incoming time
874 if (m_spellInfo->speed > 0.0f)
876 // calculate spell incoming interval
877 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
878 if (dist < 5.0f) dist = 5.0f;
879 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
880 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
881 m_delayMoment = target.timeDelay;
883 else
884 target.timeDelay = 0LL;
886 // Add target to list
887 m_UniqueGOTargetInfo.push_back(target);
890 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
892 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
893 if (go)
894 AddGOTarget(go, effIndex);
897 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
899 if( m_spellInfo->Effect[effIndex]==0 )
900 return;
902 // Lookup target in already in list
903 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
905 if (pitem == ihit->item) // Found in list
907 ihit->effectMask |= 1<<effIndex; // Add only effect mask
908 return;
912 // This is new target add data
914 ItemTargetInfo target;
915 target.item = pitem;
916 target.effectMask = 1<<effIndex;
917 m_UniqueItemInfo.push_back(target);
920 void Spell::DoAllEffectOnTarget(TargetInfo *target)
922 if (target->processed) // Check target
923 return;
924 target->processed = true; // Target checked in apply effects procedure
926 // Get mask of effects for target
927 uint32 mask = target->effectMask;
929 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
930 if (!unit)
931 return;
933 // Get original caster (if exist) and calculate damage/healing from him data
934 Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
936 // Skip if m_originalCaster not avaiable
937 if (!caster)
938 return;
940 SpellMissInfo missInfo = target->missCondition;
941 // Need init unitTarget by default unit (can changed in code on reflect)
942 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
943 unitTarget = unit;
945 // Reset damage/healing counter
946 m_damage = 0;
947 m_healing = 0;
949 // Fill base trigger info
950 uint32 procAttacker = m_procAttacker;
951 uint32 procVictim = m_procVictim;
952 uint32 procEx = PROC_EX_NONE;
954 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
955 DoSpellHitOnUnit(unit, mask);
956 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
958 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
959 DoSpellHitOnUnit(m_caster, mask);
962 // All calculated do it!
963 // Do healing and triggers
964 if (m_healing)
966 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
967 uint32 addhealth = m_healing;
968 if (crit)
970 procEx |= PROC_EX_CRITICAL_HIT;
971 addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
973 else
974 procEx |= PROC_EX_NORMAL_HIT;
976 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
978 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
979 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
980 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
982 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
984 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
985 if(caster->GetTypeId()==TYPEID_PLAYER)
986 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
987 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
989 // Do damage and triggers
990 else if (m_damage)
992 // Fill base damage struct (unitTarget - is real spell target)
993 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
995 // Add bonuses and fill damageInfo struct
996 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
998 // Send log damage message to client
999 caster->SendSpellNonMeleeDamageLog(&damageInfo);
1001 procEx = createProcExtendMask(&damageInfo, missInfo);
1002 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1004 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1005 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1006 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
1008 caster->DealSpellDamage(&damageInfo, true);
1010 // Judgement of Blood
1011 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1013 int32 damagePoint = damageInfo.damage * 33 / 100;
1014 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1017 // Passive spell hits/misses or active spells only misses (only triggers)
1018 else
1020 // Fill base damage struct (unitTarget - is real spell target)
1021 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1022 procEx = createProcExtendMask(&damageInfo, missInfo);
1023 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1024 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1025 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1028 // Call scripted function for AI if this spell is casted upon a creature (except pets)
1029 if(IS_CREATURE_GUID(target->targetGUID))
1031 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1032 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1033 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1034 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1036 if(((Creature*)unit)->AI())
1037 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1041 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1043 if(!unit || !effectMask)
1044 return;
1046 // Recheck immune (only for delayed spells)
1047 if( m_spellInfo->speed && (
1048 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1049 unit->IsImmunedToSpell(m_spellInfo)))
1051 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1052 return;
1055 if (unit->GetTypeId() == TYPEID_PLAYER)
1057 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1058 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1061 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1063 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1066 if( m_caster != unit )
1068 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1069 if (m_spellInfo->speed > 0.0f &&
1070 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1071 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1073 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1074 return;
1077 if( !m_caster->IsFriendlyTo(unit) )
1079 // for delayed spells ignore not visible explicit target
1080 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1082 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1083 return;
1086 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1088 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1090 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1091 unit->SetStandState(UNIT_STAND_STATE_STAND);
1093 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1094 ((Creature*)unit)->AI()->AttackStart(m_caster);
1096 unit->SetInCombatWith(m_caster);
1097 m_caster->SetInCombatWith(unit);
1099 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1101 m_caster->SetContestedPvP(attackedPlayer);
1103 unit->AddThreat(m_caster, 0.0f);
1106 else
1108 // for delayed spells ignore negative spells (after duel end) for friendly targets
1109 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1111 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1112 return;
1115 // assisting case, healing and resurrection
1116 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1117 m_caster->SetContestedPvP();
1118 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1120 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1121 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1126 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1127 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1128 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1129 // Increase Diminishing on unit, current informations for actually casts will use values above
1130 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1131 unit->IncrDiminishing(m_diminishGroup);
1133 // Apply additional spell effects to target
1134 if (m_preCastSpell)
1135 m_caster->CastSpell(unit,m_preCastSpell, true, m_CastItem);
1137 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1139 if (effectMask & (1<<effectNumber))
1141 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1142 if ( m_applyMultiplierMask & (1 << effectNumber) )
1144 // Get multiplier
1145 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1146 // Apply multiplier mods
1147 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1148 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1149 m_damageMultipliers[effectNumber] *= multiplier;
1155 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1157 if (target->processed) // Check target
1158 return;
1159 target->processed = true; // Target checked in apply effects procedure
1161 uint32 effectMask = target->effectMask;
1162 if(!effectMask)
1163 return;
1165 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1166 if(!go)
1167 return;
1169 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1170 if (effectMask & (1<<effectNumber))
1171 HandleEffects(NULL,NULL,go,effectNumber);
1173 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1174 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1175 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1176 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1179 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1181 uint32 effectMask = target->effectMask;
1182 if(!target->item || !effectMask)
1183 return;
1185 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1186 if (effectMask & (1<<effectNumber))
1187 HandleEffects(NULL, target->item, NULL, effectNumber);
1190 bool Spell::IsAliveUnitPresentInTargetList()
1192 // Not need check return true
1193 if (m_needAliveTargetMask == 0)
1194 return true;
1196 uint8 needAliveTargetMask = m_needAliveTargetMask;
1198 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1200 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1202 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1204 if (unit && unit->isAlive())
1205 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1209 // is all effects from m_needAliveTargetMask have alive targets
1210 return needAliveTargetMask==0;
1213 // Helper for Chain Healing
1214 // Spell target first
1215 // Raidmates then descending by injury suffered (MaxHealth - Health)
1216 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1217 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1219 const Unit* MainTarget;
1220 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1221 // functor for operator ">"
1222 bool operator()(Unit const* _Left, Unit const* _Right) const
1224 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1226 int32 ChainHealingHash(Unit const* Target) const
1228 if (Target == MainTarget)
1229 return 0;
1230 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1231 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1233 if (Target->GetHealth() == Target->GetMaxHealth())
1234 return 40000;
1235 else
1236 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1238 else
1239 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1243 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1245 public:
1246 const Unit* MainTarget;
1247 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1249 bool operator()(const Unit* Target)
1251 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1255 // Helper for targets nearest to the spell target
1256 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1257 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1259 const Unit* MainTarget;
1260 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1261 // functor for operator ">"
1262 bool operator()(const Unit* _Left, const Unit* _Right) const
1264 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1268 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1270 float radius;
1271 if (m_spellInfo->EffectRadiusIndex[i])
1272 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1273 else
1274 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1276 if(m_originalCaster)
1277 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1278 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1280 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1281 if(m_originalCaster)
1282 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1283 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1285 // Get spell max affected targets
1286 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1287 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1288 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1290 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1291 continue;
1292 unMaxTargets+=(*m)->GetModifier()->m_amount;
1294 switch(cur)
1296 case TARGET_TOTEM_EARTH:
1297 case TARGET_TOTEM_WATER:
1298 case TARGET_TOTEM_AIR:
1299 case TARGET_TOTEM_FIRE:
1300 case TARGET_SELF:
1301 case TARGET_SELF2:
1302 case TARGET_DYNAMIC_OBJECT:
1303 case TARGET_AREAEFFECT_CUSTOM:
1304 case TARGET_AREAEFFECT_CUSTOM_2:
1305 case TARGET_SUMMON:
1307 TagUnitMap.push_back(m_caster);
1308 break;
1310 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1312 m_targets.m_targetMask = 0;
1313 unMaxTargets = EffectChainTarget;
1314 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1316 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1317 Cell cell(p);
1318 cell.data.Part.reserved = ALL_DISTRICT;
1319 cell.SetNoCreate();
1321 std::list<Unit *> tempUnitMap;
1324 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1325 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1327 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1328 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1330 CellLock<GridReadGuard> cell_lock(cell, p);
1331 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1332 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1335 if(tempUnitMap.empty())
1336 break;
1338 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1340 //Now to get us a random target that's in the initial range of the spell
1341 uint32 t = 0;
1342 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1343 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1344 ++t, ++itr;
1346 if(!t)
1347 break;
1349 itr = tempUnitMap.begin();
1350 std::advance(itr, rand()%t);
1351 Unit *pUnitTarget = *itr;
1352 TagUnitMap.push_back(pUnitTarget);
1354 tempUnitMap.erase(itr);
1356 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1358 t = unMaxTargets - 1;
1359 Unit *prev = pUnitTarget;
1360 std::list<Unit*>::iterator next = tempUnitMap.begin();
1362 while(t && next != tempUnitMap.end() )
1364 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1365 break;
1367 if(!prev->IsWithinLOSInMap(*next))
1369 ++next;
1370 continue;
1373 prev = *next;
1374 TagUnitMap.push_back(prev);
1375 tempUnitMap.erase(next);
1376 tempUnitMap.sort(TargetDistanceOrder(prev));
1377 next = tempUnitMap.begin();
1379 --t;
1381 }break;
1382 case TARGET_RANDOM_FRIEND_CHAIN_IN_AREA:
1384 m_targets.m_targetMask = 0;
1385 unMaxTargets = EffectChainTarget;
1386 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1387 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1388 Cell cell(p);
1389 cell.data.Part.reserved = ALL_DISTRICT;
1390 cell.SetNoCreate();
1391 std::list<Unit *> tempUnitMap;
1393 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1394 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1396 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1397 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1399 CellLock<GridReadGuard> cell_lock(cell, p);
1400 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1401 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1404 if(tempUnitMap.empty())
1405 break;
1407 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1409 //Now to get us a random target that's in the initial range of the spell
1410 uint32 t = 0;
1411 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1412 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1413 ++t, ++itr;
1415 if(!t)
1416 break;
1418 itr = tempUnitMap.begin();
1419 std::advance(itr, rand()%t);
1420 Unit *pUnitTarget = *itr;
1421 TagUnitMap.push_back(pUnitTarget);
1423 tempUnitMap.erase(itr);
1425 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1427 t = unMaxTargets - 1;
1428 Unit *prev = pUnitTarget;
1429 std::list<Unit*>::iterator next = tempUnitMap.begin();
1431 while(t && next != tempUnitMap.end() )
1433 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1434 break;
1436 if(!prev->IsWithinLOSInMap(*next))
1438 ++next;
1439 continue;
1441 prev = *next;
1442 TagUnitMap.push_back(prev);
1443 tempUnitMap.erase(next);
1444 tempUnitMap.sort(TargetDistanceOrder(prev));
1445 next = tempUnitMap.begin();
1446 --t;
1448 }break;
1449 case TARGET_PET:
1451 Pet* tmpUnit = m_caster->GetPet();
1452 if (!tmpUnit) break;
1453 TagUnitMap.push_back(tmpUnit);
1454 break;
1456 case TARGET_CHAIN_DAMAGE:
1458 if (EffectChainTarget <= 1)
1460 Unit* pUnitTarget = SelectMagnetTarget();
1461 if(pUnitTarget)
1462 TagUnitMap.push_back(pUnitTarget);
1464 else
1466 Unit* pUnitTarget = m_targets.getUnitTarget();
1467 if(!pUnitTarget)
1468 break;
1470 unMaxTargets = EffectChainTarget;
1472 float max_range;
1473 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1474 max_range = radius; //
1475 else
1476 //FIXME: This very like horrible hack and wrong for most spells
1477 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1479 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1480 Cell cell(p);
1481 cell.data.Part.reserved = ALL_DISTRICT;
1482 cell.SetNoCreate();
1484 Unit* originalCaster = GetOriginalCaster();
1485 if(originalCaster)
1487 std::list<Unit *> tempUnitMap;
1490 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1491 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1493 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1494 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1496 CellLock<GridReadGuard> cell_lock(cell, p);
1497 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1498 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1501 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1503 if(tempUnitMap.empty())
1504 break;
1506 if(*tempUnitMap.begin() == pUnitTarget)
1507 tempUnitMap.erase(tempUnitMap.begin());
1509 TagUnitMap.push_back(pUnitTarget);
1510 uint32 t = unMaxTargets - 1;
1511 Unit *prev = pUnitTarget;
1512 std::list<Unit*>::iterator next = tempUnitMap.begin();
1514 while(t && next != tempUnitMap.end() )
1516 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1517 break;
1519 if(!prev->IsWithinLOSInMap(*next))
1521 ++next;
1522 continue;
1525 prev = *next;
1526 TagUnitMap.push_back(prev);
1527 tempUnitMap.erase(next);
1528 tempUnitMap.sort(TargetDistanceOrder(prev));
1529 next = tempUnitMap.begin();
1531 --t;
1535 }break;
1536 case TARGET_ALL_ENEMY_IN_AREA:
1538 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1539 Cell cell(p);
1540 cell.data.Part.reserved = ALL_DISTRICT;
1541 cell.SetNoCreate();
1543 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1545 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1546 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1548 CellLock<GridReadGuard> cell_lock(cell, p);
1549 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1550 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1551 }break;
1552 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1554 // targets the ground, not the units in the area
1555 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1557 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1558 Cell cell(p);
1559 cell.data.Part.reserved = ALL_DISTRICT;
1560 cell.SetNoCreate();
1562 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1564 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1565 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1567 CellLock<GridReadGuard> cell_lock(cell, p);
1568 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1569 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1571 // exclude caster (this can be important if this not original caster)
1572 TagUnitMap.remove(m_caster);
1574 }break;
1575 case TARGET_DUELVSPLAYER_COORDINATES:
1577 if(Unit* currentTarget = m_targets.getUnitTarget())
1579 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1580 TagUnitMap.push_back(currentTarget);
1582 }break;
1583 case TARGET_ALL_PARTY_AROUND_CASTER:
1584 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1585 case TARGET_ALL_PARTY:
1586 case TARGET_ALL_RAID_AROUND_CASTER:
1588 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1589 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1591 if(pGroup)
1593 uint8 subgroup = pTarget->GetSubGroup();
1595 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1597 Player* Target = itr->getSource();
1599 // IsHostileTo check duel and controlled by enemy
1600 if( Target &&
1601 (cur==TARGET_ALL_RAID_AROUND_CASTER || Target->GetSubGroup()==subgroup) &&
1602 !m_caster->IsHostileTo(Target) )
1604 if( m_caster->IsWithinDistInMap(Target, radius) )
1605 TagUnitMap.push_back(Target);
1607 if(Pet* pet = Target->GetPet())
1608 if( m_caster->IsWithinDistInMap(pet, radius) )
1609 TagUnitMap.push_back(pet);
1613 else
1615 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1616 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1617 TagUnitMap.push_back(ownerOrSelf);
1618 if(Pet* pet = ownerOrSelf->GetPet())
1619 if( m_caster->IsWithinDistInMap(pet, radius) )
1620 TagUnitMap.push_back(pet);
1622 }break;
1623 case TARGET_SINGLE_FRIEND:
1624 case TARGET_SINGLE_FRIEND_2:
1626 if(m_targets.getUnitTarget())
1627 TagUnitMap.push_back(m_targets.getUnitTarget());
1628 }break;
1629 case TARGET_NONCOMBAT_PET:
1631 if(Unit* target = m_targets.getUnitTarget())
1632 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1633 TagUnitMap.push_back(target);
1634 }break;
1635 case TARGET_CASTER_COORDINATES:
1637 // Check original caster is GO - set its coordinates as dst cast
1638 WorldObject *caster = NULL;
1639 if (m_originalCasterGUID)
1640 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
1641 if (!caster)
1642 caster = m_caster;
1643 // Set dest for targets
1644 m_targets.setDestination(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ());
1645 }break;
1646 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1648 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1649 Cell cell(p);
1650 cell.data.Part.reserved = ALL_DISTRICT;
1651 cell.SetNoCreate();
1653 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1655 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1656 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1658 CellLock<GridReadGuard> cell_lock(cell, p);
1659 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1660 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1661 }break;
1662 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1664 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1665 Cell cell(p);
1666 cell.data.Part.reserved = ALL_DISTRICT;
1667 cell.SetNoCreate();
1669 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1671 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1672 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1674 CellLock<GridReadGuard> cell_lock(cell, p);
1675 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1676 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1677 }break;
1678 // TARGET_SINGLE_PARTY means that the spells can only be casted on a party member and not on the caster (some seals, fire shield from imp, etc..)
1679 case TARGET_SINGLE_PARTY:
1681 Unit *target = m_targets.getUnitTarget();
1682 // Thoses spells apparently can't be casted on the caster.
1683 if( target && target != m_caster)
1685 // Can only be casted on group's members or its pets
1686 Group *pGroup = NULL;
1688 Unit* owner = m_caster->GetCharmerOrOwner();
1689 Unit *targetOwner = target->GetCharmerOrOwner();
1690 if(owner)
1692 if(owner->GetTypeId() == TYPEID_PLAYER)
1694 if( target == owner )
1696 TagUnitMap.push_back(target);
1697 break;
1699 pGroup = ((Player*)owner)->GetGroup();
1702 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1704 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1706 TagUnitMap.push_back(target);
1707 break;
1709 pGroup = ((Player*)m_caster)->GetGroup();
1712 if(pGroup)
1714 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1715 if(targetOwner)
1717 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1718 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1719 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1720 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1722 TagUnitMap.push_back(target);
1725 // 1Our target can be a player who is on our group
1726 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1728 TagUnitMap.push_back(target);
1732 }break;
1733 case TARGET_GAMEOBJECT:
1735 if(m_targets.getGOTarget())
1736 AddGOTarget(m_targets.getGOTarget(), i);
1737 }break;
1738 case TARGET_IN_FRONT_OF_CASTER:
1740 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1741 Cell cell(p);
1742 cell.data.Part.reserved = ALL_DISTRICT;
1743 cell.SetNoCreate();
1745 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1746 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1748 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1749 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1751 CellLock<GridReadGuard> cell_lock(cell, p);
1752 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1753 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1754 }break;
1755 case TARGET_DUELVSPLAYER:
1757 Unit *target = m_targets.getUnitTarget();
1758 if(target)
1760 if(m_caster->IsFriendlyTo(target))
1762 TagUnitMap.push_back(target);
1764 else
1766 Unit* pUnitTarget = SelectMagnetTarget();
1767 if(pUnitTarget)
1768 TagUnitMap.push_back(pUnitTarget);
1771 }break;
1772 case TARGET_GAMEOBJECT_ITEM:
1774 if(m_targets.getGOTargetGUID())
1775 AddGOTarget(m_targets.getGOTarget(), i);
1776 else if(m_targets.getItemTarget())
1777 AddItemTarget(m_targets.getItemTarget(), i);
1778 break;
1780 case TARGET_MASTER:
1782 if(Unit* owner = m_caster->GetCharmerOrOwner())
1783 TagUnitMap.push_back(owner);
1784 break;
1786 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1788 // targets the ground, not the units in the area
1789 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1791 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1792 Cell cell(p);
1793 cell.data.Part.reserved = ALL_DISTRICT;
1794 cell.SetNoCreate();
1796 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1798 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1799 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1801 CellLock<GridReadGuard> cell_lock(cell, p);
1802 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1803 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1805 }break;
1806 case TARGET_MINION:
1808 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1809 TagUnitMap.push_back(m_caster);
1810 }break;
1811 case TARGET_SINGLE_ENEMY:
1813 Unit* pUnitTarget = SelectMagnetTarget();
1814 if(pUnitTarget)
1815 TagUnitMap.push_back(pUnitTarget);
1816 }break;
1817 case TARGET_AREAEFFECT_PARTY:
1819 Unit* owner = m_caster->GetCharmerOrOwner();
1820 Player *pTarget = NULL;
1822 if(owner)
1824 TagUnitMap.push_back(m_caster);
1825 if(owner->GetTypeId() == TYPEID_PLAYER)
1826 pTarget = (Player*)owner;
1828 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1830 if(Unit* target = m_targets.getUnitTarget())
1832 if( target->GetTypeId() != TYPEID_PLAYER)
1834 if(((Creature*)target)->isPet())
1836 Unit *targetOwner = target->GetOwner();
1837 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1838 pTarget = (Player*)targetOwner;
1841 else
1842 pTarget = (Player*)target;
1846 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1848 if(pGroup)
1850 uint8 subgroup = pTarget->GetSubGroup();
1852 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1854 Player* Target = itr->getSource();
1856 // IsHostileTo check duel and controlled by enemy
1857 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1859 if( pTarget->IsWithinDistInMap(Target, radius) )
1860 TagUnitMap.push_back(Target);
1862 if(Pet* pet = Target->GetPet())
1863 if( pTarget->IsWithinDistInMap(pet, radius) )
1864 TagUnitMap.push_back(pet);
1868 else if (owner)
1870 if(m_caster->IsWithinDistInMap(owner, radius))
1871 TagUnitMap.push_back(owner);
1873 else if(pTarget)
1875 TagUnitMap.push_back(pTarget);
1877 if(Pet* pet = pTarget->GetPet())
1878 if( m_caster->IsWithinDistInMap(pet, radius) )
1879 TagUnitMap.push_back(pet);
1882 }break;
1883 case TARGET_SCRIPT:
1885 if(m_targets.getUnitTarget())
1886 TagUnitMap.push_back(m_targets.getUnitTarget());
1887 if(m_targets.getItemTarget())
1888 AddItemTarget(m_targets.getItemTarget(), i);
1889 }break;
1890 case TARGET_SELF_FISHING:
1892 TagUnitMap.push_back(m_caster);
1893 }break;
1894 case TARGET_CHAIN_HEAL:
1896 Unit* pUnitTarget = m_targets.getUnitTarget();
1897 if(!pUnitTarget)
1898 break;
1900 if (EffectChainTarget <= 1)
1901 TagUnitMap.push_back(pUnitTarget);
1902 else
1904 unMaxTargets = EffectChainTarget;
1905 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1907 std::list<Unit *> tempUnitMap;
1910 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1911 Cell cell(p);
1912 cell.data.Part.reserved = ALL_DISTRICT;
1913 cell.SetNoCreate();
1915 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1917 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1918 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1920 CellLock<GridReadGuard> cell_lock(cell, p);
1921 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1922 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1926 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1927 tempUnitMap.push_front(m_caster);
1929 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1931 if(tempUnitMap.empty())
1932 break;
1934 if(*tempUnitMap.begin() == pUnitTarget)
1935 tempUnitMap.erase(tempUnitMap.begin());
1937 TagUnitMap.push_back(pUnitTarget);
1938 uint32 t = unMaxTargets - 1;
1939 Unit *prev = pUnitTarget;
1940 std::list<Unit*>::iterator next = tempUnitMap.begin();
1942 while(t && next != tempUnitMap.end() )
1944 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1945 break;
1947 if(!prev->IsWithinLOSInMap(*next))
1949 ++next;
1950 continue;
1953 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1955 next = tempUnitMap.erase(next);
1956 continue;
1959 prev = *next;
1960 TagUnitMap.push_back(prev);
1961 tempUnitMap.erase(next);
1962 tempUnitMap.sort(TargetDistanceOrder(prev));
1963 next = tempUnitMap.begin();
1965 --t;
1968 }break;
1969 case TARGET_CURRENT_ENEMY_COORDINATES:
1971 Unit* currentTarget = m_targets.getUnitTarget();
1972 if(currentTarget)
1974 TagUnitMap.push_back(currentTarget);
1975 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1976 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1978 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1979 Cell cell(p);
1980 cell.data.Part.reserved = ALL_DISTRICT;
1981 cell.SetNoCreate();
1982 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1983 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1984 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1985 CellLock<GridReadGuard> cell_lock(cell, p);
1986 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1987 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1990 }break;
1991 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1993 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1994 ? (Player*)m_targets.getUnitTarget() : NULL;
1996 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1997 if(pGroup)
1999 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
2001 Player* Target = itr->getSource();
2003 // IsHostileTo check duel and controlled by enemy
2004 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
2005 targetPlayer->getClass() == Target->getClass() &&
2006 !m_caster->IsHostileTo(Target) )
2008 TagUnitMap.push_back(Target);
2012 else if(m_targets.getUnitTarget())
2013 TagUnitMap.push_back(m_targets.getUnitTarget());
2014 break;
2016 case TARGET_TABLE_X_Y_Z_COORDINATES:
2018 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
2019 if(st)
2021 if (st->target_mapId == m_caster->GetMapId())
2022 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
2024 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
2025 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
2027 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
2028 Cell cell(p);
2029 cell.data.Part.reserved = ALL_DISTRICT;
2030 cell.SetNoCreate();
2032 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
2033 // Select friendly targets for positive effect
2034 if (IsPositiveEffect(m_spellInfo->Id, i))
2035 targetB = SPELL_TARGETS_FRIENDLY;
2037 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
2039 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
2040 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
2042 CellLock<GridReadGuard> cell_lock(cell, p);
2043 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
2044 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
2047 else
2048 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
2049 }break;
2050 case TARGET_BEHIND_VICTIM:
2052 Unit *pTarget = m_caster->getVictim();
2053 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
2054 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
2056 if(pTarget)
2058 float _target_x, _target_y, _target_z;
2059 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
2060 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
2061 m_targets.setDestination(_target_x, _target_y, _target_z);
2063 }break;
2064 case TARGET_DYNAMIC_OBJECT_COORDINATES:
2066 // if parent spell create dynamic object extract area from it
2067 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
2068 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
2069 }break;
2070 default:
2071 break;
2074 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2076 // make sure one unit is always removed per iteration
2077 uint32 removed_utarget = 0;
2078 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2080 next = itr;
2081 ++next;
2082 if (!*itr) continue;
2083 if ((*itr) == m_targets.getUnitTarget())
2085 TagUnitMap.erase(itr);
2086 removed_utarget = 1;
2087 // break;
2090 // remove random units from the map
2091 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2093 uint32 poz = urand(0, TagUnitMap.size()-1);
2094 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2096 if (!*itr) continue;
2097 if (!poz)
2099 TagUnitMap.erase(itr);
2100 break;
2104 // the player's target will always be added to the map
2105 if (removed_utarget && m_targets.getUnitTarget())
2106 TagUnitMap.push_back(m_targets.getUnitTarget());
2110 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2112 m_targets = *targets;
2114 m_spellState = SPELL_STATE_PREPARING;
2116 m_castPositionX = m_caster->GetPositionX();
2117 m_castPositionY = m_caster->GetPositionY();
2118 m_castPositionZ = m_caster->GetPositionZ();
2119 m_castOrientation = m_caster->GetOrientation();
2121 if(triggeredByAura)
2122 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2124 // create and add update event for this spell
2125 SpellEvent* Event = new SpellEvent(this);
2126 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2128 //Prevent casting at cast another spell (ServerSide check)
2129 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2131 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2132 finish(false);
2133 return;
2136 // Fill cost data
2137 m_powerCost = CalculatePowerCost();
2139 uint8 result = CanCast(true);
2140 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2142 if(triggeredByAura)
2144 SendChannelUpdate(0);
2145 triggeredByAura->SetAuraDuration(0);
2147 SendCastResult(result);
2148 finish(false);
2149 return;
2152 // Prepare data for triggers
2153 prepareDataForTriggerSystem();
2155 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2156 m_casttime = GetSpellCastTime(m_spellInfo, this);
2158 // set timer base at cast time
2159 ReSetTimer();
2161 // stealth must be removed at cast starting (at show channel bar)
2162 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2163 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2165 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2166 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2169 if(m_IsTriggeredSpell)
2170 cast(true);
2171 else
2173 m_caster->SetCurrentCastedSpell( this );
2174 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2175 SendSpellStart();
2179 void Spell::cancel()
2181 if(m_spellState == SPELL_STATE_FINISHED)
2182 return;
2184 m_autoRepeat = false;
2185 switch (m_spellState)
2187 case SPELL_STATE_PREPARING:
2188 case SPELL_STATE_DELAYED:
2190 SendInterrupted(0);
2191 SendCastResult(SPELL_FAILED_INTERRUPTED);
2192 } break;
2194 case SPELL_STATE_CASTING:
2196 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2198 if( ihit->missCondition == SPELL_MISS_NONE )
2200 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2201 if( unit && unit->isAlive() )
2202 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2206 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2207 SendChannelUpdate(0);
2208 SendInterrupted(0);
2209 SendCastResult(SPELL_FAILED_INTERRUPTED);
2210 } break;
2212 default:
2214 } break;
2217 finish(false);
2218 m_caster->RemoveDynObject(m_spellInfo->Id);
2219 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2222 void Spell::cast(bool skipCheck)
2224 SetExecutedCurrently(true);
2226 uint8 castResult = 0;
2228 // update pointers base at GUIDs to prevent access to non-existed already object
2229 UpdatePointers();
2231 // cancel at lost main target unit
2232 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2234 cancel();
2235 SetExecutedCurrently(false);
2236 return;
2239 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2240 m_caster->SetInFront(m_targets.getUnitTarget());
2242 castResult = CheckPower();
2243 if(castResult != 0)
2245 SendCastResult(castResult);
2246 finish(false);
2247 SetExecutedCurrently(false);
2248 return;
2251 // triggered cast called from Spell::prepare where it was already checked
2252 if(!skipCheck)
2254 castResult = CanCast(false);
2255 if(castResult != 0)
2257 SendCastResult(castResult);
2258 finish(false);
2259 SetExecutedCurrently(false);
2260 return;
2264 switch(m_spellInfo->SpellFamilyName)
2266 case SPELLFAMILY_GENERIC:
2268 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2269 m_preCastSpell = 11196; // Recently Bandaged
2270 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2271 m_preCastSpell = 23230; // Blood Fury - Healing Reduction
2272 break;
2274 case SPELLFAMILY_MAGE:
2276 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2277 m_preCastSpell = 41425; // Hypothermia
2278 break;
2280 case SPELLFAMILY_PRIEST:
2282 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2283 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2284 m_preCastSpell = 6788; // Weakened Soul
2285 if (m_spellInfo->Id == 47585) // Dispersion (transform)
2286 m_preCastSpell = 60069; // Dispersion (mana regen)
2287 break;
2289 case SPELLFAMILY_PALADIN:
2291 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2292 m_preCastSpell = 25771; // Forbearance
2293 break;
2295 case SPELLFAMILY_SHAMAN:
2297 if (m_spellInfo->Id == 2825) // Bloodlust
2298 m_preCastSpell = 57724; // Sated
2299 else if (m_spellInfo->Id == 32182) // Heroism
2300 m_preCastSpell = 57723; // Exhaustion
2301 break;
2303 default:
2304 break;
2307 // Conflagrate - consumes immolate
2308 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2310 // for caster applied auras only
2311 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2312 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2314 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2315 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2317 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2318 break;
2323 // traded items have trade slot instead of guid in m_itemTargetGUID
2324 // set to real guid to be sent later to the client
2325 m_targets.updateTradeSlotItem();
2327 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2329 if (m_CastItem)
2330 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2332 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2335 // CAST SPELL
2336 SendSpellCooldown();
2338 TakePower();
2339 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2340 FillTargetMap();
2342 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2344 SetExecutedCurrently(false);
2345 return;
2348 SendCastResult(castResult);
2349 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2351 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2352 if (m_spellInfo->speed > 0.0f)
2355 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2356 // in case delayed spell remove item at cast delay start
2357 TakeCastItem();
2359 // Okay, maps created, now prepare flags
2360 m_immediateHandled = false;
2361 m_spellState = SPELL_STATE_DELAYED;
2362 SetDelayStart(0);
2364 else
2366 // Immediate spell, no big deal
2367 handle_immediate();
2370 SetExecutedCurrently(false);
2373 void Spell::handle_immediate()
2375 // start channeling if applicable
2376 if(IsChanneledSpell(m_spellInfo))
2378 int32 duration = GetSpellDuration(m_spellInfo);
2379 if (duration)
2381 // Apply duration mod
2382 if(Player* modOwner = m_caster->GetSpellModOwner())
2383 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
2384 m_spellState = SPELL_STATE_CASTING;
2385 SendChannelStart(duration);
2389 // process immediate effects (items, ground, etc.) also initialize some variables
2390 _handle_immediate_phase();
2392 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2393 DoAllEffectOnTarget(&(*ihit));
2395 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2396 DoAllEffectOnTarget(&(*ihit));
2398 // spell is finished, perform some last features of the spell here
2399 _handle_finish_phase();
2401 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2402 TakeCastItem();
2404 if(m_spellState != SPELL_STATE_CASTING)
2405 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2408 uint64 Spell::handle_delayed(uint64 t_offset)
2410 uint64 next_time = 0;
2412 if (!m_immediateHandled)
2414 _handle_immediate_phase();
2415 m_immediateHandled = true;
2418 // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
2419 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2421 if (ihit->processed == false)
2423 if ( ihit->timeDelay <= t_offset )
2424 DoAllEffectOnTarget(&(*ihit));
2425 else if( next_time == 0 || ihit->timeDelay < next_time )
2426 next_time = ihit->timeDelay;
2430 // now recheck gameobject targeting correctness
2431 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2433 if (ighit->processed == false)
2435 if ( ighit->timeDelay <= t_offset )
2436 DoAllEffectOnTarget(&(*ighit));
2437 else if( next_time == 0 || ighit->timeDelay < next_time )
2438 next_time = ighit->timeDelay;
2441 // All targets passed - need finish phase
2442 if (next_time == 0)
2444 // spell is finished, perform some last features of the spell here
2445 _handle_finish_phase();
2447 finish(true); // successfully finish spell cast
2449 // return zero, spell is finished now
2450 return 0;
2452 else
2454 // spell is unfinished, return next execution time
2455 return next_time;
2459 void Spell::_handle_immediate_phase()
2461 // handle some immediate features of the spell here
2462 HandleThreatSpells(m_spellInfo->Id);
2464 m_needSpellLog = IsNeedSendToClient();
2465 for(uint32 j = 0;j<3;j++)
2467 if(m_spellInfo->Effect[j]==0)
2468 continue;
2470 // apply Send Event effect to ground in case empty target lists
2471 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2473 HandleEffects(NULL,NULL,NULL, j);
2474 continue;
2477 // Don't do spell log, if is school damage spell
2478 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2479 m_needSpellLog = false;
2481 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2482 if(m_originalCaster)
2483 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2484 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2486 // initialize multipliers
2487 m_damageMultipliers[j] = 1.0f;
2488 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2489 (EffectChainTarget > 1) )
2490 m_applyMultiplierMask |= 1 << j;
2493 // initialize Diminishing Returns Data
2494 m_diminishLevel = DIMINISHING_LEVEL_1;
2495 m_diminishGroup = DIMINISHING_NONE;
2497 // process items
2498 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2499 DoAllEffectOnTarget(&(*ihit));
2501 // process ground
2502 for(uint32 j = 0;j<3;j++)
2504 // persistent area auras target only the ground
2505 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2506 HandleEffects(NULL,NULL,NULL, j);
2510 void Spell::_handle_finish_phase()
2512 // spell log
2513 if(m_needSpellLog)
2514 SendLogExecute();
2517 void Spell::SendSpellCooldown()
2519 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2520 return;
2522 Player* _player = (Player*)m_caster;
2523 // Add cooldown for max (disable spell)
2524 // Cooldown started on SendCooldownEvent call
2525 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2527 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2528 return;
2531 // init cooldown values
2532 uint32 cat = 0;
2533 int32 rec = -1;
2534 int32 catrec = -1;
2536 // some special item spells without correct cooldown in SpellInfo
2537 // cooldown information stored in item prototype
2538 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2540 if(m_CastItem)
2542 ItemPrototype const* proto = m_CastItem->GetProto();
2543 if(proto)
2545 for(int idx = 0; idx < 5; ++idx)
2547 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2549 cat = proto->Spells[idx].SpellCategory;
2550 rec = proto->Spells[idx].SpellCooldown;
2551 catrec = proto->Spells[idx].SpellCategoryCooldown;
2552 break;
2558 // if no cooldown found above then base at DBC data
2559 if(rec < 0 && catrec < 0)
2561 cat = m_spellInfo->Category;
2562 rec = m_spellInfo->RecoveryTime;
2563 catrec = m_spellInfo->CategoryRecoveryTime;
2566 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2567 // prevent 0 cooldowns set by another way
2568 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT))
2569 rec = _player->GetAttackTime(RANGED_ATTACK);
2571 // Now we have cooldown data (if found any), time to apply mods
2572 if(rec > 0)
2573 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2575 if(catrec > 0)
2576 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2578 // replace negative cooldowns by 0
2579 if (rec < 0) rec = 0;
2580 if (catrec < 0) catrec = 0;
2582 // no cooldown after applying spell mods
2583 if( rec == 0 && catrec == 0)
2584 return;
2586 time_t curTime = time(NULL);
2588 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2589 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2591 // self spell cooldown
2592 if(recTime > 0)
2593 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2595 // category spells
2596 if (catrec > 0)
2598 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2599 if(i_scstore != sSpellCategoryStore.end())
2601 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2603 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2604 continue;
2606 _player->AddSpellCooldown(*i_scset, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2612 void Spell::update(uint32 difftime)
2614 // update pointers based at it's GUIDs
2615 UpdatePointers();
2617 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2619 cancel();
2620 return;
2623 // check if the player caster has moved before the spell finished
2624 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2625 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2626 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2628 // always cancel for channeled spells
2629 if( m_spellState == SPELL_STATE_CASTING )
2630 cancel();
2631 // don't cancel for melee, autorepeat, triggered and instant spells
2632 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2633 cancel();
2636 switch(m_spellState)
2638 case SPELL_STATE_PREPARING:
2640 if(m_timer)
2642 if(difftime >= m_timer)
2643 m_timer = 0;
2644 else
2645 m_timer -= difftime;
2648 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2649 cast();
2650 } break;
2651 case SPELL_STATE_CASTING:
2653 if(m_timer > 0)
2655 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2657 // check if player has jumped before the channeling finished
2658 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2659 cancel();
2661 // check for incapacitating player states
2662 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2663 cancel();
2665 // check if player has turned if flag is set
2666 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2667 cancel();
2670 // check if there are alive targets left
2671 if (!IsAliveUnitPresentInTargetList())
2673 SendChannelUpdate(0);
2674 finish();
2677 if(difftime >= m_timer)
2678 m_timer = 0;
2679 else
2680 m_timer -= difftime;
2683 if(m_timer == 0)
2685 SendChannelUpdate(0);
2687 // channeled spell processed independently for quest targeting
2688 // cast at creature (or GO) quest objectives update at successful cast channel finished
2689 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2690 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2692 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2694 TargetInfo* target = &*ihit;
2695 if(!IS_CREATURE_GUID(target->targetGUID))
2696 continue;
2698 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2699 if (unit==NULL)
2700 continue;
2702 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2705 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2707 GOTargetInfo* target = &*ihit;
2709 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2710 if(!go)
2711 continue;
2713 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2717 finish();
2719 } break;
2720 default:
2722 }break;
2726 void Spell::finish(bool ok)
2728 if(!m_caster)
2729 return;
2731 if(m_spellState == SPELL_STATE_FINISHED)
2732 return;
2734 m_spellState = SPELL_STATE_FINISHED;
2736 // other code related only to successfully finished spells
2737 if(!ok)
2738 return;
2740 //remove spell mods
2741 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2742 ((Player*)m_caster)->RemoveSpellMods(this);
2744 // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2745 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2746 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2748 if (!(*i)->isAffectedOnSpell(m_spellInfo))
2749 continue;
2750 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2751 if( ihit->missCondition == SPELL_MISS_NONE )
2753 // check m_caster->GetGUID() let load auras at login and speedup most often case
2754 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2755 if (unit && unit->isAlive())
2757 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2758 uint32 auraSpellIdx = (*i)->GetEffIndex();
2759 // Calculate chance at that moment (can be depend for example from combo points)
2760 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2761 if(roll_chance_i(chance))
2762 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2767 // Heal caster for all health leech from all targets
2768 if (m_healthLeech)
2770 m_caster->ModifyHealth(m_healthLeech);
2771 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2774 if (IsMeleeAttackResetSpell())
2776 m_caster->resetAttackTimer(BASE_ATTACK);
2777 if(m_caster->haveOffhandWeapon())
2778 m_caster->resetAttackTimer(OFF_ATTACK);
2781 /*if (IsRangedAttackResetSpell())
2782 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2784 // Clear combo at finish state
2785 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2787 // Not drop combopoints if negative spell and if any miss on enemy exist
2788 bool needDrop = true;
2789 if (!IsPositiveSpell(m_spellInfo->Id))
2790 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2791 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2793 needDrop = false;
2794 break;
2796 if (needDrop)
2797 ((Player*)m_caster)->ClearComboPoints();
2800 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2801 if(!m_TriggerSpells.empty())
2802 TriggerSpell();
2804 // Stop Attack for some spells
2805 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2806 m_caster->AttackStop();
2809 void Spell::SendCastResult(uint8 result)
2811 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2812 return;
2814 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2815 return;
2817 if(result != 0)
2819 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2820 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2821 data << uint32(m_spellInfo->Id);
2822 data << uint8(result); // problem
2823 switch (result)
2825 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2826 data << uint32(m_spellInfo->RequiresSpellFocus);
2827 break;
2828 case SPELL_FAILED_REQUIRES_AREA:
2829 // hardcode areas limitation case
2830 switch(m_spellInfo->Id)
2832 case 41617: // Cenarion Mana Salve
2833 case 41619: // Cenarion Healing Salve
2834 data << uint32(3905);
2835 break;
2836 case 41618: // Bottled Nethergon Energy
2837 case 41620: // Bottled Nethergon Vapor
2838 data << uint32(3842);
2839 break;
2840 case 45373: // Bloodberry Elixir
2841 data << uint32(4075);
2842 break;
2843 default: // default case (don't must be)
2844 data << uint32(0);
2845 break;
2847 break;
2848 case SPELL_FAILED_TOTEMS:
2849 if(m_spellInfo->Totem[0])
2850 data << uint32(m_spellInfo->Totem[0]);
2851 if(m_spellInfo->Totem[1])
2852 data << uint32(m_spellInfo->Totem[1]);
2853 break;
2854 case SPELL_FAILED_TOTEM_CATEGORY:
2855 if(m_spellInfo->TotemCategory[0])
2856 data << uint32(m_spellInfo->TotemCategory[0]);
2857 if(m_spellInfo->TotemCategory[1])
2858 data << uint32(m_spellInfo->TotemCategory[1]);
2859 break;
2860 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2861 data << uint32(m_spellInfo->EquippedItemClass);
2862 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2863 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2864 break;
2866 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2870 void Spell::SendSpellStart()
2872 if(!IsNeedSendToClient())
2873 return;
2875 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2877 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2878 if(IsRangedSpell())
2879 castFlags |= CAST_FLAG_AMMO;
2881 if(m_spellInfo->runeCostID)
2882 castFlags |= CAST_FLAG_UNKNOWN10;
2884 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2886 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2887 if(m_CastItem)
2888 data.append(m_CastItem->GetPackGUID());
2889 else
2890 data.append(m_caster->GetPackGUID());
2892 data.append(m_caster->GetPackGUID());
2893 data << uint8(m_cast_count); // pending spell cast?
2894 data << uint32(m_spellInfo->Id); // spellId
2895 data << uint32(castFlags); // cast flags
2896 data << uint32(m_timer); // delay?
2898 m_targets.write(&data);
2900 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2901 data << uint32(0);
2903 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2905 uint8 v1 = 0;//m_runesState;
2906 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2907 data << uint8(v1); // runes state before
2908 data << uint8(v2); // runes state after
2909 for(uint8 i = 0; i < MAX_RUNES; ++i)
2911 uint8 m = (1 << i);
2912 if(m & v1) // usable before...
2913 if(!(m & v2)) // ...but on cooldown now...
2914 data << uint8(0); // some unknown byte (time?)
2918 if ( castFlags & CAST_FLAG_AMMO )
2919 WriteAmmoToPacket(&data);
2921 m_caster->SendMessageToSet(&data, true);
2924 void Spell::SendSpellGo()
2926 // not send invisible spell casting
2927 if(!IsNeedSendToClient())
2928 return;
2930 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2932 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2934 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2935 if(IsRangedSpell())
2936 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2938 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2940 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2941 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2942 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2945 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2947 if(m_CastItem)
2948 data.append(m_CastItem->GetPackGUID());
2949 else
2950 data.append(m_caster->GetPackGUID());
2952 data.append(m_caster->GetPackGUID());
2953 data << uint8(m_cast_count); // pending spell cast?
2954 data << uint32(m_spellInfo->Id); // spellId
2955 data << uint32(castFlags); // cast flags
2956 data << uint32(getMSTime()); // timestamp
2958 WriteSpellGoTargets(&data);
2960 m_targets.write(&data);
2962 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2963 data << uint32(0);
2965 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2967 uint8 v1 = m_runesState;
2968 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2969 data << uint8(v1); // runes state before
2970 data << uint8(v2); // runes state after
2971 for(uint8 i = 0; i < MAX_RUNES; ++i)
2973 uint8 m = (1 << i);
2974 if(m & v1) // usable before...
2975 if(!(m & v2)) // ...but on cooldown now...
2976 data << uint8(0); // some unknown byte (time?)
2980 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2982 data << float(0);
2983 data << uint32(0);
2986 if ( castFlags & CAST_FLAG_AMMO )
2987 WriteAmmoToPacket(&data);
2989 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2991 data << uint32(0);
2992 data << uint32(0);
2995 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2997 data << uint8(0);
3000 m_caster->SendMessageToSet(&data, true);
3003 void Spell::WriteAmmoToPacket( WorldPacket * data )
3005 uint32 ammoInventoryType = 0;
3006 uint32 ammoDisplayID = 0;
3008 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3010 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
3011 if(pItem)
3013 ammoInventoryType = pItem->GetProto()->InventoryType;
3014 if( ammoInventoryType == INVTYPE_THROWN )
3015 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
3016 else
3018 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
3019 if(ammoID)
3021 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
3022 if(pProto)
3024 ammoDisplayID = pProto->DisplayInfoID;
3025 ammoInventoryType = pProto->InventoryType;
3028 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
3030 ammoDisplayID = 5996; // normal arrow
3031 ammoInventoryType = INVTYPE_AMMO;
3036 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
3038 *data << uint32(ammoDisplayID);
3039 *data << uint32(ammoInventoryType);
3042 void Spell::WriteSpellGoTargets( WorldPacket * data )
3044 // This function also fill data for channeled spells:
3045 // m_needAliveTargetMask req for stop channelig if one target die
3046 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
3047 uint32 miss = 0;
3048 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3050 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
3052 // possibly SPELL_MISS_IMMUNE2 for this??
3053 ihit->missCondition = SPELL_MISS_IMMUNE2;
3054 miss++;
3056 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3057 hit++;
3058 else
3059 miss++;
3062 *data << (uint8)hit;
3063 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3064 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3066 *data << uint64(ihit->targetGUID);
3067 m_needAliveTargetMask |=ihit->effectMask;
3070 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3071 *data << uint64(ighit->targetGUID); // Always hits
3073 *data << (uint8)miss;
3074 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3076 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3078 *data << uint64(ihit->targetGUID);
3079 *data << uint8(ihit->missCondition);
3080 if( ihit->missCondition == SPELL_MISS_REFLECT )
3081 *data << uint8(ihit->reflectResult);
3084 // Reset m_needAliveTargetMask for non channeled spell
3085 if(!IsChanneledSpell(m_spellInfo))
3086 m_needAliveTargetMask = 0;
3089 void Spell::SendLogExecute()
3091 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3093 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3095 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3096 data.append(m_caster->GetPackGUID());
3097 else
3098 data.append(target->GetPackGUID());
3100 data << uint32(m_spellInfo->Id);
3101 uint32 count1 = 1;
3102 data << uint32(count1); // count1 (effect count?)
3103 for(uint32 i = 0; i < count1; ++i)
3105 data << uint32(m_spellInfo->Effect[0]); // spell effect
3106 uint32 count2 = 1;
3107 data << uint32(count2); // count2 (target count?)
3108 for(uint32 j = 0; j < count2; ++j)
3110 switch(m_spellInfo->Effect[0])
3112 case SPELL_EFFECT_POWER_DRAIN:
3113 if(Unit *unit = m_targets.getUnitTarget())
3114 data.append(unit->GetPackGUID());
3115 else
3116 data << uint8(0);
3117 data << uint32(0);
3118 data << uint32(0);
3119 data << float(0);
3120 break;
3121 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3122 if(Unit *unit = m_targets.getUnitTarget())
3123 data.append(unit->GetPackGUID());
3124 else
3125 data << uint8(0);
3126 data << uint32(0); // count?
3127 break;
3128 case SPELL_EFFECT_INTERRUPT_CAST:
3129 if(Unit *unit = m_targets.getUnitTarget())
3130 data.append(unit->GetPackGUID());
3131 else
3132 data << uint8(0);
3133 data << uint32(0); // spellid
3134 break;
3135 case SPELL_EFFECT_DURABILITY_DAMAGE:
3136 if(Unit *unit = m_targets.getUnitTarget())
3137 data.append(unit->GetPackGUID());
3138 else
3139 data << uint8(0);
3140 data << uint32(0);
3141 data << uint32(0);
3142 break;
3143 case SPELL_EFFECT_OPEN_LOCK:
3144 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3145 if(Item *item = m_targets.getItemTarget())
3146 data.append(item->GetPackGUID());
3147 else
3148 data << uint8(0);
3149 break;
3150 case SPELL_EFFECT_CREATE_ITEM:
3151 case SPELL_EFFECT_CREATE_ITEM_2:
3152 data << uint32(m_spellInfo->EffectItemType[0]);
3153 break;
3154 case SPELL_EFFECT_SUMMON:
3155 case SPELL_EFFECT_TRANS_DOOR:
3156 case SPELL_EFFECT_SUMMON_PET:
3157 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3158 case SPELL_EFFECT_CREATE_HOUSE:
3159 case SPELL_EFFECT_DUEL:
3160 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3161 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3162 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3163 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3164 if(Unit *unit = m_targets.getUnitTarget())
3165 data.append(unit->GetPackGUID());
3166 else if(m_targets.getItemTargetGUID())
3167 data.appendPackGUID(m_targets.getItemTargetGUID());
3168 else if(GameObject *go = m_targets.getGOTarget())
3169 data.append(go->GetPackGUID());
3170 else
3171 data << uint8(0); // guid
3172 break;
3173 case SPELL_EFFECT_FEED_PET:
3174 data << uint32(m_targets.getItemTargetEntry());
3175 break;
3176 case SPELL_EFFECT_DISMISS_PET:
3177 if(Unit *unit = m_targets.getUnitTarget())
3178 data.append(unit->GetPackGUID());
3179 else
3180 data << uint8(0);
3181 break;
3182 case SPELL_EFFECT_RESURRECT:
3183 case SPELL_EFFECT_RESURRECT_NEW:
3184 if(Unit *unit = m_targets.getUnitTarget())
3185 data.append(unit->GetPackGUID());
3186 else
3187 data << uint8(0);
3188 break;
3189 default:
3190 return;
3195 m_caster->SendMessageToSet(&data, true);
3198 void Spell::SendInterrupted(uint8 result)
3200 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3201 data.append(m_caster->GetPackGUID());
3202 data << uint8(m_cast_count);
3203 data << uint32(m_spellInfo->Id);
3204 data << uint8(result);
3205 m_caster->SendMessageToSet(&data, true);
3207 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3208 data.append(m_caster->GetPackGUID());
3209 data << uint8(m_cast_count);
3210 data << uint32(m_spellInfo->Id);
3211 data << uint8(result);
3212 m_caster->SendMessageToSet(&data, true);
3215 void Spell::SendChannelUpdate(uint32 time)
3217 if(time == 0)
3219 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3220 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3223 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3224 return;
3226 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3227 data.append(m_caster->GetPackGUID());
3228 data << uint32(time);
3230 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3233 void Spell::SendChannelStart(uint32 duration)
3235 WorldObject* target = NULL;
3237 // select first not resisted target from target list for _0_ effect
3238 if(!m_UniqueTargetInfo.empty())
3240 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3242 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3244 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3245 break;
3249 else if(!m_UniqueGOTargetInfo.empty())
3251 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3253 if(itr->effectMask & (1<<0) )
3255 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3256 break;
3261 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3263 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3264 data.append(m_caster->GetPackGUID());
3265 data << uint32(m_spellInfo->Id);
3266 data << uint32(duration);
3268 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3271 m_timer = duration;
3272 if(target)
3273 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3274 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3277 void Spell::SendResurrectRequest(Player* target)
3279 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3280 // However, the packet structure differs slightly
3282 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3284 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3285 data << uint64(m_caster->GetGUID());
3286 data << uint32(strlen(sentName)+1);
3288 data << sentName;
3289 data << uint8(0);
3291 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3292 target->GetSession()->SendPacket(&data);
3295 void Spell::SendPlaySpellVisual(uint32 SpellID)
3297 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3298 return;
3300 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3301 data << uint64(m_caster->GetGUID());
3302 data << uint32(SpellID); // spell visual id?
3303 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3306 void Spell::TakeCastItem()
3308 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3309 return;
3311 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3312 if(m_IsTriggeredSpell)
3313 return;
3315 ItemPrototype const *proto = m_CastItem->GetProto();
3317 if(!proto)
3319 // This code is to avoid a crash
3320 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3321 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3322 return;
3325 bool expendable = false;
3326 bool withoutCharges = false;
3328 for (int i = 0; i<5; i++)
3330 if (proto->Spells[i].SpellId)
3332 // item has limited charges
3333 if (proto->Spells[i].SpellCharges)
3335 if (proto->Spells[i].SpellCharges < 0)
3336 expendable = true;
3338 int32 charges = m_CastItem->GetSpellCharges(i);
3340 // item has charges left
3341 if (charges)
3343 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3344 if (proto->Stackable == 1)
3345 m_CastItem->SetSpellCharges(i, charges);
3346 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3349 // all charges used
3350 withoutCharges = (charges == 0);
3355 if (expendable && withoutCharges)
3357 uint32 count = 1;
3358 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3360 // prevent crash at access to deleted m_targets.getItemTarget
3361 if(m_CastItem==m_targets.getItemTarget())
3362 m_targets.setItemTarget(NULL);
3364 m_CastItem = NULL;
3368 void Spell::TakePower()
3370 if(m_CastItem || m_triggeredByAuraSpell)
3371 return;
3373 // health as power used
3374 if(m_spellInfo->powerType == POWER_HEALTH)
3376 m_caster->ModifyHealth( -(int32)m_powerCost );
3377 return;
3380 if(m_spellInfo->powerType >= MAX_POWERS)
3382 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3383 return;
3386 Powers powerType = Powers(m_spellInfo->powerType);
3388 if(powerType == POWER_RUNE)
3390 TakeRunePower();
3391 return;
3394 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3396 // Set the five second timer
3397 if (powerType == POWER_MANA && m_powerCost > 0)
3398 m_caster->SetLastManaUse(getMSTime());
3401 uint8 Spell::CheckRuneCost(uint32 runeCostID)
3403 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3404 return 0;
3406 Player *plr = (Player*)m_caster;
3408 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3409 return 0;
3411 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3413 if(!src)
3414 return 0;
3416 if(src->NoRuneCost())
3417 return 0;
3419 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3421 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3423 runeCost[i] = src->RuneCost[i];
3426 runeCost[RUNE_DEATH] = 0; // calculated later
3428 for(uint32 i = 0; i < MAX_RUNES; ++i)
3430 uint8 rune = plr->GetCurrentRune(i);
3431 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3433 runeCost[rune]--;
3437 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3439 if(runeCost[i] > 0)
3441 runeCost[RUNE_DEATH] += runeCost[i];
3445 if(runeCost[RUNE_DEATH] > 0)
3446 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3448 return 0;
3451 void Spell::TakeRunePower()
3453 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3454 return;
3456 Player *plr = (Player*)m_caster;
3458 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3459 return;
3461 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3463 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3464 return;
3466 m_runesState = plr->GetRunesState(); // store previous state
3468 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3470 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3472 runeCost[i] = src->RuneCost[i];
3475 runeCost[RUNE_DEATH] = 0; // calculated later
3477 for(uint32 i = 0; i < MAX_RUNES; ++i)
3479 uint8 rune = plr->GetCurrentRune(i);
3480 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3482 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3483 runeCost[rune]--;
3487 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3489 if(runeCost[RUNE_DEATH] > 0)
3491 for(uint32 i = 0; i < MAX_RUNES; ++i)
3493 uint8 rune = plr->GetCurrentRune(i);
3494 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3496 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3497 runeCost[rune]--;
3498 plr->ConvertRune(i, plr->GetBaseRune(i));
3499 if(runeCost[RUNE_DEATH] == 0)
3500 break;
3505 // you can gain some runic power when use runes
3506 float rp = src->runePowerGain;;
3507 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3508 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3511 void Spell::TakeReagents()
3513 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3514 return;
3516 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3517 return;
3519 Player* p_caster = (Player*)m_caster;
3520 if (p_caster->CanNoReagentCast(m_spellInfo))
3521 return;
3523 for(uint32 x=0;x<8;x++)
3525 if(m_spellInfo->Reagent[x] <= 0)
3526 continue;
3528 uint32 itemid = m_spellInfo->Reagent[x];
3529 uint32 itemcount = m_spellInfo->ReagentCount[x];
3531 // if CastItem is also spell reagent
3532 if (m_CastItem)
3534 ItemPrototype const *proto = m_CastItem->GetProto();
3535 if( proto && proto->ItemId == itemid )
3537 for(int s=0;s<5;s++)
3539 // CastItem will be used up and does not count as reagent
3540 int32 charges = m_CastItem->GetSpellCharges(s);
3541 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3543 ++itemcount;
3544 break;
3548 m_CastItem = NULL;
3552 // if getItemTarget is also spell reagent
3553 if (m_targets.getItemTargetEntry()==itemid)
3554 m_targets.setItemTarget(NULL);
3556 p_caster->DestroyItemCount(itemid, itemcount, true);
3560 void Spell::HandleThreatSpells(uint32 spellId)
3562 if(!m_targets.getUnitTarget() || !spellId)
3563 return;
3565 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3566 return;
3568 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3569 if(!threatSpell)
3570 return;
3572 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3574 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3577 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3579 unitTarget = pUnitTarget;
3580 itemTarget = pItemTarget;
3581 gameObjTarget = pGOTarget;
3583 uint8 eff = m_spellInfo->Effect[i];
3585 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3587 sLog.outDebug( "Spell: Effect : %u", eff);
3589 if(eff<TOTAL_SPELL_EFFECTS)
3591 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3592 (*this.*SpellEffects[eff])(i);
3595 else
3597 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3598 if (m_CastItem)
3599 EffectEnchantItemTmp(i);
3600 else
3602 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3603 eff, m_spellInfo->Id);
3609 void Spell::TriggerSpell()
3611 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3613 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3614 spell->prepare(&m_targets); // use original spell original targets
3618 uint8 Spell::CanCast(bool strict)
3620 // check cooldowns to prevent cheating
3621 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3623 if(m_triggeredByAuraSpell)
3624 return SPELL_FAILED_DONT_REPORT;
3625 else
3626 return SPELL_FAILED_NOT_READY;
3629 // only allow triggered spells if at an ended battleground
3630 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3631 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3632 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3633 return SPELL_FAILED_DONT_REPORT;
3635 // only check at first call, Stealth auras are already removed at second call
3636 // for now, ignore triggered spells
3637 if( strict && !m_IsTriggeredSpell)
3639 bool checkForm = true;
3640 // Ignore form req aura
3641 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3642 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3644 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3645 continue;
3646 checkForm = false;
3647 break;
3649 if (checkForm)
3651 // Cannot be used in this stance/form
3652 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3653 return shapeError;
3655 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3656 return SPELL_FAILED_ONLY_STEALTHED;
3660 // caster state requirements
3661 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3662 return SPELL_FAILED_CASTER_AURASTATE;
3663 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3664 return SPELL_FAILED_CASTER_AURASTATE;
3666 // Caster aura req check if need
3667 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3668 return SPELL_FAILED_CASTER_AURASTATE;
3669 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3670 return SPELL_FAILED_CASTER_AURASTATE;
3672 // cancel autorepeat spells if cast start when moving
3673 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3674 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3676 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3677 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3678 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3679 return SPELL_FAILED_MOVING;
3682 Unit *target = m_targets.getUnitTarget();
3684 if(target)
3686 // target state requirements (not allowed state), apply to self also
3687 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3688 return SPELL_FAILED_TARGET_AURASTATE;
3690 // Target aura req check if need
3691 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3692 return SPELL_FAILED_CASTER_AURASTATE;
3693 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3694 return SPELL_FAILED_CASTER_AURASTATE;
3696 if(target != m_caster)
3698 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3699 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3700 return SPELL_FAILED_TARGET_AURASTATE;
3702 // Not allow casting on flying player
3703 if (target->isInFlight())
3704 return SPELL_FAILED_BAD_TARGETS;
3706 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3707 return SPELL_FAILED_LINE_OF_SIGHT;
3709 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3710 // this case can be triggered if rank not found (too low-level target for first rank)
3711 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3713 for(int i=0;i<3;i++)
3715 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3716 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3717 return SPELL_FAILED_LOWLEVEL;
3721 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3723 // Additional check for some spells
3724 // If 0 spell effect empty - client not send target data (need use selection)
3725 // TODO: check it on next client version
3726 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3727 m_spellInfo->EffectImplicitTargetA[1] == TARGET_CHAIN_DAMAGE)
3729 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3730 m_targets.setUnitTarget(target);
3731 else
3732 return SPELL_FAILED_BAD_TARGETS;
3736 // check pet presents
3737 for(int j=0;j<3;j++)
3739 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3741 target = m_caster->GetPet();
3742 if(!target)
3744 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3745 return SPELL_FAILED_DONT_REPORT;
3746 else
3747 return SPELL_FAILED_NO_PET;
3749 break;
3753 //check creature type
3754 //ignore self casts (including area casts when caster selected as target)
3755 if(target != m_caster)
3757 if(!CheckTargetCreatureType(target))
3759 if(target->GetTypeId()==TYPEID_PLAYER)
3760 return SPELL_FAILED_TARGET_IS_PLAYER;
3761 else
3762 return SPELL_FAILED_BAD_TARGETS;
3766 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3767 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3768 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3770 // check correctness positive/negative cast target (pet cast real check and cheating check)
3771 if(IsPositiveSpell(m_spellInfo->Id))
3773 if(m_caster->IsHostileTo(target))
3774 return SPELL_FAILED_BAD_TARGETS;
3776 else
3778 if(m_caster->IsFriendlyTo(target))
3779 return SPELL_FAILED_BAD_TARGETS;
3783 if(IsPositiveSpell(m_spellInfo->Id))
3785 if(target->IsImmunedToSpell(m_spellInfo))
3786 return SPELL_FAILED_TARGET_AURASTATE;
3789 //Must be behind the target.
3790 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3792 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3793 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3795 SendInterrupted(2);
3796 return SPELL_FAILED_NOT_BEHIND;
3800 //Target must be facing you.
3801 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3803 SendInterrupted(2);
3804 return SPELL_FAILED_NOT_INFRONT;
3807 // check if target is in combat
3808 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3810 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3813 // Spell casted only on battleground
3814 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3815 if(!((Player*)m_caster)->InBattleGround())
3816 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3818 // do not allow spells to be cast in arenas
3819 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3820 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3821 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3822 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3823 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3824 if(mapEntry->IsBattleArena())
3825 return SPELL_FAILED_NOT_IN_ARENA;
3827 // zone check
3828 if (uint8 res= GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId(),
3829 m_caster->GetTypeId()==TYPEID_PLAYER ? ((Player*)m_caster)->GetBattleGroundId() : 0))
3830 return res;
3832 // not let players cast spells at mount (and let do it to creatures)
3833 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3834 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3836 if(m_caster->isInFlight())
3837 return SPELL_FAILED_NOT_FLYING;
3838 else
3839 return SPELL_FAILED_NOT_MOUNTED;
3842 // always (except passive spells) check items (focus object can be required for any type casts)
3843 if(!IsPassiveSpell(m_spellInfo->Id))
3844 if(uint8 castResult = CheckItems())
3845 return castResult;
3847 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3848 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3850 for(uint8 j = 0; j < 3; j++)
3852 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3853 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3854 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3855 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3857 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3858 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3859 if(lower==upper)
3860 sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = TARGET_SCRIPT or TARGET_SCRIPT_COORDINATES, but does not have record in `spell_script_target`",m_spellInfo->Id);
3862 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3863 float range = GetSpellMaxRange(srange);
3865 Creature* creatureScriptTarget = NULL;
3866 GameObject* goScriptTarget = NULL;
3868 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3870 switch(i_spellST->second.type)
3872 case SPELL_TARGET_TYPE_GAMEOBJECT:
3874 GameObject* p_GameObject = NULL;
3876 if(i_spellST->second.targetEntry)
3878 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3879 Cell cell(p);
3880 cell.data.Part.reserved = ALL_DISTRICT;
3882 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3883 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
3885 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3886 CellLock<GridReadGuard> cell_lock(cell, p);
3887 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3889 if(p_GameObject)
3891 // remember found target and range, next attempt will find more near target with another entry
3892 creatureScriptTarget = NULL;
3893 goScriptTarget = p_GameObject;
3894 range = go_check.GetLastRange();
3897 else if( focusObject ) //Focus Object
3899 float frange = m_caster->GetDistance(focusObject);
3900 if(range >= frange)
3902 creatureScriptTarget = NULL;
3903 goScriptTarget = focusObject;
3904 range = frange;
3907 break;
3909 case SPELL_TARGET_TYPE_CREATURE:
3910 case SPELL_TARGET_TYPE_DEAD:
3911 default:
3913 Creature *p_Creature = NULL;
3915 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3916 Cell cell(p);
3917 cell.data.Part.reserved = ALL_DISTRICT;
3918 cell.SetNoCreate(); // Really don't know what is that???
3920 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3921 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
3923 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3925 CellLock<GridReadGuard> cell_lock(cell, p);
3926 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
3928 if(p_Creature )
3930 creatureScriptTarget = p_Creature;
3931 goScriptTarget = NULL;
3932 range = u_check.GetLastRange();
3934 break;
3939 if(creatureScriptTarget)
3941 // store coordinates for TARGET_SCRIPT_COORDINATES
3942 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3943 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3945 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3947 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3948 AddUnitTarget(creatureScriptTarget, j);
3950 // store explicit target for TARGET_SCRIPT
3951 else
3952 AddUnitTarget(creatureScriptTarget, j);
3954 else if(goScriptTarget)
3956 // store coordinates for TARGET_SCRIPT_COORDINATES
3957 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3958 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3960 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3962 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3963 AddGOTarget(goScriptTarget, j);
3965 // store explicit target for TARGET_SCRIPT
3966 else
3967 AddGOTarget(goScriptTarget, j);
3969 //Missing DB Entry or targets for this spellEffect.
3970 else
3972 // not report target not existence for triggered spells
3973 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3974 return SPELL_FAILED_DONT_REPORT;
3975 else
3976 return SPELL_FAILED_BAD_TARGETS;
3982 if(!m_IsTriggeredSpell)
3983 if(uint8 castResult = CheckRange(strict))
3984 return castResult;
3987 if(uint8 castResult = CheckPower())
3988 return castResult;
3991 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
3992 if(uint8 castResult = CheckCasterAuras())
3993 return castResult;
3995 for (int i = 0; i < 3; i++)
3997 // for effects of spells that have only one target
3998 switch(m_spellInfo->Effect[i])
4000 case SPELL_EFFECT_DUMMY:
4002 if(m_spellInfo->SpellIconID == 1648) // Execute
4004 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4005 return SPELL_FAILED_BAD_TARGETS;
4007 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
4009 if(m_caster->IsInWater())
4010 return SPELL_FAILED_ONLY_ABOVEWATER;
4012 else if(m_spellInfo->SpellIconID==156) // Holy Shock
4014 // spell different for friends and enemies
4015 // hart version required facing
4016 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
4017 return SPELL_FAILED_UNIT_NOT_INFRONT;
4019 break;
4021 case SPELL_EFFECT_SCHOOL_DAMAGE:
4023 // Hammer of Wrath
4024 if(m_spellInfo->SpellVisual[0] == 7250)
4026 if (!m_targets.getUnitTarget())
4027 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4029 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4030 return SPELL_FAILED_BAD_TARGETS;
4032 break;
4034 case SPELL_EFFECT_TAMECREATURE:
4036 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
4037 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4039 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
4040 return SPELL_FAILED_HIGHLEVEL;
4042 // use SMSG_PET_TAME_FAILURE?
4043 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
4044 return SPELL_FAILED_BAD_TARGETS;
4046 if(m_caster->GetPetGUID())
4047 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4049 if(m_caster->GetCharmGUID())
4050 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4052 break;
4054 case SPELL_EFFECT_LEARN_SPELL:
4056 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
4057 break;
4059 Pet* pet = m_caster->GetPet();
4061 if(!pet)
4062 return SPELL_FAILED_NO_PET;
4064 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4066 if(!learn_spellproto)
4067 return SPELL_FAILED_NOT_KNOWN;
4069 if(m_spellInfo->spellLevel > pet->getLevel())
4070 return SPELL_FAILED_LOWLEVEL;
4072 break;
4074 case SPELL_EFFECT_LEARN_PET_SPELL:
4076 Pet* pet = m_caster->GetPet();
4078 if(!pet)
4079 return SPELL_FAILED_NO_PET;
4081 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4083 if(!learn_spellproto)
4084 return SPELL_FAILED_NOT_KNOWN;
4086 if(m_spellInfo->spellLevel > pet->getLevel())
4087 return SPELL_FAILED_LOWLEVEL;
4089 break;
4091 case SPELL_EFFECT_FEED_PET:
4093 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4094 return SPELL_FAILED_BAD_TARGETS;
4096 Item* foodItem = m_targets.getItemTarget();
4097 if(!foodItem)
4098 return SPELL_FAILED_BAD_TARGETS;
4100 Pet* pet = m_caster->GetPet();
4102 if(!pet)
4103 return SPELL_FAILED_NO_PET;
4105 if(!pet->HaveInDiet(foodItem->GetProto()))
4106 return SPELL_FAILED_WRONG_PET_FOOD;
4108 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4109 return SPELL_FAILED_FOOD_LOWLEVEL;
4111 if(m_caster->isInCombat() || pet->isInCombat())
4112 return SPELL_FAILED_AFFECTING_COMBAT;
4114 break;
4116 case SPELL_EFFECT_POWER_BURN:
4117 case SPELL_EFFECT_POWER_DRAIN:
4119 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4120 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4121 if(Unit* target = m_targets.getUnitTarget())
4122 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
4123 return SPELL_FAILED_BAD_TARGETS;
4124 break;
4126 case SPELL_EFFECT_CHARGE:
4128 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4129 return SPELL_FAILED_ROOTED;
4131 break;
4133 case SPELL_EFFECT_SKINNING:
4135 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4136 return SPELL_FAILED_BAD_TARGETS;
4138 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4139 return SPELL_FAILED_TARGET_UNSKINNABLE;
4141 Creature* creature = (Creature*)m_targets.getUnitTarget();
4142 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4144 return SPELL_FAILED_TARGET_NOT_LOOTED;
4147 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4149 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4150 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4151 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
4152 if (ReqValue > skillValue)
4153 return SPELL_FAILED_LOW_CASTLEVEL;
4155 // chance for fail at orange skinning attempt
4156 if( (m_selfContainer && (*m_selfContainer) == this) &&
4157 skillValue < sWorld.GetConfigMaxSkillValue() &&
4158 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
4159 return SPELL_FAILED_TRY_AGAIN;
4161 break;
4163 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4164 case SPELL_EFFECT_OPEN_LOCK:
4166 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4167 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4168 break;
4170 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4171 // we need a go target in case of TARGET_GAMEOBJECT
4172 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4173 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4174 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4175 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4176 return SPELL_FAILED_BAD_TARGETS;
4178 // In BattleGround players can use only flags and banners
4179 if( ((Player*)m_caster)->InBattleGround() &&
4180 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
4181 return SPELL_FAILED_TRY_AGAIN;
4183 // get the lock entry
4184 LockEntry const *lockInfo = NULL;
4185 if (GameObject* go=m_targets.getGOTarget())
4186 lockInfo = sLockStore.LookupEntry(go->GetLockId());
4187 else if(Item* itm=m_targets.getItemTarget())
4188 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
4190 // check lock compatibility
4191 if (lockInfo)
4193 // check for lock - key pair (checked by client also, just prevent cheating
4194 bool ok_key = false;
4195 for(int it = 0; it < 8; ++it)
4197 switch(lockInfo->Type[it])
4199 case LOCK_KEY_NONE:
4200 break;
4201 case LOCK_KEY_ITEM:
4203 if(lockInfo->Index[it])
4205 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4206 ok_key =true;
4207 break;
4210 case LOCK_KEY_SKILL:
4212 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->Index[it])
4213 break;
4215 switch(lockInfo->Index[it])
4217 case LOCKTYPE_HERBALISM:
4218 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
4219 ok_key =true;
4220 break;
4221 case LOCKTYPE_MINING:
4222 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
4223 ok_key =true;
4224 break;
4225 default:
4226 ok_key =true;
4227 break;
4231 if(ok_key)
4232 break;
4235 if(!ok_key)
4236 return SPELL_FAILED_BAD_TARGETS;
4239 // chance for fail at orange mining/herb/LockPicking gathering attempt
4240 if (!m_selfContainer || ((*m_selfContainer) != this))
4241 break;
4243 // get the skill value of the player
4244 int32 SkillValue = 0;
4245 bool canFailAtMax = true;
4246 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
4248 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
4249 canFailAtMax = false;
4251 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
4253 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
4254 canFailAtMax = false;
4256 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4257 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
4259 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
4260 if(m_CastItem)
4261 SkillValue = 0;
4263 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
4264 SkillValue += m_currentBasePoints[i]+1;
4266 // get the required lock value
4267 int32 ReqValue=0;
4268 if (lockInfo)
4270 // check for lock - key pair
4271 bool ok = false;
4272 for(int it = 0; it < 8; ++it)
4274 if(lockInfo->Type[it]==LOCK_KEY_ITEM && lockInfo->Index[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4276 // if so, we're good to go
4277 ok = true;
4278 break;
4281 if(ok)
4282 break;
4284 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4285 ReqValue = lockInfo->Skill[1];
4286 else
4287 ReqValue = lockInfo->Skill[0];
4290 // skill doesn't meet the required value
4291 if (ReqValue > SkillValue)
4292 return SPELL_FAILED_LOW_CASTLEVEL;
4294 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4295 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
4296 return SPELL_FAILED_TRY_AGAIN;
4298 break;
4300 case SPELL_EFFECT_SUMMON_DEAD_PET:
4302 Creature *pet = m_caster->GetPet();
4303 if(!pet)
4304 return SPELL_FAILED_NO_PET;
4306 if(pet->isAlive())
4307 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4309 break;
4311 // This is generic summon effect
4312 case SPELL_EFFECT_SUMMON:
4314 switch(m_spellInfo->EffectMiscValueB[i])
4316 case SUMMON_TYPE_POSESSED:
4317 case SUMMON_TYPE_POSESSED2:
4318 case SUMMON_TYPE_DEMON:
4319 case SUMMON_TYPE_SUMMON:
4321 if(m_caster->GetPetGUID())
4322 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4324 if(m_caster->GetCharmGUID())
4325 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4326 break;
4329 break;
4331 // Not used for summon?
4332 case SPELL_EFFECT_SUMMON_PHANTASM:
4334 if(m_caster->GetPetGUID())
4335 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4337 if(m_caster->GetCharmGUID())
4338 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4340 break;
4342 case SPELL_EFFECT_SUMMON_PET:
4344 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4347 Pet* pet = ((Player*)m_caster)->GetPet();
4349 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4351 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4352 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4354 else
4355 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4358 if(m_caster->GetCharmGUID())
4359 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4361 break;
4363 case SPELL_EFFECT_SUMMON_PLAYER:
4365 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4366 return SPELL_FAILED_BAD_TARGETS;
4367 if(!((Player*)m_caster)->GetSelection())
4368 return SPELL_FAILED_BAD_TARGETS;
4370 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4371 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4372 return SPELL_FAILED_BAD_TARGETS;
4374 // check if our map is dungeon
4375 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4377 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4378 if(!instance)
4379 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4380 if ( instance->levelMin > target->getLevel() )
4381 return SPELL_FAILED_LOWLEVEL;
4382 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4383 return SPELL_FAILED_HIGHLEVEL;
4385 break;
4387 case SPELL_EFFECT_LEAP:
4388 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4390 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4391 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4392 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4393 // teleport a bit above terrain level to avoid falling below it
4394 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4395 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4396 return SPELL_FAILED_TRY_AGAIN;
4398 float caster_pos_z = m_caster->GetPositionZ();
4399 // Control the caster to not climb or drop when +-fz > 8
4400 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4401 return SPELL_FAILED_TRY_AGAIN;
4403 // not allow use this effect at battleground until battleground start
4404 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4405 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4406 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4407 return SPELL_FAILED_TRY_AGAIN;
4408 break;
4410 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4412 if (m_targets.getUnitTarget()==m_caster)
4413 return SPELL_FAILED_BAD_TARGETS;
4414 break;
4416 default:break;
4420 for (int i = 0; i < 3; i++)
4422 switch(m_spellInfo->EffectApplyAuraName[i])
4424 case SPELL_AURA_MOD_POSSESS:
4425 case SPELL_AURA_MOD_CHARM:
4427 if(m_caster->GetPetGUID())
4428 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4430 if(m_caster->GetCharmGUID())
4431 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4433 if(m_caster->GetCharmerGUID())
4434 return SPELL_FAILED_CHARMED;
4436 if(!m_targets.getUnitTarget())
4437 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4439 if(m_targets.getUnitTarget()->GetCharmerGUID())
4440 return SPELL_FAILED_CHARMED;
4442 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4443 return SPELL_FAILED_HIGHLEVEL;
4445 break;
4447 case SPELL_AURA_MOUNTED:
4449 if (m_caster->IsInWater())
4450 return SPELL_FAILED_ONLY_ABOVEWATER;
4452 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4453 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4455 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4456 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4457 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4459 ShapeshiftForm form = m_caster->m_form;
4460 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4461 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4462 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4463 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4464 return SPELL_FAILED_NOT_SHAPESHIFT;
4466 break;
4468 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4470 if(!m_targets.getUnitTarget())
4471 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4473 // can be casted at non-friendly unit or own pet/charm
4474 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4475 return SPELL_FAILED_TARGET_FRIENDLY;
4477 break;
4479 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4480 case SPELL_AURA_FLY:
4482 // not allow cast fly spells at old maps by players (all spells is self target)
4483 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4485 if( !((Player*)m_caster)->IsAllowUseFlyMountsHere() )
4486 return SPELL_FAILED_NOT_HERE;
4489 break;
4491 case SPELL_AURA_PERIODIC_MANA_LEECH:
4493 if (!m_targets.getUnitTarget())
4494 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4496 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4497 break;
4499 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4500 return SPELL_FAILED_BAD_TARGETS;
4502 break;
4504 default:
4505 break;
4509 // all ok
4510 return 0;
4513 int16 Spell::PetCanCast(Unit* target)
4515 if(!m_caster->isAlive())
4516 return SPELL_FAILED_CASTER_DEAD;
4518 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4519 return SPELL_FAILED_SPELL_IN_PROGRESS;
4520 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4521 return SPELL_FAILED_AFFECTING_COMBAT;
4523 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4525 //dead owner (pets still alive when owners ressed?)
4526 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4527 return SPELL_FAILED_CASTER_DEAD;
4529 if(!target && m_targets.getUnitTarget())
4530 target = m_targets.getUnitTarget();
4532 bool need = false;
4533 for(uint32 i = 0;i<3;i++)
4535 if(m_spellInfo->EffectImplicitTargetA[i] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_FRIEND || m_spellInfo->EffectImplicitTargetA[i] == TARGET_DUELVSPLAYER || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_PARTY || m_spellInfo->EffectImplicitTargetA[i] == TARGET_CURRENT_ENEMY_COORDINATES)
4537 need = true;
4538 if(!target)
4539 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4540 break;
4543 if(need)
4544 m_targets.setUnitTarget(target);
4546 Unit* _target = m_targets.getUnitTarget();
4548 if(_target) //for target dead/target not valid
4550 if(!_target->isAlive())
4551 return SPELL_FAILED_BAD_TARGETS;
4553 if(IsPositiveSpell(m_spellInfo->Id))
4555 if(m_caster->IsHostileTo(_target))
4556 return SPELL_FAILED_BAD_TARGETS;
4558 else
4560 bool duelvsplayertar = false;
4561 for(int j=0;j<3;j++)
4563 //TARGET_DUELVSPLAYER is positive AND negative
4564 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4566 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4568 return SPELL_FAILED_BAD_TARGETS;
4572 //cooldown
4573 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4574 return SPELL_FAILED_NOT_READY;
4577 uint16 result = CanCast(true);
4578 if(result != 0)
4579 return result;
4580 else
4581 return -1; //this allows to check spell fail 0, in combat
4584 uint8 Spell::CheckCasterAuras() const
4586 // Flag drop spells totally immuned to caster auras
4587 // FIXME: find more nice check for all totally immuned spells
4588 // AttributesEx3 & 0x10000000?
4589 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4590 return 0;
4592 uint8 school_immune = 0;
4593 uint32 mechanic_immune = 0;
4594 uint32 dispel_immune = 0;
4596 //Check if the spell grants school or mechanic immunity.
4597 //We use bitmasks so the loop is done only once and not on every aura check below.
4598 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4600 for(int i = 0;i < 3; i ++)
4602 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4603 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4604 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4605 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4606 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4607 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4609 //immune movement impairment and loss of control
4610 if(m_spellInfo->Id==(uint32)42292)
4611 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4614 //Check whether the cast should be prevented by any state you might have.
4615 uint8 prevented_reason = 0;
4616 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4617 uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
4618 if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4619 prevented_reason = SPELL_FAILED_STUNNED;
4620 else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4621 prevented_reason = SPELL_FAILED_CONFUSED;
4622 else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4623 prevented_reason = SPELL_FAILED_FLEEING;
4624 else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4625 prevented_reason = SPELL_FAILED_SILENCED;
4626 else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4627 prevented_reason = SPELL_FAILED_PACIFIED;
4629 // Attr must make flag drop spell totally immune from all effects
4630 if(prevented_reason)
4632 if(school_immune || mechanic_immune || dispel_immune)
4634 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4635 Unit::AuraMap const& auras = m_caster->GetAuras();
4636 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4638 if(itr->second)
4640 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4641 continue;
4642 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4643 continue;
4644 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4645 continue;
4647 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4648 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4649 switch(itr->second->GetModifier()->m_auraname)
4651 case SPELL_AURA_MOD_STUN:
4652 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4653 return SPELL_FAILED_STUNNED;
4654 break;
4655 case SPELL_AURA_MOD_CONFUSE:
4656 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4657 return SPELL_FAILED_CONFUSED;
4658 break;
4659 case SPELL_AURA_MOD_FEAR:
4660 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4661 return SPELL_FAILED_FLEEING;
4662 break;
4663 case SPELL_AURA_MOD_SILENCE:
4664 case SPELL_AURA_MOD_PACIFY:
4665 case SPELL_AURA_MOD_PACIFY_SILENCE:
4666 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4667 return SPELL_FAILED_PACIFIED;
4668 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4669 return SPELL_FAILED_SILENCED;
4670 break;
4675 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4676 else
4677 return prevented_reason;
4679 return 0; // all ok
4682 bool Spell::CanAutoCast(Unit* target)
4684 uint64 targetguid = target->GetGUID();
4686 for(uint32 j = 0;j<3;j++)
4688 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4690 if( m_spellInfo->StackAmount <= 1)
4692 if( target->HasAura(m_spellInfo->Id, j) )
4693 return false;
4695 else
4697 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4698 return false;
4701 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4703 if( target->HasAura(m_spellInfo->Id, j) )
4704 return false;
4708 int16 result = PetCanCast(target);
4710 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4712 FillTargetMap();
4713 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4714 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4715 if( ihit->targetGUID == targetguid )
4716 return true;
4718 return false; //target invalid
4721 uint8 Spell::CheckRange(bool strict)
4723 float range_mod;
4725 // self cast doesn't need range checking -- also for Starshards fix
4726 if (m_spellInfo->rangeIndex == 1) return 0;
4728 if (strict) //add radius of caster
4729 range_mod = 1.25;
4730 else //add radius of caster and ~5 yds "give"
4731 range_mod = 6.25;
4733 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4734 float max_range = GetSpellMaxRange(srange) + range_mod;
4735 float min_range = GetSpellMinRange(srange);
4737 if(Player* modOwner = m_caster->GetSpellModOwner())
4738 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4740 Unit *target = m_targets.getUnitTarget();
4742 if(target && target != m_caster)
4744 // distance from target center in checks
4745 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4746 if(dist > max_range)
4747 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4748 if(dist < min_range)
4749 return SPELL_FAILED_TOO_CLOSE;
4750 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4751 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4752 return SPELL_FAILED_UNIT_NOT_INFRONT;
4755 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4757 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4758 if(dist > max_range)
4759 return SPELL_FAILED_OUT_OF_RANGE;
4760 if(dist < min_range)
4761 return SPELL_FAILED_TOO_CLOSE;
4764 return 0; // ok
4767 int32 Spell::CalculatePowerCost()
4769 // item cast not used power
4770 if(m_CastItem)
4771 return 0;
4773 // Spell drain all exist power on cast (Only paladin lay of Hands)
4774 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4776 // If power type - health drain all
4777 if (m_spellInfo->powerType == POWER_HEALTH)
4778 return m_caster->GetHealth();
4779 // Else drain all power
4780 if (m_spellInfo->powerType < MAX_POWERS)
4781 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4782 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4783 return 0;
4786 // Base powerCost
4787 int32 powerCost = m_spellInfo->manaCost;
4788 // PCT cost from total amount
4789 if (m_spellInfo->ManaCostPercentage)
4791 switch (m_spellInfo->powerType)
4793 // health as power used
4794 case POWER_HEALTH:
4795 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4796 break;
4797 case POWER_MANA:
4798 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4799 break;
4800 case POWER_RAGE:
4801 case POWER_FOCUS:
4802 case POWER_ENERGY:
4803 case POWER_HAPPINESS:
4804 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4805 break;
4806 case POWER_RUNE:
4807 case POWER_RUNIC_POWER:
4808 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4809 break;
4810 default:
4811 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4812 return 0;
4815 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4816 // Flat mod from caster auras by spell school
4817 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4818 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4819 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4820 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4821 // Apply cost mod by spell
4822 if(Player* modOwner = m_caster->GetSpellModOwner())
4823 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4825 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4826 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4828 // PCT mod from user auras by school
4829 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4830 if (powerCost < 0)
4831 powerCost = 0;
4832 return powerCost;
4835 uint8 Spell::CheckPower()
4837 // item cast not used power
4838 if(m_CastItem)
4839 return 0;
4841 // health as power used - need check health amount
4842 if(m_spellInfo->powerType == POWER_HEALTH)
4844 if(m_caster->GetHealth() <= m_powerCost)
4845 return SPELL_FAILED_CASTER_AURASTATE;
4846 return 0;
4848 // Check valid power type
4849 if( m_spellInfo->powerType >= MAX_POWERS )
4851 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4852 return SPELL_FAILED_UNKNOWN;
4855 uint8 failReason = CheckRuneCost(m_spellInfo->runeCostID);
4856 if(failReason)
4857 return failReason;
4859 // Check power amount
4860 Powers powerType = Powers(m_spellInfo->powerType);
4861 if(m_caster->GetPower(powerType) < m_powerCost)
4862 return SPELL_FAILED_NO_POWER;
4863 else
4864 return 0;
4867 uint8 Spell::CheckItems()
4869 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4870 return 0;
4872 uint32 itemid, itemcount;
4873 Player* p_caster = (Player*)m_caster;
4875 if(m_CastItem)
4877 itemid = m_CastItem->GetEntry();
4878 if( !p_caster->HasItemCount(itemid,1) )
4879 return SPELL_FAILED_ITEM_NOT_READY;
4880 else
4882 ItemPrototype const *proto = m_CastItem->GetProto();
4883 if(!proto)
4884 return SPELL_FAILED_ITEM_NOT_READY;
4886 for (int i = 0; i<5; i++)
4888 if (proto->Spells[i].SpellCharges)
4890 if(m_CastItem->GetSpellCharges(i)==0)
4891 return SPELL_FAILED_NO_CHARGES_REMAIN;
4895 uint32 ItemClass = proto->Class;
4896 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4898 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4899 uint8 failReason = 0;
4900 for (int i = 0; i < 3; i++)
4902 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4903 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4904 continue;
4906 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4908 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4910 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4911 continue;
4913 else
4915 failReason = 0;
4916 break;
4920 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4921 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4923 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4925 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4926 continue;
4929 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4930 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4932 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4933 continue;
4935 else
4937 failReason = 0;
4938 break;
4942 if (failReason)
4943 return failReason;
4948 if(m_targets.getItemTargetGUID())
4950 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4951 return SPELL_FAILED_BAD_TARGETS;
4953 if(!m_targets.getItemTarget())
4954 return SPELL_FAILED_ITEM_GONE;
4956 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4957 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4959 // if not item target then required item must be equipped
4960 else
4962 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4963 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4966 if(m_spellInfo->RequiresSpellFocus)
4968 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4969 Cell cell(p);
4970 cell.data.Part.reserved = ALL_DISTRICT;
4972 GameObject* ok = NULL;
4973 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4974 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(m_caster,ok,go_check);
4976 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4977 CellLock<GridReadGuard> cell_lock(cell, p);
4978 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4980 if(!ok)
4981 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4983 focusObject = ok; // game object found in range
4986 if (!p_caster->CanNoReagentCast(m_spellInfo))
4988 for(uint32 i=0;i<8;i++)
4990 if(m_spellInfo->Reagent[i] <= 0)
4991 continue;
4993 itemid = m_spellInfo->Reagent[i];
4994 itemcount = m_spellInfo->ReagentCount[i];
4996 // if CastItem is also spell reagent
4997 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4999 ItemPrototype const *proto = m_CastItem->GetProto();
5000 if(!proto)
5001 return SPELL_FAILED_ITEM_NOT_READY;
5002 for(int s=0;s<5;s++)
5004 // CastItem will be used up and does not count as reagent
5005 int32 charges = m_CastItem->GetSpellCharges(s);
5006 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
5008 ++itemcount;
5009 break;
5013 if( !p_caster->HasItemCount(itemid,itemcount) )
5014 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
5018 uint32 totems = 2;
5019 for(int i=0;i<2;++i)
5021 if(m_spellInfo->Totem[i] != 0)
5023 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
5025 totems -= 1;
5026 continue;
5028 }else
5029 totems -= 1;
5031 if(totems != 0)
5032 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
5034 //Check items for TotemCategory
5035 uint32 TotemCategory = 2;
5036 for(int i=0;i<2;++i)
5038 if(m_spellInfo->TotemCategory[i] != 0)
5040 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
5042 TotemCategory -= 1;
5043 continue;
5046 else
5047 TotemCategory -= 1;
5049 if(TotemCategory != 0)
5050 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
5052 for(int i = 0; i < 3; i++)
5054 switch (m_spellInfo->Effect[i])
5056 case SPELL_EFFECT_CREATE_ITEM:
5058 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
5060 ItemPosCountVec dest;
5061 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
5062 if (msg != EQUIP_ERR_OK )
5064 p_caster->SendEquipError( msg, NULL, NULL );
5065 return SPELL_FAILED_DONT_REPORT;
5068 break;
5070 case SPELL_EFFECT_ENCHANT_ITEM:
5071 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
5073 Item* targetItem = m_targets.getItemTarget();
5074 if(!targetItem)
5075 return SPELL_FAILED_ITEM_NOT_FOUND;
5077 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5078 return SPELL_FAILED_LOWLEVEL;
5079 // Not allow enchant in trade slot for some enchant type
5080 if( targetItem->GetOwner() != m_caster )
5082 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5083 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5084 if(!pEnchant)
5085 return SPELL_FAILED_ERROR;
5086 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5087 return SPELL_FAILED_NOT_TRADEABLE;
5089 break;
5091 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5093 Item *item = m_targets.getItemTarget();
5094 if(!item)
5095 return SPELL_FAILED_ITEM_NOT_FOUND;
5096 // Not allow enchant in trade slot for some enchant type
5097 if( item->GetOwner() != m_caster )
5099 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5100 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5101 if(!pEnchant)
5102 return SPELL_FAILED_ERROR;
5103 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5104 return SPELL_FAILED_NOT_TRADEABLE;
5106 break;
5108 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5109 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5110 break;
5111 case SPELL_EFFECT_DISENCHANT:
5113 if(!m_targets.getItemTarget())
5114 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5116 // prevent disenchanting in trade slot
5117 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5118 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5120 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5121 if(!itemProto)
5122 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5124 uint32 item_quality = itemProto->Quality;
5125 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5126 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5127 if (item_disenchantskilllevel == uint32(-1))
5128 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5129 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5130 return SPELL_FAILED_LOW_CASTLEVEL;
5131 if(item_quality > 4 || item_quality < 2)
5132 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5133 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5134 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5135 if (!itemProto->DisenchantID)
5136 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5137 break;
5139 case SPELL_EFFECT_PROSPECTING:
5141 if(!m_targets.getItemTarget())
5142 return SPELL_FAILED_CANT_BE_PROSPECTED;
5143 //ensure item is a prospectable ore
5144 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5145 return SPELL_FAILED_CANT_BE_PROSPECTED;
5146 //prevent prospecting in trade slot
5147 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5148 return SPELL_FAILED_CANT_BE_PROSPECTED;
5149 //Check for enough skill in jewelcrafting
5150 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5151 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5152 return SPELL_FAILED_LOW_CASTLEVEL;
5153 //make sure the player has the required ores in inventory
5154 if(m_targets.getItemTarget()->GetCount() < 5)
5155 return SPELL_FAILED_NEED_MORE_ITEMS;
5157 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5158 return SPELL_FAILED_CANT_BE_PROSPECTED;
5160 break;
5162 case SPELL_EFFECT_MILLING:
5164 if(!m_targets.getItemTarget())
5165 return SPELL_FAILED_CANT_BE_MILLED;
5166 //ensure item is a millable herb
5167 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5168 return SPELL_FAILED_CANT_BE_MILLED;
5169 //prevent milling in trade slot
5170 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5171 return SPELL_FAILED_CANT_BE_MILLED;
5172 //Check for enough skill in inscription
5173 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5174 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5175 return SPELL_FAILED_LOW_CASTLEVEL;
5176 //make sure the player has the required herbs in inventory
5177 if(m_targets.getItemTarget()->GetCount() < 5)
5178 return SPELL_FAILED_NEED_MORE_ITEMS;
5180 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5181 return SPELL_FAILED_CANT_BE_MILLED;
5183 break;
5185 case SPELL_EFFECT_WEAPON_DAMAGE:
5186 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5188 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5189 if( m_attackType != RANGED_ATTACK )
5190 break;
5191 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5192 if(!pItem || pItem->IsBroken())
5193 return SPELL_FAILED_EQUIPPED_ITEM;
5195 switch(pItem->GetProto()->SubClass)
5197 case ITEM_SUBCLASS_WEAPON_THROWN:
5199 uint32 ammo = pItem->GetEntry();
5200 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5201 return SPELL_FAILED_NO_AMMO;
5202 }; break;
5203 case ITEM_SUBCLASS_WEAPON_GUN:
5204 case ITEM_SUBCLASS_WEAPON_BOW:
5205 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5207 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5208 if(!ammo)
5210 // Requires No Ammo
5211 if(m_caster->GetDummyAura(46699))
5212 break; // skip other checks
5214 return SPELL_FAILED_NO_AMMO;
5217 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5218 if(!ammoProto)
5219 return SPELL_FAILED_NO_AMMO;
5221 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5222 return SPELL_FAILED_NO_AMMO;
5224 // check ammo ws. weapon compatibility
5225 switch(pItem->GetProto()->SubClass)
5227 case ITEM_SUBCLASS_WEAPON_BOW:
5228 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5229 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5230 return SPELL_FAILED_NO_AMMO;
5231 break;
5232 case ITEM_SUBCLASS_WEAPON_GUN:
5233 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5234 return SPELL_FAILED_NO_AMMO;
5235 break;
5236 default:
5237 return SPELL_FAILED_NO_AMMO;
5240 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5241 return SPELL_FAILED_NO_AMMO;
5242 }; break;
5243 case ITEM_SUBCLASS_WEAPON_WAND:
5244 default:
5245 break;
5247 break;
5249 default:break;
5253 return uint8(0);
5256 void Spell::Delayed()
5258 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5259 return;
5261 if (m_spellState == SPELL_STATE_DELAYED)
5262 return; // spell is active and can't be time-backed
5264 if(isDelayableNoMore()) // Spells may only be delayed twice
5265 return;
5267 // spells not loosing casting time ( slam, dynamites, bombs.. )
5268 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5269 return;
5271 //check pushback reduce
5272 int32 delaytime = 500; // spellcasting delay is normally 500ms
5273 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5274 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5275 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5276 if(delayReduce >= 100)
5277 return;
5279 delaytime = delaytime * (100 - delayReduce) / 100;
5281 if(int32(m_timer) + delaytime > m_casttime)
5283 delaytime = m_casttime - m_timer;
5284 m_timer = m_casttime;
5286 else
5287 m_timer += delaytime;
5289 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5291 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5292 data.append(m_caster->GetPackGUID());
5293 data << uint32(delaytime);
5295 m_caster->SendMessageToSet(&data,true);
5298 void Spell::DelayedChannel()
5300 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5301 return;
5303 if(isDelayableNoMore()) // Spells may only be delayed twice
5304 return;
5306 //check pushback reduce
5307 int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
5308 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5309 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,delayReduce, this);
5310 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5311 if(delayReduce >= 100)
5312 return;
5314 delaytime = delaytime * (100 - delayReduce) / 100;
5316 if(int32(m_timer) < delaytime)
5318 delaytime = m_timer;
5319 m_timer = 0;
5321 else
5322 m_timer -= delaytime;
5324 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5326 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5328 if ((*ihit).missCondition == SPELL_MISS_NONE)
5330 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5331 if (unit)
5333 for (int j=0;j<3;j++)
5334 if( ihit->effectMask & (1<<j) )
5335 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5341 for(int j = 0; j < 3; j++)
5343 // partially interrupt persistent area auras
5344 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5345 if(dynObj)
5346 dynObj->Delay(delaytime);
5349 SendChannelUpdate(m_timer);
5352 void Spell::UpdatePointers()
5354 if(m_originalCasterGUID==m_caster->GetGUID())
5355 m_originalCaster = m_caster;
5356 else
5358 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5359 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5362 m_targets.Update(m_caster);
5365 bool Spell::IsAffectedByAura(Aura *aura)
5367 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5370 bool Spell::CheckTargetCreatureType(Unit* target) const
5372 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5374 // Curse of Doom : not find another way to fix spell target check :/
5375 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5377 // not allow cast at player
5378 if(target->GetTypeId()==TYPEID_PLAYER)
5379 return false;
5381 spellCreatureTargetMask = 0x7FF;
5384 // Dismiss Pet and Taming Lesson skipped
5385 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5386 spellCreatureTargetMask = 0;
5388 if (spellCreatureTargetMask)
5390 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5392 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5394 return true;
5397 CurrentSpellTypes Spell::GetCurrentContainer()
5399 if (IsNextMeleeSwingSpell())
5400 return(CURRENT_MELEE_SPELL);
5401 else if (IsAutoRepeat())
5402 return(CURRENT_AUTOREPEAT_SPELL);
5403 else if (IsChanneledSpell(m_spellInfo))
5404 return(CURRENT_CHANNELED_SPELL);
5405 else
5406 return(CURRENT_GENERIC_SPELL);
5409 bool Spell::CheckTarget( Unit* target, uint32 eff )
5411 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5412 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5414 if (!CheckTargetCreatureType(target))
5415 return false;
5418 // Check Aura spell req (need for AoE spells)
5419 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5420 return false;
5421 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5422 return false;
5424 // Check targets for not_selectable unit flag and remove
5425 // A player can cast spells on his pet (or other controlled unit) though in any state
5426 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5428 // any unattackable target skipped
5429 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5430 return false;
5432 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5433 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5434 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5435 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5436 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5437 return false;
5440 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5441 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5443 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5444 return false;
5446 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5447 return false;
5450 //Check targets for LOS visibility (except spells without range limitations )
5451 switch(m_spellInfo->Effect[eff])
5453 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5454 break;
5455 case SPELL_EFFECT_DUMMY:
5456 if(m_spellInfo->Id!=20577) // Cannibalize
5457 break;
5458 //fall through
5459 case SPELL_EFFECT_RESURRECT_NEW:
5460 // player far away, maybe his corpse near?
5461 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5463 if(!m_targets.getCorpseTargetGUID())
5464 return false;
5466 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5467 if(!corpse)
5468 return false;
5470 if(target->GetGUID()!=corpse->GetOwnerGUID())
5471 return false;
5473 if(!corpse->IsWithinLOSInMap(m_caster))
5474 return false;
5477 // all ok by some way or another, skip normal check
5478 break;
5479 default: // normal case
5480 // Get GO cast coordinates if original caster -> GO
5481 WorldObject *caster = NULL;
5482 if (m_originalCasterGUID)
5483 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
5484 if (!caster)
5485 caster = m_caster;
5486 if(target!=m_caster && !target->IsWithinLOSInMap(caster))
5487 return false;
5488 break;
5491 return true;
5494 Unit* Spell::SelectMagnetTarget()
5496 Unit* target = m_targets.getUnitTarget();
5498 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
5500 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
5501 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
5503 if(Unit* magnet = (*itr)->GetCaster())
5505 if(magnet->IsWithinLOSInMap(m_caster))
5507 target = magnet;
5508 m_targets.setUnitTarget(target);
5509 break;
5515 return target;
5518 bool Spell::IsNeedSendToClient() const
5520 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5521 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5524 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5526 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5527 if(itr->effectMask & (1<<effect))
5528 return true;
5530 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5531 if(itr->effectMask & (1<<effect))
5532 return true;
5534 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5535 if(itr->effectMask & (1<<effect))
5536 return true;
5538 return false;
5541 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5543 m_Spell = spell;
5546 SpellEvent::~SpellEvent()
5548 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5549 m_Spell->cancel();
5551 if (m_Spell->IsDeletable())
5553 delete m_Spell;
5555 else
5557 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5558 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5562 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5564 // update spell if it is not finished
5565 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5566 m_Spell->update(p_time);
5568 // check spell state to process
5569 switch (m_Spell->getState())
5571 case SPELL_STATE_FINISHED:
5573 // spell was finished, check deletable state
5574 if (m_Spell->IsDeletable())
5576 // check, if we do have unfinished triggered spells
5578 return(true); // spell is deletable, finish event
5580 // event will be re-added automatically at the end of routine)
5581 } break;
5583 case SPELL_STATE_CASTING:
5585 // this spell is in channeled state, process it on the next update
5586 // event will be re-added automatically at the end of routine)
5587 } break;
5589 case SPELL_STATE_DELAYED:
5591 // first, check, if we have just started
5592 if (m_Spell->GetDelayStart() != 0)
5594 // no, we aren't, do the typical update
5595 // check, if we have channeled spell on our hands
5596 if (IsChanneledSpell(m_Spell->m_spellInfo))
5598 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5599 // check, if we have casting anything else except this channeled spell and autorepeat
5600 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5602 // another non-melee non-delayed spell is casted now, abort
5603 m_Spell->cancel();
5605 else
5607 // do the action (pass spell to channeling state)
5608 m_Spell->handle_immediate();
5610 // event will be re-added automatically at the end of routine)
5612 else
5614 // run the spell handler and think about what we can do next
5615 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5616 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5617 if (n_offset)
5619 // re-add us to the queue
5620 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5621 return(false); // event not complete
5623 // event complete
5624 // finish update event will be re-added automatically at the end of routine)
5627 else
5629 // delaying had just started, record the moment
5630 m_Spell->SetDelayStart(e_time);
5631 // re-plan the event for the delay moment
5632 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5633 return(false); // event not complete
5635 } break;
5637 default:
5639 // all other states
5640 // event will be re-added automatically at the end of routine)
5641 } break;
5644 // spell processing not complete, plan event on the next update interval
5645 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5646 return(false); // event not complete
5649 void SpellEvent::Abort(uint64 /*e_time*/)
5651 // oops, the spell we try to do is aborted
5652 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5653 m_Spell->cancel();
5656 bool SpellEvent::IsDeletable() const
5658 return m_Spell->IsDeletable();