Merge branch 'master' into 308
[getmangos.git] / src / game / Spell.cpp
blob1a672c2abc50abad7c9907980496375874c34838
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::setGOTarget(GameObject *target)
106 m_GOTarget = target;
107 m_GOTargetGUID = target->GetGUID();
108 // m_targetMask |= TARGET_FLAG_OBJECT;
111 void SpellCastTargets::setItemTarget(Item* item)
113 if(!item)
114 return;
116 m_itemTarget = item;
117 m_itemTargetGUID = item->GetGUID();
118 m_itemTargetEntry = item->GetEntry();
119 m_targetMask |= TARGET_FLAG_ITEM;
122 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
124 m_CorpseTargetGUID = corpse->GetGUID();
127 void SpellCastTargets::Update(Unit* caster)
129 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
130 m_unitTarget = m_unitTargetGUID ?
131 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
132 NULL;
134 m_itemTarget = NULL;
135 if(caster->GetTypeId()==TYPEID_PLAYER)
137 if(m_targetMask & TARGET_FLAG_ITEM)
138 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
139 else
141 Player* pTrader = ((Player*)caster)->GetTrader();
142 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
143 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
145 if(m_itemTarget)
146 m_itemTargetEntry = m_itemTarget->GetEntry();
150 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
152 if(data->rpos()+4 > data->size())
153 return false;
155 *data >> m_targetMask;
157 if(m_targetMask == TARGET_FLAG_SELF)
159 m_destX = caster->GetPositionX();
160 m_destY = caster->GetPositionY();
161 m_destZ = caster->GetPositionZ();
162 m_unitTarget = caster;
163 m_unitTargetGUID = caster->GetGUID();
164 return true;
167 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
168 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
169 if(!data->readPackGUID(m_unitTargetGUID))
170 return false;
172 if( m_targetMask & ( TARGET_FLAG_OBJECT ))
173 if(!data->readPackGUID(m_GOTargetGUID))
174 return false;
176 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
177 if(!data->readPackGUID(m_itemTargetGUID))
178 return false;
180 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
181 if(!data->readPackGUID(m_CorpseTargetGUID))
182 return false;
184 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
186 if(data->rpos()+4+4+4 > data->size())
187 return false;
189 *data >> m_srcX >> m_srcY >> m_srcZ;
190 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
191 return false;
194 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
196 if(data->rpos()+1+4+4+4 > data->size())
197 return false;
199 if(!data->readPackGUID(m_unitTargetGUID))
200 return false;
202 *data >> m_destX >> m_destY >> m_destZ;
203 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
204 return false;
207 if( m_targetMask & TARGET_FLAG_STRING )
209 if(data->rpos()+1 > data->size())
210 return false;
212 *data >> m_strTarget;
215 // find real units/GOs
216 Update(caster);
217 return true;
220 void SpellCastTargets::write ( WorldPacket * data )
222 *data << uint32(m_targetMask);
224 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
226 if(m_targetMask & TARGET_FLAG_UNIT)
228 if(m_unitTarget)
229 data->append(m_unitTarget->GetPackGUID());
230 else
231 *data << uint8(0);
233 else if( m_targetMask & TARGET_FLAG_OBJECT )
235 if(m_GOTarget)
236 data->append(m_GOTarget->GetPackGUID());
237 else
238 *data << uint8(0);
240 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
241 data->appendPackGUID(m_CorpseTargetGUID);
242 else
243 *data << uint8(0);
246 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
248 if(m_itemTarget)
249 data->append(m_itemTarget->GetPackGUID());
250 else
251 *data << uint8(0);
254 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
255 *data << m_srcX << m_srcY << m_srcZ;
257 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
259 if(m_unitTarget)
260 data->append(m_unitTarget->GetPackGUID());
261 else
262 *data << uint8(0);
264 *data << m_destX << m_destY << m_destZ;
267 if( m_targetMask & TARGET_FLAG_STRING )
268 *data << m_strTarget;
271 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
273 ASSERT( Caster != NULL && info != NULL );
274 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
276 m_spellInfo = info;
277 m_caster = Caster;
278 m_selfContainer = NULL;
279 m_triggeringContainer = triggeringContainer;
280 m_referencedFromCurrentSpell = false;
281 m_executedCurrently = false;
282 m_delayStart = 0;
283 m_delayAtDamageCount = 0;
285 m_applyMultiplierMask = 0;
287 // Get data for type of attack
288 switch (m_spellInfo->DmgClass)
290 case SPELL_DAMAGE_CLASS_MELEE:
291 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
292 m_attackType = OFF_ATTACK;
293 else
294 m_attackType = BASE_ATTACK;
295 break;
296 case SPELL_DAMAGE_CLASS_RANGED:
297 m_attackType = RANGED_ATTACK;
298 break;
299 default:
300 // Wands
301 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
302 m_attackType = RANGED_ATTACK;
303 else
304 m_attackType = BASE_ATTACK;
305 break;
308 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
310 if(m_attackType == RANGED_ATTACK)
312 // wand case
313 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
315 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
316 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
319 // Set health leech amount to zero
320 m_healthLeech = 0;
322 if(originalCasterGUID)
323 m_originalCasterGUID = originalCasterGUID;
324 else
325 m_originalCasterGUID = m_caster->GetGUID();
327 if(m_originalCasterGUID==m_caster->GetGUID())
328 m_originalCaster = m_caster;
329 else
331 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
332 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
335 for(int i=0; i <3; ++i)
336 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
338 m_spellState = SPELL_STATE_NULL;
340 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
341 m_TriggerSpells.clear();
342 m_IsTriggeredSpell = triggered;
343 //m_AreaAura = false;
344 m_CastItem = NULL;
346 unitTarget = NULL;
347 itemTarget = NULL;
348 gameObjTarget = NULL;
349 focusObject = NULL;
350 m_cast_count = 0;
351 m_glyphIndex = 0;
352 m_triggeredByAuraSpell = NULL;
354 //Auto Shot & Shoot (wand)
355 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
357 m_runesState = 0;
358 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
359 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
360 m_timer = 0; // will set to castime in prepare
362 m_needAliveTargetMask = 0;
364 // determine reflection
365 m_canReflect = false;
367 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
369 for(int j=0;j<3;j++)
371 if (m_spellInfo->Effect[j]==0)
372 continue;
374 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
375 m_canReflect = true;
376 else
377 m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
379 if(m_canReflect)
380 continue;
381 else
382 break;
386 CleanupTargetList();
389 Spell::~Spell()
393 void Spell::FillTargetMap()
395 // TODO: ADD the correct target FILLS!!!!!!
397 for(uint32 i=0;i<3;i++)
399 // not call for empty effect.
400 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
401 if(m_spellInfo->Effect[i]==0)
402 continue;
404 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
405 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
406 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
407 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
408 continue;
410 // TODO: find a way so this is not needed?
411 // for area auras always add caster as target (needed for totems for example)
412 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
413 AddUnitTarget(m_caster, i);
415 std::list<Unit*> tmpUnitMap;
417 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
418 // but need it support in some know cases
419 switch(m_spellInfo->EffectImplicitTargetA[i])
421 case TARGET_ALL_AROUND_CASTER:
422 if( m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_PARTY ||
423 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER ||
424 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_RAID_AROUND_CASTER )
426 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
428 // Note: this hack with search required until GO casting not implemented
429 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
430 // currently each enemy selected explicitly and self cast damage
431 else if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
433 if(m_targets.getUnitTarget())
434 tmpUnitMap.push_back(m_targets.getUnitTarget());
436 else
438 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
439 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
441 break;
442 case TARGET_TABLE_X_Y_Z_COORDINATES:
443 // Only if target A, for target B (used in teleports) dest select in effect
444 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
445 break;
446 default:
447 switch(m_spellInfo->EffectImplicitTargetB[i])
449 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
450 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
451 break;
452 default:
453 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
454 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
455 break;
457 break;
460 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
461 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
463 // add here custom effects that need default target.
464 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
465 switch(m_spellInfo->Effect[i])
467 case SPELL_EFFECT_DUMMY:
469 switch(m_spellInfo->Id)
471 case 20577: // Cannibalize
473 // non-standard target selection
474 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
475 float max_range = GetSpellMaxRange(srange);
477 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
478 Cell cell(p);
479 cell.data.Part.reserved = ALL_DISTRICT;
480 cell.SetNoCreate();
482 WorldObject* result = NULL;
484 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
485 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(result, u_check);
487 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
488 CellLock<GridReadGuard> cell_lock(cell, p);
489 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
491 if(!result)
493 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
494 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
497 if(result)
499 switch(result->GetTypeId())
501 case TYPEID_UNIT:
502 case TYPEID_PLAYER:
503 tmpUnitMap.push_back((Unit*)result);
504 break;
505 case TYPEID_CORPSE:
506 m_targets.setCorpseTarget((Corpse*)result);
507 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
508 tmpUnitMap.push_back(owner);
509 break;
512 else
514 // clear cooldown at fail
515 if(m_caster->GetTypeId()==TYPEID_PLAYER)
517 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
519 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
520 data << uint32(m_spellInfo->Id);
521 data << uint64(m_caster->GetGUID());
522 ((Player*)m_caster)->GetSession()->SendPacket(&data);
525 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
526 finish(false);
528 break;
530 default:
531 if(m_targets.getUnitTarget())
532 tmpUnitMap.push_back(m_targets.getUnitTarget());
533 break;
535 break;
537 case SPELL_EFFECT_RESURRECT:
538 case SPELL_EFFECT_PARRY:
539 case SPELL_EFFECT_BLOCK:
540 case SPELL_EFFECT_CREATE_ITEM:
541 case SPELL_EFFECT_TRIGGER_SPELL:
542 case SPELL_EFFECT_TRIGGER_MISSILE:
543 case SPELL_EFFECT_LEARN_SPELL:
544 case SPELL_EFFECT_SKILL_STEP:
545 case SPELL_EFFECT_PROFICIENCY:
546 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
547 case SPELL_EFFECT_SELF_RESURRECT:
548 case SPELL_EFFECT_REPUTATION:
549 if(m_targets.getUnitTarget())
550 tmpUnitMap.push_back(m_targets.getUnitTarget());
551 break;
552 case SPELL_EFFECT_SUMMON_PLAYER:
553 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
555 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
556 if(target)
557 tmpUnitMap.push_back(target);
559 break;
560 case SPELL_EFFECT_RESURRECT_NEW:
561 if(m_targets.getUnitTarget())
562 tmpUnitMap.push_back(m_targets.getUnitTarget());
563 if(m_targets.getCorpseTargetGUID())
565 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
566 if(corpse)
568 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
569 if(owner)
570 tmpUnitMap.push_back(owner);
573 break;
574 case SPELL_EFFECT_SUMMON:
575 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
577 if(m_targets.getUnitTarget())
578 tmpUnitMap.push_back(m_targets.getUnitTarget());
580 else
581 tmpUnitMap.push_back(m_caster);
582 break;
583 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
584 case SPELL_EFFECT_TRANS_DOOR:
585 case SPELL_EFFECT_ADD_FARSIGHT:
586 case SPELL_EFFECT_APPLY_GLYPH:
587 case SPELL_EFFECT_STUCK:
588 case SPELL_EFFECT_FEED_PET:
589 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
590 case SPELL_EFFECT_SKILL:
591 tmpUnitMap.push_back(m_caster);
592 break;
593 case SPELL_EFFECT_LEARN_PET_SPELL:
594 if(Pet* pet = m_caster->GetPet())
595 tmpUnitMap.push_back(pet);
596 break;
597 case SPELL_EFFECT_ENCHANT_ITEM:
598 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
599 case SPELL_EFFECT_DISENCHANT:
600 case SPELL_EFFECT_PROSPECTING:
601 case SPELL_EFFECT_MILLING:
602 if(m_targets.getItemTarget())
603 AddItemTarget(m_targets.getItemTarget(), i);
604 break;
605 case SPELL_EFFECT_APPLY_AURA:
606 switch(m_spellInfo->EffectApplyAuraName[i])
608 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)
609 case SPELL_AURA_ADD_PCT_MODIFIER:
610 tmpUnitMap.push_back(m_caster);
611 break;
612 default: // apply to target in other case
613 if(m_targets.getUnitTarget())
614 tmpUnitMap.push_back(m_targets.getUnitTarget());
615 break;
617 break;
618 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
619 // AreaAura
620 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
621 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
622 break;
623 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
624 if(m_targets.getUnitTarget())
626 tmpUnitMap.push_back(m_targets.getUnitTarget());
628 else if (m_targets.getCorpseTargetGUID())
630 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
631 if(corpse)
633 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
634 if(owner)
635 tmpUnitMap.push_back(owner);
638 break;
639 default:
640 break;
643 if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
644 m_needAliveTargetMask |= (1<<i);
646 if(m_caster->GetTypeId() == TYPEID_PLAYER)
648 Player *me = (Player*)m_caster;
649 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
651 Unit *owner = (*itr)->GetOwner();
652 Unit *u = owner ? owner : (*itr);
653 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
655 me->UpdatePvP(true);
656 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
657 break;
662 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
664 if (!CheckTarget (*itr, i))
666 itr = tmpUnitMap.erase(itr);
667 continue;
669 else
670 ++itr;
673 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
674 AddUnitTarget((*iunit), i);
678 void Spell::prepareDataForTriggerSystem()
680 //==========================================================================================
681 // Now fill data for trigger system, need know:
682 // Ñan spell trigger another or not ( m_canTrigger )
683 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
684 //==========================================================================================
685 // Fill flag can spell trigger or not
686 // TODO: possible exist spell attribute for this
687 m_canTrigger = false;
689 if (m_CastItem)
690 m_canTrigger = false; // Do not trigger from item cast spell
691 else if (!m_IsTriggeredSpell)
692 m_canTrigger = true; // Normal cast - can trigger
693 else if (!m_triggeredByAuraSpell)
694 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
696 if (!m_canTrigger) // Exceptions (some periodic triggers)
698 switch (m_spellInfo->SpellFamilyName)
700 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
701 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
702 break;
703 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
704 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
705 break;
706 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
707 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
708 break;
709 case SPELLFAMILY_ROGUE: // For poisons need do it
710 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
711 break;
712 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect
713 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000014LL) m_canTrigger = true;
714 break;
715 case SPELLFAMILY_PALADIN: // For Holy Shock triggers need do it
716 if (m_spellInfo->SpellFamilyFlags & 0x0001000000200000LL) m_canTrigger = true;
717 break;
721 // Get data for type of attack and fill base info for trigger
722 switch (m_spellInfo->DmgClass)
724 case SPELL_DAMAGE_CLASS_MELEE:
725 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
726 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
727 break;
728 case SPELL_DAMAGE_CLASS_RANGED:
729 // Auto attack
730 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
732 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
733 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
735 else // Ranged spell attack
737 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
738 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
740 break;
741 default:
742 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
744 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
745 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
747 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
749 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
750 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
752 else // Negative spell
754 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
755 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
757 break;
759 // Hunter traps spells (for Entrapment trigger)
760 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
761 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x0000200000000014LL)
762 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
765 void Spell::CleanupTargetList()
767 m_UniqueTargetInfo.clear();
768 m_UniqueGOTargetInfo.clear();
769 m_UniqueItemInfo.clear();
770 m_delayMoment = 0;
773 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
775 if( m_spellInfo->Effect[effIndex]==0 )
776 return;
778 // Check for effect immune skip if immuned
779 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
781 uint64 targetGUID = pVictim->GetGUID();
783 // Lookup target in already in list
784 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
786 if (targetGUID == ihit->targetGUID) // Found in list
788 if (!immuned)
789 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
790 return;
794 // This is new target calculate data for him
796 // Get spell hit result on target
797 TargetInfo target;
798 target.targetGUID = targetGUID; // Store target GUID
799 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
800 target.processed = false; // Effects not apply on target
802 // Calculate hit result
803 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
805 // Spell have speed - need calculate incoming time
806 if (m_spellInfo->speed > 0.0f)
808 // calculate spell incoming interval
809 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
810 if (dist < 5.0f) dist = 5.0f;
811 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
813 // Calculate minimum incoming time
814 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
815 m_delayMoment = target.timeDelay;
817 else
818 target.timeDelay = 0LL;
820 // If target reflect spell back to caster
821 if (target.missCondition==SPELL_MISS_REFLECT)
823 // Calculate reflected spell result on caster
824 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
826 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
827 target.reflectResult = SPELL_MISS_PARRY;
829 // Increase time interval for reflected spells by 1.5
830 target.timeDelay+=target.timeDelay>>1;
832 else
833 target.reflectResult = SPELL_MISS_NONE;
835 // Add target to list
836 m_UniqueTargetInfo.push_back(target);
839 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
841 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
842 if (unit)
843 AddUnitTarget(unit, effIndex);
846 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
848 if( m_spellInfo->Effect[effIndex]==0 )
849 return;
851 uint64 targetGUID = pVictim->GetGUID();
853 // Lookup target in already in list
854 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
856 if (targetGUID == ihit->targetGUID) // Found in list
858 ihit->effectMask |= 1<<effIndex; // Add only effect mask
859 return;
863 // This is new target calculate data for him
865 GOTargetInfo target;
866 target.targetGUID = targetGUID;
867 target.effectMask = 1<<effIndex;
868 target.processed = false; // Effects not apply on target
870 // Spell have speed - need calculate incoming time
871 if (m_spellInfo->speed > 0.0f)
873 // calculate spell incoming interval
874 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
875 if (dist < 5.0f) dist = 5.0f;
876 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
877 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
878 m_delayMoment = target.timeDelay;
880 else
881 target.timeDelay = 0LL;
883 // Add target to list
884 m_UniqueGOTargetInfo.push_back(target);
887 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
889 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
890 if (go)
891 AddGOTarget(go, effIndex);
894 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
896 if( m_spellInfo->Effect[effIndex]==0 )
897 return;
899 // Lookup target in already in list
900 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
902 if (pitem == ihit->item) // Found in list
904 ihit->effectMask |= 1<<effIndex; // Add only effect mask
905 return;
909 // This is new target add data
911 ItemTargetInfo target;
912 target.item = pitem;
913 target.effectMask = 1<<effIndex;
914 m_UniqueItemInfo.push_back(target);
917 void Spell::DoAllEffectOnTarget(TargetInfo *target)
919 if (target->processed) // Check target
920 return;
921 target->processed = true; // Target checked in apply effects procedure
923 // Get mask of effects for target
924 uint32 mask = target->effectMask;
926 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
927 if (!unit)
928 return;
930 // Get original caster (if exist) and calculate damage/healing from him data
931 Unit *caster = m_originalCasterGUID ? m_originalCaster : m_caster;
933 // Skip if m_originalCaster not avaiable
934 if (!caster)
935 return;
937 SpellMissInfo missInfo = target->missCondition;
938 // Need init unitTarget by default unit (can changed in code on reflect)
939 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
940 unitTarget = unit;
942 // Reset damage/healing counter
943 m_damage = 0;
944 m_healing = 0;
946 // Fill base trigger info
947 uint32 procAttacker = m_procAttacker;
948 uint32 procVictim = m_procVictim;
949 uint32 procEx = PROC_EX_NONE;
951 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
952 DoSpellHitOnUnit(unit, mask);
953 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
955 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
956 DoSpellHitOnUnit(m_caster, mask);
959 // All calculated do it!
960 // Do healing and triggers
961 if (m_healing)
963 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
964 uint32 addhealth = m_healing;
965 if (crit)
967 procEx |= PROC_EX_CRITICAL_HIT;
968 addhealth = caster->SpellCriticalBonus(m_spellInfo, addhealth, NULL);
970 else
971 procEx |= PROC_EX_NORMAL_HIT;
973 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
975 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
976 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
977 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
979 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
981 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
982 if(caster->GetTypeId()==TYPEID_PLAYER)
983 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
984 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
986 // Do damage and triggers
987 else if (m_damage)
989 // Fill base damage struct (unitTarget - is real spell target)
990 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
992 // Add bonuses and fill damageInfo struct
993 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
995 // Send log damage message to client
996 caster->SendSpellNonMeleeDamageLog(&damageInfo);
998 procEx = createProcExtendMask(&damageInfo, missInfo);
999 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1001 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1002 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1003 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
1005 caster->DealSpellDamage(&damageInfo, true);
1007 // Judgement of Blood
1008 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1010 int32 damagePoint = damageInfo.damage * 33 / 100;
1011 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1013 // Bloodthirst
1014 else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && m_spellInfo->SpellFamilyFlags & 0x40000000000LL)
1016 uint32 BTAura = 0;
1017 switch(m_spellInfo->Id)
1019 case 23881: BTAura = 23885; break;
1020 case 23892: BTAura = 23886; break;
1021 case 23893: BTAura = 23887; break;
1022 case 23894: BTAura = 23888; break;
1023 case 25251: BTAura = 25252; break;
1024 case 30335: BTAura = 30339; break;
1025 default:
1026 sLog.outError("Spell::EffectSchoolDMG: Spell %u not handled in BTAura",m_spellInfo->Id);
1027 break;
1029 if (BTAura)
1030 m_caster->CastSpell(m_caster,BTAura,true);
1033 // Passive spell hits/misses or active spells only misses (only triggers)
1034 else
1036 // Fill base damage struct (unitTarget - is real spell target)
1037 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1038 procEx = createProcExtendMask(&damageInfo, missInfo);
1039 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1040 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1041 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1044 // Call scripted function for AI if this spell is casted upon a creature (except pets)
1045 if(IS_CREATURE_GUID(target->targetGUID))
1047 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1048 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1049 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1050 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1052 if(((Creature*)unit)->AI())
1053 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1057 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1059 if(!unit || !effectMask)
1060 return;
1062 // Recheck immune (only for delayed spells)
1063 if( m_spellInfo->speed && (
1064 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1065 unit->IsImmunedToSpell(m_spellInfo)))
1067 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1068 return;
1071 if (unit->GetTypeId() == TYPEID_PLAYER)
1073 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1074 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1077 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1079 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1082 if( m_caster != unit )
1084 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1085 if (m_spellInfo->speed > 0.0f &&
1086 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1087 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1089 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1090 return;
1093 if( !m_caster->IsFriendlyTo(unit) )
1095 // for delayed spells ignore not visible explicit target
1096 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1098 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1099 return;
1102 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1104 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1106 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1107 unit->SetStandState(PLAYER_STATE_NONE);
1109 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1110 ((Creature*)unit)->AI()->AttackStart(m_caster);
1112 unit->SetInCombatWith(m_caster);
1113 m_caster->SetInCombatWith(unit);
1115 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1117 m_caster->SetContestedPvP(attackedPlayer);
1119 unit->AddThreat(m_caster, 0.0f);
1122 else
1124 // for delayed spells ignore negative spells (after duel end) for friendly targets
1125 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1127 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1128 return;
1131 // assisting case, healing and resurrection
1132 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1133 m_caster->SetContestedPvP();
1134 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1136 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1137 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1142 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1143 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1144 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1145 // Increase Diminishing on unit, current informations for actually casts will use values above
1146 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1147 unit->IncrDiminishing(m_diminishGroup);
1149 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1151 if (effectMask & (1<<effectNumber))
1153 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1154 if ( m_applyMultiplierMask & (1 << effectNumber) )
1156 // Get multiplier
1157 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1158 // Apply multiplier mods
1159 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1160 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1161 m_damageMultipliers[effectNumber] *= multiplier;
1167 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1169 if (target->processed) // Check target
1170 return;
1171 target->processed = true; // Target checked in apply effects procedure
1173 uint32 effectMask = target->effectMask;
1174 if(!effectMask)
1175 return;
1177 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1178 if(!go)
1179 return;
1181 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1182 if (effectMask & (1<<effectNumber))
1183 HandleEffects(NULL,NULL,go,effectNumber);
1185 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1186 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1187 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1188 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1191 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1193 uint32 effectMask = target->effectMask;
1194 if(!target->item || !effectMask)
1195 return;
1197 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1198 if (effectMask & (1<<effectNumber))
1199 HandleEffects(NULL, target->item, NULL, effectNumber);
1202 bool Spell::IsAliveUnitPresentInTargetList()
1204 // Not need check return true
1205 if (m_needAliveTargetMask == 0)
1206 return true;
1208 uint8 needAliveTargetMask = m_needAliveTargetMask;
1210 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1212 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1214 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1216 if (unit && unit->isAlive())
1217 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1221 // is all effects from m_needAliveTargetMask have alive targets
1222 return needAliveTargetMask==0;
1225 // Helper for Chain Healing
1226 // Spell target first
1227 // Raidmates then descending by injury suffered (MaxHealth - Health)
1228 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1229 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1231 const Unit* MainTarget;
1232 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1233 // functor for operator ">"
1234 bool operator()(Unit const* _Left, Unit const* _Right) const
1236 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1238 int32 ChainHealingHash(Unit const* Target) const
1240 if (Target == MainTarget)
1241 return 0;
1242 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1243 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1245 if (Target->GetHealth() == Target->GetMaxHealth())
1246 return 40000;
1247 else
1248 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1250 else
1251 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1255 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1257 public:
1258 const Unit* MainTarget;
1259 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1261 bool operator()(const Unit* Target)
1263 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1267 // Helper for targets nearest to the spell target
1268 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1269 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1271 const Unit* MainTarget;
1272 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1273 // functor for operator ">"
1274 bool operator()(const Unit* _Left, const Unit* _Right) const
1276 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1280 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1282 float radius;
1283 if (m_spellInfo->EffectRadiusIndex[i])
1284 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1285 else
1286 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1288 if(m_originalCaster)
1289 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1290 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1292 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1293 if(m_originalCaster)
1294 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1295 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1297 // Get spell max affected targets
1298 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1299 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1300 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1302 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1303 continue;
1304 unMaxTargets+=(*m)->GetModifier()->m_amount;
1306 switch(cur)
1308 case TARGET_TOTEM_EARTH:
1309 case TARGET_TOTEM_WATER:
1310 case TARGET_TOTEM_AIR:
1311 case TARGET_TOTEM_FIRE:
1312 case TARGET_SELF:
1313 case TARGET_SELF2:
1314 case TARGET_DYNAMIC_OBJECT:
1315 case TARGET_AREAEFFECT_CUSTOM:
1316 case TARGET_AREAEFFECT_CUSTOM_2:
1317 case TARGET_SUMMON:
1319 TagUnitMap.push_back(m_caster);
1320 break;
1322 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1324 m_targets.m_targetMask = 0;
1325 unMaxTargets = EffectChainTarget;
1326 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1328 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1329 Cell cell(p);
1330 cell.data.Part.reserved = ALL_DISTRICT;
1331 cell.SetNoCreate();
1333 std::list<Unit *> tempUnitMap;
1336 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1337 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1339 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1340 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1342 CellLock<GridReadGuard> cell_lock(cell, p);
1343 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1344 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1347 if(tempUnitMap.empty())
1348 break;
1350 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1352 //Now to get us a random target that's in the initial range of the spell
1353 uint32 t = 0;
1354 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1355 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1356 ++t, ++itr;
1358 if(!t)
1359 break;
1361 itr = tempUnitMap.begin();
1362 std::advance(itr, rand()%t);
1363 Unit *pUnitTarget = *itr;
1364 TagUnitMap.push_back(pUnitTarget);
1366 tempUnitMap.erase(itr);
1368 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1370 t = unMaxTargets - 1;
1371 Unit *prev = pUnitTarget;
1372 std::list<Unit*>::iterator next = tempUnitMap.begin();
1374 while(t && next != tempUnitMap.end() )
1376 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1377 break;
1379 if(!prev->IsWithinLOSInMap(*next))
1381 ++next;
1382 continue;
1385 prev = *next;
1386 TagUnitMap.push_back(prev);
1387 tempUnitMap.erase(next);
1388 tempUnitMap.sort(TargetDistanceOrder(prev));
1389 next = tempUnitMap.begin();
1391 --t;
1393 }break;
1394 case TARGET_PET:
1396 Pet* tmpUnit = m_caster->GetPet();
1397 if (!tmpUnit) break;
1398 TagUnitMap.push_back(tmpUnit);
1399 break;
1401 case TARGET_CHAIN_DAMAGE:
1403 if (EffectChainTarget <= 1)
1405 Unit* pUnitTarget = SelectMagnetTarget();
1406 if(pUnitTarget)
1407 TagUnitMap.push_back(pUnitTarget);
1409 else
1411 Unit* pUnitTarget = m_targets.getUnitTarget();
1412 if(!pUnitTarget)
1413 break;
1415 unMaxTargets = EffectChainTarget;
1417 float max_range;
1418 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1419 max_range = radius; //
1420 else
1421 //FIXME: This very like horrible hack and wrong for most spells
1422 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1424 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1425 Cell cell(p);
1426 cell.data.Part.reserved = ALL_DISTRICT;
1427 cell.SetNoCreate();
1429 Unit* originalCaster = GetOriginalCaster();
1430 if(originalCaster)
1432 std::list<Unit *> tempUnitMap;
1435 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1436 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1438 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1439 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1441 CellLock<GridReadGuard> cell_lock(cell, p);
1442 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1443 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1446 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1448 if(tempUnitMap.empty())
1449 break;
1451 if(*tempUnitMap.begin() == pUnitTarget)
1452 tempUnitMap.erase(tempUnitMap.begin());
1454 TagUnitMap.push_back(pUnitTarget);
1455 uint32 t = unMaxTargets - 1;
1456 Unit *prev = pUnitTarget;
1457 std::list<Unit*>::iterator next = tempUnitMap.begin();
1459 while(t && next != tempUnitMap.end() )
1461 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1462 break;
1464 if(!prev->IsWithinLOSInMap(*next))
1466 ++next;
1467 continue;
1470 prev = *next;
1471 TagUnitMap.push_back(prev);
1472 tempUnitMap.erase(next);
1473 tempUnitMap.sort(TargetDistanceOrder(prev));
1474 next = tempUnitMap.begin();
1476 --t;
1480 }break;
1481 case TARGET_ALL_ENEMY_IN_AREA:
1483 }break;
1484 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1486 // targets the ground, not the units in the area
1487 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1489 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1490 Cell cell(p);
1491 cell.data.Part.reserved = ALL_DISTRICT;
1492 cell.SetNoCreate();
1494 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1496 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1497 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1499 CellLock<GridReadGuard> cell_lock(cell, p);
1500 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1501 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1503 // exclude caster (this can be important if this not original caster)
1504 TagUnitMap.remove(m_caster);
1506 }break;
1507 case TARGET_DUELVSPLAYER_COORDINATES:
1509 if(Unit* currentTarget = m_targets.getUnitTarget())
1511 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1512 TagUnitMap.push_back(currentTarget);
1514 }break;
1515 case TARGET_ALL_PARTY_AROUND_CASTER:
1516 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1517 case TARGET_ALL_PARTY:
1518 case TARGET_ALL_RAID_AROUND_CASTER:
1520 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1521 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1523 if(pGroup)
1525 uint8 subgroup = pTarget->GetSubGroup();
1527 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1529 Player* Target = itr->getSource();
1531 // IsHostileTo check duel and controlled by enemy
1532 if( Target &&
1533 (cur==TARGET_ALL_RAID_AROUND_CASTER || Target->GetSubGroup()==subgroup) &&
1534 !m_caster->IsHostileTo(Target) )
1536 if( m_caster->IsWithinDistInMap(Target, radius) )
1537 TagUnitMap.push_back(Target);
1539 if(Pet* pet = Target->GetPet())
1540 if( m_caster->IsWithinDistInMap(pet, radius) )
1541 TagUnitMap.push_back(pet);
1545 else
1547 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1548 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1549 TagUnitMap.push_back(ownerOrSelf);
1550 if(Pet* pet = ownerOrSelf->GetPet())
1551 if( m_caster->IsWithinDistInMap(pet, radius) )
1552 TagUnitMap.push_back(pet);
1554 }break;
1555 case TARGET_SINGLE_FRIEND:
1556 case TARGET_SINGLE_FRIEND_2:
1558 if(m_targets.getUnitTarget())
1559 TagUnitMap.push_back(m_targets.getUnitTarget());
1560 }break;
1561 case TARGET_NONCOMBAT_PET:
1563 if(Unit* target = m_targets.getUnitTarget())
1564 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1565 TagUnitMap.push_back(target);
1566 }break;
1567 case TARGET_ALL_AROUND_CASTER:
1569 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1570 Cell cell(p);
1571 cell.data.Part.reserved = ALL_DISTRICT;
1572 cell.SetNoCreate();
1574 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1576 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1577 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1579 CellLock<GridReadGuard> cell_lock(cell, p);
1580 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1581 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1582 }break;
1583 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1585 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1586 Cell cell(p);
1587 cell.data.Part.reserved = ALL_DISTRICT;
1588 cell.SetNoCreate();
1590 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1592 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1593 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1595 CellLock<GridReadGuard> cell_lock(cell, p);
1596 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1597 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1598 }break;
1599 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1601 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1602 Cell cell(p);
1603 cell.data.Part.reserved = ALL_DISTRICT;
1604 cell.SetNoCreate();
1606 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1608 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1609 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1611 CellLock<GridReadGuard> cell_lock(cell, p);
1612 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1613 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1614 }break;
1615 // 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..)
1616 case TARGET_SINGLE_PARTY:
1618 Unit *target = m_targets.getUnitTarget();
1619 // Thoses spells apparently can't be casted on the caster.
1620 if( target && target != m_caster)
1622 // Can only be casted on group's members or its pets
1623 Group *pGroup = NULL;
1625 Unit* owner = m_caster->GetCharmerOrOwner();
1626 Unit *targetOwner = target->GetCharmerOrOwner();
1627 if(owner)
1629 if(owner->GetTypeId() == TYPEID_PLAYER)
1631 if( target == owner )
1633 TagUnitMap.push_back(target);
1634 break;
1636 pGroup = ((Player*)owner)->GetGroup();
1639 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1641 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1643 TagUnitMap.push_back(target);
1644 break;
1646 pGroup = ((Player*)m_caster)->GetGroup();
1649 if(pGroup)
1651 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1652 if(targetOwner)
1654 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1655 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1656 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1657 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1659 TagUnitMap.push_back(target);
1662 // 1Our target can be a player who is on our group
1663 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1665 TagUnitMap.push_back(target);
1669 }break;
1670 case TARGET_GAMEOBJECT:
1672 if(m_targets.getGOTarget())
1673 AddGOTarget(m_targets.getGOTarget(), i);
1674 }break;
1675 case TARGET_IN_FRONT_OF_CASTER:
1677 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1678 Cell cell(p);
1679 cell.data.Part.reserved = ALL_DISTRICT;
1680 cell.SetNoCreate();
1682 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1683 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1685 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1686 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1688 CellLock<GridReadGuard> cell_lock(cell, p);
1689 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1690 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1691 }break;
1692 case TARGET_DUELVSPLAYER:
1694 Unit *target = m_targets.getUnitTarget();
1695 if(target)
1697 if(m_caster->IsFriendlyTo(target))
1699 TagUnitMap.push_back(target);
1701 else
1703 Unit* pUnitTarget = SelectMagnetTarget();
1704 if(pUnitTarget)
1705 TagUnitMap.push_back(pUnitTarget);
1708 }break;
1709 case TARGET_GAMEOBJECT_ITEM:
1711 if(m_targets.getGOTargetGUID())
1712 AddGOTarget(m_targets.getGOTarget(), i);
1713 else if(m_targets.getItemTarget())
1714 AddItemTarget(m_targets.getItemTarget(), i);
1715 break;
1717 case TARGET_MASTER:
1719 if(Unit* owner = m_caster->GetCharmerOrOwner())
1720 TagUnitMap.push_back(owner);
1721 break;
1723 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1725 // targets the ground, not the units in the area
1726 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1728 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1729 Cell cell(p);
1730 cell.data.Part.reserved = ALL_DISTRICT;
1731 cell.SetNoCreate();
1733 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1735 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1736 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1738 CellLock<GridReadGuard> cell_lock(cell, p);
1739 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1740 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1742 }break;
1743 case TARGET_MINION:
1745 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1746 TagUnitMap.push_back(m_caster);
1747 }break;
1748 case TARGET_SINGLE_ENEMY:
1750 Unit* pUnitTarget = SelectMagnetTarget();
1751 if(pUnitTarget)
1752 TagUnitMap.push_back(pUnitTarget);
1753 }break;
1754 case TARGET_AREAEFFECT_PARTY:
1756 Unit* owner = m_caster->GetCharmerOrOwner();
1757 Player *pTarget = NULL;
1759 if(owner)
1761 TagUnitMap.push_back(m_caster);
1762 if(owner->GetTypeId() == TYPEID_PLAYER)
1763 pTarget = (Player*)owner;
1765 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1767 if(Unit* target = m_targets.getUnitTarget())
1769 if( target->GetTypeId() != TYPEID_PLAYER)
1771 if(((Creature*)target)->isPet())
1773 Unit *targetOwner = target->GetOwner();
1774 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1775 pTarget = (Player*)targetOwner;
1778 else
1779 pTarget = (Player*)target;
1783 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1785 if(pGroup)
1787 uint8 subgroup = pTarget->GetSubGroup();
1789 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1791 Player* Target = itr->getSource();
1793 // IsHostileTo check duel and controlled by enemy
1794 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1796 if( pTarget->IsWithinDistInMap(Target, radius) )
1797 TagUnitMap.push_back(Target);
1799 if(Pet* pet = Target->GetPet())
1800 if( pTarget->IsWithinDistInMap(pet, radius) )
1801 TagUnitMap.push_back(pet);
1805 else if (owner)
1807 if(m_caster->IsWithinDistInMap(owner, radius))
1808 TagUnitMap.push_back(owner);
1810 else if(pTarget)
1812 TagUnitMap.push_back(pTarget);
1814 if(Pet* pet = pTarget->GetPet())
1815 if( m_caster->IsWithinDistInMap(pet, radius) )
1816 TagUnitMap.push_back(pet);
1819 }break;
1820 case TARGET_SCRIPT:
1822 if(m_targets.getUnitTarget())
1823 TagUnitMap.push_back(m_targets.getUnitTarget());
1824 if(m_targets.getItemTarget())
1825 AddItemTarget(m_targets.getItemTarget(), i);
1826 }break;
1827 case TARGET_SELF_FISHING:
1829 TagUnitMap.push_back(m_caster);
1830 }break;
1831 case TARGET_CHAIN_HEAL:
1833 Unit* pUnitTarget = m_targets.getUnitTarget();
1834 if(!pUnitTarget)
1835 break;
1837 if (EffectChainTarget <= 1)
1838 TagUnitMap.push_back(pUnitTarget);
1839 else
1841 unMaxTargets = EffectChainTarget;
1842 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1844 std::list<Unit *> tempUnitMap;
1847 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1848 Cell cell(p);
1849 cell.data.Part.reserved = ALL_DISTRICT;
1850 cell.SetNoCreate();
1852 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1854 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1855 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1857 CellLock<GridReadGuard> cell_lock(cell, p);
1858 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1859 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1863 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1864 tempUnitMap.push_front(m_caster);
1866 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1868 if(tempUnitMap.empty())
1869 break;
1871 if(*tempUnitMap.begin() == pUnitTarget)
1872 tempUnitMap.erase(tempUnitMap.begin());
1874 TagUnitMap.push_back(pUnitTarget);
1875 uint32 t = unMaxTargets - 1;
1876 Unit *prev = pUnitTarget;
1877 std::list<Unit*>::iterator next = tempUnitMap.begin();
1879 while(t && next != tempUnitMap.end() )
1881 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1882 break;
1884 if(!prev->IsWithinLOSInMap(*next))
1886 ++next;
1887 continue;
1890 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1892 next = tempUnitMap.erase(next);
1893 continue;
1896 prev = *next;
1897 TagUnitMap.push_back(prev);
1898 tempUnitMap.erase(next);
1899 tempUnitMap.sort(TargetDistanceOrder(prev));
1900 next = tempUnitMap.begin();
1902 --t;
1905 }break;
1906 case TARGET_CURRENT_ENEMY_COORDINATES:
1908 Unit* currentTarget = m_targets.getUnitTarget();
1909 if(currentTarget)
1911 TagUnitMap.push_back(currentTarget);
1912 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1913 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1915 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1916 Cell cell(p);
1917 cell.data.Part.reserved = ALL_DISTRICT;
1918 cell.SetNoCreate();
1919 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1920 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1921 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1922 CellLock<GridReadGuard> cell_lock(cell, p);
1923 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1924 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1927 }break;
1928 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1930 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1931 ? (Player*)m_targets.getUnitTarget() : NULL;
1933 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1934 if(pGroup)
1936 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1938 Player* Target = itr->getSource();
1940 // IsHostileTo check duel and controlled by enemy
1941 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1942 targetPlayer->getClass() == Target->getClass() &&
1943 !m_caster->IsHostileTo(Target) )
1945 TagUnitMap.push_back(Target);
1949 else if(m_targets.getUnitTarget())
1950 TagUnitMap.push_back(m_targets.getUnitTarget());
1951 break;
1953 case TARGET_TABLE_X_Y_Z_COORDINATES:
1955 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
1956 if(st)
1958 if (st->target_mapId == m_caster->GetMapId())
1959 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1961 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
1962 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
1964 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1965 Cell cell(p);
1966 cell.data.Part.reserved = ALL_DISTRICT;
1967 cell.SetNoCreate();
1969 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1970 // Select friendly targets for positive effect
1971 if (IsPositiveEffect(m_spellInfo->Id, i))
1972 targetB = SPELL_TARGETS_FRIENDLY;
1974 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
1976 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1977 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1979 CellLock<GridReadGuard> cell_lock(cell, p);
1980 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1981 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1984 else
1985 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1986 }break;
1987 case TARGET_BEHIND_VICTIM:
1989 Unit *pTarget = m_caster->getVictim();
1990 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
1991 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
1993 if(pTarget)
1995 float _target_x, _target_y, _target_z;
1996 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
1997 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
1998 m_targets.setDestination(_target_x, _target_y, _target_z);
2000 }break;
2001 default:
2002 break;
2005 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2007 // make sure one unit is always removed per iteration
2008 uint32 removed_utarget = 0;
2009 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2011 next = itr;
2012 ++next;
2013 if (!*itr) continue;
2014 if ((*itr) == m_targets.getUnitTarget())
2016 TagUnitMap.erase(itr);
2017 removed_utarget = 1;
2018 // break;
2021 // remove random units from the map
2022 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2024 uint32 poz = urand(0, TagUnitMap.size()-1);
2025 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2027 if (!*itr) continue;
2028 if (!poz)
2030 TagUnitMap.erase(itr);
2031 break;
2035 // the player's target will always be added to the map
2036 if (removed_utarget && m_targets.getUnitTarget())
2037 TagUnitMap.push_back(m_targets.getUnitTarget());
2041 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2043 m_targets = *targets;
2045 m_spellState = SPELL_STATE_PREPARING;
2047 m_castPositionX = m_caster->GetPositionX();
2048 m_castPositionY = m_caster->GetPositionY();
2049 m_castPositionZ = m_caster->GetPositionZ();
2050 m_castOrientation = m_caster->GetOrientation();
2052 if(triggeredByAura)
2053 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2055 // create and add update event for this spell
2056 SpellEvent* Event = new SpellEvent(this);
2057 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2059 //Prevent casting at cast another spell (ServerSide check)
2060 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2062 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2063 finish(false);
2064 return;
2067 // Fill cost data
2068 m_powerCost = CalculatePowerCost();
2070 uint8 result = CanCast(true);
2071 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2073 if(triggeredByAura)
2075 SendChannelUpdate(0);
2076 triggeredByAura->SetAuraDuration(0);
2078 SendCastResult(result);
2079 finish(false);
2080 return;
2083 // Prepare data for triggers
2084 prepareDataForTriggerSystem();
2086 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2087 m_casttime = GetSpellCastTime(m_spellInfo, this);
2089 // set timer base at cast time
2090 ReSetTimer();
2092 // stealth must be removed at cast starting (at show channel bar)
2093 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2094 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2096 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2097 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2100 if(m_IsTriggeredSpell)
2101 cast(true);
2102 else
2104 m_caster->SetCurrentCastedSpell( this );
2105 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2106 SendSpellStart();
2110 void Spell::cancel()
2112 if(m_spellState == SPELL_STATE_FINISHED)
2113 return;
2115 m_autoRepeat = false;
2116 switch (m_spellState)
2118 case SPELL_STATE_PREPARING:
2119 case SPELL_STATE_DELAYED:
2121 SendInterrupted(0);
2122 SendCastResult(SPELL_FAILED_INTERRUPTED);
2123 } break;
2125 case SPELL_STATE_CASTING:
2127 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2129 if( ihit->missCondition == SPELL_MISS_NONE )
2131 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2132 if( unit && unit->isAlive() )
2133 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2137 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2138 SendChannelUpdate(0);
2139 SendInterrupted(0);
2140 SendCastResult(SPELL_FAILED_INTERRUPTED);
2141 } break;
2143 default:
2145 } break;
2148 finish(false);
2149 m_caster->RemoveDynObject(m_spellInfo->Id);
2150 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2153 void Spell::cast(bool skipCheck)
2155 SetExecutedCurrently(true);
2157 uint8 castResult = 0;
2159 // update pointers base at GUIDs to prevent access to non-existed already object
2160 UpdatePointers();
2162 // cancel at lost main target unit
2163 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2165 cancel();
2166 SetExecutedCurrently(false);
2167 return;
2170 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2171 m_caster->SetInFront(m_targets.getUnitTarget());
2173 castResult = CheckPower();
2174 if(castResult != 0)
2176 SendCastResult(castResult);
2177 finish(false);
2178 SetExecutedCurrently(false);
2179 return;
2182 // triggered cast called from Spell::prepare where it was already checked
2183 if(!skipCheck)
2185 castResult = CanCast(false);
2186 if(castResult != 0)
2188 SendCastResult(castResult);
2189 finish(false);
2190 SetExecutedCurrently(false);
2191 return;
2195 // Conflagrate - consumes immolate
2196 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2198 // for caster applied auras only
2199 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2200 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2202 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2203 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2205 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2206 break;
2211 // traded items have trade slot instead of guid in m_itemTargetGUID
2212 // set to real guid to be sent later to the client
2213 m_targets.updateTradeSlotItem();
2215 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2217 if (m_CastItem)
2218 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2220 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2223 // CAST SPELL
2224 SendSpellCooldown();
2226 TakePower();
2227 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2228 FillTargetMap();
2230 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2232 SetExecutedCurrently(false);
2233 return;
2236 SendCastResult(castResult);
2237 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2239 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2240 if (m_spellInfo->speed > 0.0f)
2243 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2244 // in case delayed spell remove item at cast delay start
2245 TakeCastItem();
2247 // Okay, maps created, now prepare flags
2248 m_immediateHandled = false;
2249 m_spellState = SPELL_STATE_DELAYED;
2250 SetDelayStart(0);
2252 else
2254 // Immediate spell, no big deal
2255 handle_immediate();
2258 SetExecutedCurrently(false);
2261 void Spell::handle_immediate()
2263 // start channeling if applicable
2264 if(IsChanneledSpell(m_spellInfo))
2266 int32 duration = GetSpellDuration(m_spellInfo);
2267 if (duration)
2269 m_spellState = SPELL_STATE_CASTING;
2270 SendChannelStart(duration);
2274 // process immediate effects (items, ground, etc.) also initialize some variables
2275 _handle_immediate_phase();
2277 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2278 DoAllEffectOnTarget(&(*ihit));
2280 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2281 DoAllEffectOnTarget(&(*ihit));
2283 // spell is finished, perform some last features of the spell here
2284 _handle_finish_phase();
2286 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2287 TakeCastItem();
2289 if(m_spellState != SPELL_STATE_CASTING)
2290 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2293 uint64 Spell::handle_delayed(uint64 t_offset)
2295 uint64 next_time = 0;
2297 if (!m_immediateHandled)
2299 _handle_immediate_phase();
2300 m_immediateHandled = true;
2303 // 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)
2304 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2306 if (ihit->processed == false)
2308 if ( ihit->timeDelay <= t_offset )
2309 DoAllEffectOnTarget(&(*ihit));
2310 else if( next_time == 0 || ihit->timeDelay < next_time )
2311 next_time = ihit->timeDelay;
2315 // now recheck gameobject targeting correctness
2316 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2318 if (ighit->processed == false)
2320 if ( ighit->timeDelay <= t_offset )
2321 DoAllEffectOnTarget(&(*ighit));
2322 else if( next_time == 0 || ighit->timeDelay < next_time )
2323 next_time = ighit->timeDelay;
2326 // All targets passed - need finish phase
2327 if (next_time == 0)
2329 // spell is finished, perform some last features of the spell here
2330 _handle_finish_phase();
2332 finish(true); // successfully finish spell cast
2334 // return zero, spell is finished now
2335 return 0;
2337 else
2339 // spell is unfinished, return next execution time
2340 return next_time;
2344 void Spell::_handle_immediate_phase()
2346 // handle some immediate features of the spell here
2347 HandleThreatSpells(m_spellInfo->Id);
2349 m_needSpellLog = IsNeedSendToClient();
2350 for(uint32 j = 0;j<3;j++)
2352 if(m_spellInfo->Effect[j]==0)
2353 continue;
2355 // apply Send Event effect to ground in case empty target lists
2356 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2358 HandleEffects(NULL,NULL,NULL, j);
2359 continue;
2362 // Don't do spell log, if is school damage spell
2363 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2364 m_needSpellLog = false;
2366 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2367 if(m_originalCaster)
2368 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2369 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2371 // initialize multipliers
2372 m_damageMultipliers[j] = 1.0f;
2373 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2374 (EffectChainTarget > 1) )
2375 m_applyMultiplierMask |= 1 << j;
2378 // initialize Diminishing Returns Data
2379 m_diminishLevel = DIMINISHING_LEVEL_1;
2380 m_diminishGroup = DIMINISHING_NONE;
2382 // process items
2383 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2384 DoAllEffectOnTarget(&(*ihit));
2386 // process ground
2387 for(uint32 j = 0;j<3;j++)
2389 // persistent area auras target only the ground
2390 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2391 HandleEffects(NULL,NULL,NULL, j);
2395 void Spell::_handle_finish_phase()
2397 // spell log
2398 if(m_needSpellLog)
2399 SendLogExecute();
2402 void Spell::SendSpellCooldown()
2404 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2405 return;
2407 Player* _player = (Player*)m_caster;
2408 // Add cooldown for max (disable spell)
2409 // Cooldown started on SendCooldownEvent call
2410 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2412 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2413 return;
2416 // init cooldown values
2417 uint32 cat = 0;
2418 int32 rec = -1;
2419 int32 catrec = -1;
2421 // some special item spells without correct cooldown in SpellInfo
2422 // cooldown information stored in item prototype
2423 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2425 if(m_CastItem)
2427 ItemPrototype const* proto = m_CastItem->GetProto();
2428 if(proto)
2430 for(int idx = 0; idx < 5; ++idx)
2432 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2434 cat = proto->Spells[idx].SpellCategory;
2435 rec = proto->Spells[idx].SpellCooldown;
2436 catrec = proto->Spells[idx].SpellCategoryCooldown;
2437 break;
2443 // if no cooldown found above then base at DBC data
2444 if(rec < 0 && catrec < 0)
2446 cat = m_spellInfo->Category;
2447 rec = m_spellInfo->RecoveryTime;
2448 catrec = m_spellInfo->CategoryRecoveryTime;
2451 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2452 // prevent 0 cooldowns set by another way
2453 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT))
2454 rec = _player->GetAttackTime(RANGED_ATTACK);
2456 // Now we have cooldown data (if found any), time to apply mods
2457 if(rec > 0)
2458 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2460 if(catrec > 0)
2461 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2463 // replace negative cooldowns by 0
2464 if (rec < 0) rec = 0;
2465 if (catrec < 0) catrec = 0;
2467 // no cooldown after applying spell mods
2468 if( rec == 0 && catrec == 0)
2469 return;
2471 time_t curTime = time(NULL);
2473 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2474 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2476 // self spell cooldown
2477 if(recTime > 0)
2478 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2480 // category spells
2481 if (catrec > 0)
2483 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2484 if(i_scstore != sSpellCategoryStore.end())
2486 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2488 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2489 continue;
2491 _player->AddSpellCooldown(*i_scset, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2497 void Spell::update(uint32 difftime)
2499 // update pointers based at it's GUIDs
2500 UpdatePointers();
2502 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2504 cancel();
2505 return;
2508 // check if the player caster has moved before the spell finished
2509 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2510 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2511 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2513 // always cancel for channeled spells
2514 if( m_spellState == SPELL_STATE_CASTING )
2515 cancel();
2516 // don't cancel for melee, autorepeat, triggered and instant spells
2517 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2518 cancel();
2521 switch(m_spellState)
2523 case SPELL_STATE_PREPARING:
2525 if(m_timer)
2527 if(difftime >= m_timer)
2528 m_timer = 0;
2529 else
2530 m_timer -= difftime;
2533 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2534 cast();
2535 } break;
2536 case SPELL_STATE_CASTING:
2538 if(m_timer > 0)
2540 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2542 // check if player has jumped before the channeling finished
2543 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2544 cancel();
2546 // check for incapacitating player states
2547 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2548 cancel();
2550 // check if player has turned if flag is set
2551 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2552 cancel();
2555 // check if there are alive targets left
2556 if (!IsAliveUnitPresentInTargetList())
2558 SendChannelUpdate(0);
2559 finish();
2562 if(difftime >= m_timer)
2563 m_timer = 0;
2564 else
2565 m_timer -= difftime;
2568 if(m_timer == 0)
2570 SendChannelUpdate(0);
2572 // channeled spell processed independently for quest targeting
2573 // cast at creature (or GO) quest objectives update at successful cast channel finished
2574 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2575 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2577 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2579 TargetInfo* target = &*ihit;
2580 if(!IS_CREATURE_GUID(target->targetGUID))
2581 continue;
2583 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2584 if (unit==NULL)
2585 continue;
2587 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2590 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2592 GOTargetInfo* target = &*ihit;
2594 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2595 if(!go)
2596 continue;
2598 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2602 finish();
2604 } break;
2605 default:
2607 }break;
2611 void Spell::finish(bool ok)
2613 if(!m_caster)
2614 return;
2616 if(m_spellState == SPELL_STATE_FINISHED)
2617 return;
2619 m_spellState = SPELL_STATE_FINISHED;
2621 // other code related only to successfully finished spells
2622 if(!ok)
2623 return;
2625 //remove spell mods
2626 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2627 ((Player*)m_caster)->RemoveSpellMods(this);
2629 //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2630 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2631 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2633 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2634 uint32 auraSpellIdx = (*i)->GetEffIndex();
2635 if (IsAffectedByAura((*i)))
2637 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2638 if( ihit->effectMask & (1<<auraSpellIdx) )
2640 // check m_caster->GetGUID() let load auras at login and speedup most often case
2641 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2642 if (unit && unit->isAlive())
2644 // Calculate chance at that moment (can be depend for example from combo points)
2645 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2647 if(roll_chance_i(chance))
2648 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2654 // Heal caster for all health leech from all targets
2655 if (m_healthLeech)
2657 m_caster->ModifyHealth(m_healthLeech);
2658 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2661 if (IsMeleeAttackResetSpell())
2663 m_caster->resetAttackTimer(BASE_ATTACK);
2664 if(m_caster->haveOffhandWeapon())
2665 m_caster->resetAttackTimer(OFF_ATTACK);
2668 /*if (IsRangedAttackResetSpell())
2669 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2671 // Clear combo at finish state
2672 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2674 // Not drop combopoints if negative spell and if any miss on enemy exist
2675 bool needDrop = true;
2676 if (!IsPositiveSpell(m_spellInfo->Id))
2677 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2678 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2680 needDrop = false;
2681 break;
2683 if (needDrop)
2684 ((Player*)m_caster)->ClearComboPoints();
2687 // Post effects apply on spell targets in some spells
2688 if(!m_UniqueTargetInfo.empty())
2690 uint32 spellId = 0;
2691 switch(m_spellInfo->SpellFamilyName)
2693 case SPELLFAMILY_GENERIC:
2695 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2696 spellId = 11196; // Recently Bandaged
2697 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2698 spellId = 23230; // Blood Fury - Healing Reduction
2699 break;
2701 case SPELLFAMILY_MAGE:
2703 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2704 spellId = 41425; // Hypothermia
2705 break;
2707 case SPELLFAMILY_PRIEST:
2709 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2710 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2711 spellId = 6788; // Weakened Soul
2712 break;
2714 case SPELLFAMILY_PALADIN:
2716 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2717 spellId = 25771; // Forbearance
2718 break;
2720 case SPELLFAMILY_SHAMAN:
2722 if (m_spellInfo->Id == 2825) // Bloodlust
2723 spellId = 57724; // Sated
2724 else if (m_spellInfo->Id == 32182) // Heroism
2725 spellId = 57723; // Exhaustion
2726 break;
2728 default:
2729 break;
2731 if (spellId)
2733 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2735 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2736 if (unit)
2738 // TODO: fix me use cast spell (now post spell can immune by this spell)
2739 // m_caster->CastSpell(unit, spellId, true, m_CastItem);
2740 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(spellId);
2741 if (!AdditionalSpellInfo)
2742 continue;
2743 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, 0, &m_currentBasePoints[0], unit, m_caster, m_CastItem);
2744 unit->AddAura(AdditionalAura);
2749 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2750 if(!m_TriggerSpells.empty())
2751 TriggerSpell();
2753 // Stop Attack for some spells
2754 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2755 m_caster->AttackStop();
2758 void Spell::SendCastResult(uint8 result)
2760 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2761 return;
2763 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2764 return;
2766 if(result != 0)
2768 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2769 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2770 data << uint32(m_spellInfo->Id);
2771 data << uint8(result); // problem
2772 switch (result)
2774 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2775 data << uint32(m_spellInfo->RequiresSpellFocus);
2776 break;
2777 case SPELL_FAILED_REQUIRES_AREA:
2778 // hardcode areas limitation case
2779 switch(m_spellInfo->Id)
2781 case 41617: // Cenarion Mana Salve
2782 case 41619: // Cenarion Healing Salve
2783 data << uint32(3905);
2784 break;
2785 case 41618: // Bottled Nethergon Energy
2786 case 41620: // Bottled Nethergon Vapor
2787 data << uint32(3842);
2788 break;
2789 case 45373: // Bloodberry Elixir
2790 data << uint32(4075);
2791 break;
2792 default: // default case (don't must be)
2793 data << uint32(0);
2794 break;
2796 break;
2797 case SPELL_FAILED_TOTEMS:
2798 if(m_spellInfo->Totem[0])
2799 data << uint32(m_spellInfo->Totem[0]);
2800 if(m_spellInfo->Totem[1])
2801 data << uint32(m_spellInfo->Totem[1]);
2802 break;
2803 case SPELL_FAILED_TOTEM_CATEGORY:
2804 if(m_spellInfo->TotemCategory[0])
2805 data << uint32(m_spellInfo->TotemCategory[0]);
2806 if(m_spellInfo->TotemCategory[1])
2807 data << uint32(m_spellInfo->TotemCategory[1]);
2808 break;
2809 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2810 data << uint32(m_spellInfo->EquippedItemClass);
2811 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2812 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2813 break;
2815 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2819 void Spell::SendSpellStart()
2821 if(!IsNeedSendToClient())
2822 return;
2824 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2826 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2827 if(IsRangedSpell())
2828 castFlags |= CAST_FLAG_AMMO;
2830 if(m_spellInfo->runeCostID)
2831 castFlags |= CAST_FLAG_UNKNOWN10;
2833 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2835 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2836 if(m_CastItem)
2837 data.append(m_CastItem->GetPackGUID());
2838 else
2839 data.append(m_caster->GetPackGUID());
2841 data.append(m_caster->GetPackGUID());
2842 data << uint8(m_cast_count); // pending spell cast?
2843 data << uint32(m_spellInfo->Id); // spellId
2844 data << uint32(castFlags); // cast flags
2845 data << uint32(m_timer); // delay?
2847 m_targets.write(&data);
2849 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2850 data << uint32(0);
2852 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2854 uint8 v1 = 0;//m_runesState;
2855 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2856 data << uint8(v1); // runes state before
2857 data << uint8(v2); // runes state after
2858 for(uint8 i = 0; i < MAX_RUNES; ++i)
2860 uint8 m = (1 << i);
2861 if(m & v1) // usable before...
2862 if(!(m & v2)) // ...but on cooldown now...
2863 data << uint8(0); // some unknown byte (time?)
2867 if ( castFlags & CAST_FLAG_AMMO )
2868 WriteAmmoToPacket(&data);
2870 m_caster->SendMessageToSet(&data, true);
2873 void Spell::SendSpellGo()
2875 // not send invisible spell casting
2876 if(!IsNeedSendToClient())
2877 return;
2879 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2881 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2883 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2884 if(IsRangedSpell())
2885 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2887 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2889 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2890 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2891 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2894 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2895 if(m_CastItem)
2896 data.append(m_CastItem->GetPackGUID());
2897 else
2898 data.append(m_caster->GetPackGUID());
2900 data.append(m_caster->GetPackGUID());
2901 data << uint8(m_cast_count); // pending spell cast?
2902 data << uint32(m_spellInfo->Id); // spellId
2903 data << uint32(castFlags); // cast flags
2904 data << uint32(getMSTime()); // timestamp
2906 WriteSpellGoTargets(&data);
2908 m_targets.write(&data);
2910 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2911 data << uint32(0);
2913 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2915 uint8 v1 = m_runesState;
2916 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2917 data << uint8(v1); // runes state before
2918 data << uint8(v2); // runes state after
2919 for(uint8 i = 0; i < MAX_RUNES; ++i)
2921 uint8 m = (1 << i);
2922 if(m & v1) // usable before...
2923 if(!(m & v2)) // ...but on cooldown now...
2924 data << uint8(0); // some unknown byte (time?)
2928 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2930 data << float(0);
2931 data << uint32(0);
2934 if ( castFlags & CAST_FLAG_AMMO )
2935 WriteAmmoToPacket(&data);
2937 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2939 data << uint32(0);
2940 data << uint32(0);
2943 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2945 data << uint8(0);
2948 m_caster->SendMessageToSet(&data, true);
2951 void Spell::WriteAmmoToPacket( WorldPacket * data )
2953 uint32 ammoInventoryType = 0;
2954 uint32 ammoDisplayID = 0;
2956 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2958 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2959 if(pItem)
2961 ammoInventoryType = pItem->GetProto()->InventoryType;
2962 if( ammoInventoryType == INVTYPE_THROWN )
2963 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2964 else
2966 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2967 if(ammoID)
2969 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2970 if(pProto)
2972 ammoDisplayID = pProto->DisplayInfoID;
2973 ammoInventoryType = pProto->InventoryType;
2976 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
2978 ammoDisplayID = 5996; // normal arrow
2979 ammoInventoryType = INVTYPE_AMMO;
2984 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2986 *data << uint32(ammoDisplayID);
2987 *data << uint32(ammoInventoryType);
2990 void Spell::WriteSpellGoTargets( WorldPacket * data )
2992 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
2993 uint32 miss = 0;
2994 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2996 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
2998 // possibly SPELL_MISS_IMMUNE2 for this??
2999 ihit->missCondition = SPELL_MISS_IMMUNE2;
3000 miss++;
3002 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3003 hit++;
3004 else
3005 miss++;
3008 *data << (uint8)hit;
3009 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3010 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3011 *data << uint64(ihit->targetGUID);
3013 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3014 *data << uint64(ighit->targetGUID); // Always hits
3016 *data << (uint8)miss;
3017 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3019 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3021 *data << uint64(ihit->targetGUID);
3022 *data << uint8(ihit->missCondition);
3023 if( ihit->missCondition == SPELL_MISS_REFLECT )
3024 *data << uint8(ihit->reflectResult);
3029 void Spell::SendLogExecute()
3031 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3033 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3035 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3036 data.append(m_caster->GetPackGUID());
3037 else
3038 data.append(target->GetPackGUID());
3040 data << uint32(m_spellInfo->Id);
3041 uint32 count1 = 1;
3042 data << uint32(count1); // count1 (effect count?)
3043 for(uint32 i = 0; i < count1; ++i)
3045 data << uint32(m_spellInfo->Effect[0]); // spell effect
3046 uint32 count2 = 1;
3047 data << uint32(count2); // count2 (target count?)
3048 for(uint32 j = 0; j < count2; ++j)
3050 switch(m_spellInfo->Effect[0])
3052 case SPELL_EFFECT_POWER_DRAIN:
3053 if(Unit *unit = m_targets.getUnitTarget())
3054 data.append(unit->GetPackGUID());
3055 else
3056 data << uint8(0);
3057 data << uint32(0);
3058 data << uint32(0);
3059 data << float(0);
3060 break;
3061 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3062 if(Unit *unit = m_targets.getUnitTarget())
3063 data.append(unit->GetPackGUID());
3064 else
3065 data << uint8(0);
3066 data << uint32(0); // count?
3067 break;
3068 case SPELL_EFFECT_INTERRUPT_CAST:
3069 if(Unit *unit = m_targets.getUnitTarget())
3070 data.append(unit->GetPackGUID());
3071 else
3072 data << uint8(0);
3073 data << uint32(0); // spellid
3074 break;
3075 case SPELL_EFFECT_DURABILITY_DAMAGE:
3076 if(Unit *unit = m_targets.getUnitTarget())
3077 data.append(unit->GetPackGUID());
3078 else
3079 data << uint8(0);
3080 data << uint32(0);
3081 data << uint32(0);
3082 break;
3083 case SPELL_EFFECT_OPEN_LOCK:
3084 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3085 if(Item *item = m_targets.getItemTarget())
3086 data.append(item->GetPackGUID());
3087 else
3088 data << uint8(0);
3089 break;
3090 case SPELL_EFFECT_CREATE_ITEM:
3091 case SPELL_EFFECT_CREATE_ITEM_2:
3092 data << uint32(m_spellInfo->EffectItemType[0]);
3093 break;
3094 case SPELL_EFFECT_SUMMON:
3095 case SPELL_EFFECT_TRANS_DOOR:
3096 case SPELL_EFFECT_SUMMON_PET:
3097 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3098 case SPELL_EFFECT_CREATE_HOUSE:
3099 case SPELL_EFFECT_DUEL:
3100 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3101 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3102 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3103 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3104 if(Unit *unit = m_targets.getUnitTarget())
3105 data.append(unit->GetPackGUID());
3106 else if(m_targets.getItemTargetGUID())
3107 data.appendPackGUID(m_targets.getItemTargetGUID());
3108 else if(GameObject *go = m_targets.getGOTarget())
3109 data.append(go->GetPackGUID());
3110 else
3111 data << uint8(0); // guid
3112 break;
3113 case SPELL_EFFECT_FEED_PET:
3114 data << uint32(m_targets.getItemTargetEntry());
3115 break;
3116 case SPELL_EFFECT_DISMISS_PET:
3117 if(Unit *unit = m_targets.getUnitTarget())
3118 data.append(unit->GetPackGUID());
3119 else
3120 data << uint8(0);
3121 break;
3122 case SPELL_EFFECT_RESURRECT:
3123 case SPELL_EFFECT_RESURRECT_NEW:
3124 if(Unit *unit = m_targets.getUnitTarget())
3125 data.append(unit->GetPackGUID());
3126 else
3127 data << uint8(0);
3128 break;
3129 default:
3130 return;
3135 m_caster->SendMessageToSet(&data, true);
3138 void Spell::SendInterrupted(uint8 result)
3140 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3141 data.append(m_caster->GetPackGUID());
3142 data << uint8(m_cast_count);
3143 data << uint32(m_spellInfo->Id);
3144 data << uint8(result);
3145 m_caster->SendMessageToSet(&data, true);
3147 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3148 data.append(m_caster->GetPackGUID());
3149 data << uint8(m_cast_count);
3150 data << uint32(m_spellInfo->Id);
3151 data << uint8(result);
3152 m_caster->SendMessageToSet(&data, true);
3155 void Spell::SendChannelUpdate(uint32 time)
3157 if(time == 0)
3159 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3160 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3163 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3164 return;
3166 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3167 data.append(m_caster->GetPackGUID());
3168 data << uint32(time);
3170 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3173 void Spell::SendChannelStart(uint32 duration)
3175 WorldObject* target = NULL;
3177 // select first not resisted target from target list for _0_ effect
3178 if(!m_UniqueTargetInfo.empty())
3180 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3182 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3184 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3185 break;
3189 else if(!m_UniqueGOTargetInfo.empty())
3191 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3193 if(itr->effectMask & (1<<0) )
3195 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3196 break;
3201 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3203 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3204 data.append(m_caster->GetPackGUID());
3205 data << uint32(m_spellInfo->Id);
3206 data << uint32(duration);
3208 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3211 m_timer = duration;
3212 if(target)
3213 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3214 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3217 void Spell::SendResurrectRequest(Player* target)
3219 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3220 // However, the packet structure differs slightly
3222 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3224 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3225 data << uint64(m_caster->GetGUID());
3226 data << uint32(strlen(sentName)+1);
3228 data << sentName;
3229 data << uint8(0);
3231 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3232 target->GetSession()->SendPacket(&data);
3235 void Spell::SendPlaySpellVisual(uint32 SpellID)
3237 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3238 return;
3240 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3241 data << uint64(m_caster->GetGUID());
3242 data << uint32(SpellID); // spell visual id?
3243 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3246 void Spell::TakeCastItem()
3248 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3249 return;
3251 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3252 if(m_IsTriggeredSpell)
3253 return;
3255 ItemPrototype const *proto = m_CastItem->GetProto();
3257 if(!proto)
3259 // This code is to avoid a crash
3260 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3261 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3262 return;
3265 bool expendable = false;
3266 bool withoutCharges = false;
3268 for (int i = 0; i<5; i++)
3270 if (proto->Spells[i].SpellId)
3272 // item has limited charges
3273 if (proto->Spells[i].SpellCharges)
3275 if (proto->Spells[i].SpellCharges < 0)
3276 expendable = true;
3278 int32 charges = m_CastItem->GetSpellCharges(i);
3280 // item has charges left
3281 if (charges)
3283 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3284 if (proto->Stackable == 1)
3285 m_CastItem->SetSpellCharges(i, charges);
3286 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3289 // all charges used
3290 withoutCharges = (charges == 0);
3295 if (expendable && withoutCharges)
3297 uint32 count = 1;
3298 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3300 // prevent crash at access to deleted m_targets.getItemTarget
3301 if(m_CastItem==m_targets.getItemTarget())
3302 m_targets.setItemTarget(NULL);
3304 m_CastItem = NULL;
3308 void Spell::TakePower()
3310 if(m_CastItem || m_triggeredByAuraSpell)
3311 return;
3313 // health as power used
3314 if(m_spellInfo->powerType == POWER_HEALTH)
3316 m_caster->ModifyHealth( -(int32)m_powerCost );
3317 return;
3320 if(m_spellInfo->powerType >= MAX_POWERS)
3322 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3323 return;
3326 Powers powerType = Powers(m_spellInfo->powerType);
3328 if(powerType == POWER_RUNE)
3330 TakeRunePower();
3331 return;
3334 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3336 // Set the five second timer
3337 if (powerType == POWER_MANA && m_powerCost > 0)
3338 m_caster->SetLastManaUse(getMSTime());
3341 uint8 Spell::CheckRuneCost(uint32 runeCostID)
3343 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3344 return 0;
3346 Player *plr = (Player*)m_caster;
3348 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3349 return 0;
3351 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3353 if(!src)
3354 return 0;
3356 if(src->NoRuneCost())
3357 return 0;
3359 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3361 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3363 runeCost[i] = src->RuneCost[i];
3366 runeCost[RUNE_DEATH] = 0; // calculated later
3368 for(uint32 i = 0; i < MAX_RUNES; ++i)
3370 uint8 rune = plr->GetCurrentRune(i);
3371 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3373 runeCost[rune]--;
3377 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3379 if(runeCost[i] > 0)
3381 runeCost[RUNE_DEATH] += runeCost[i];
3385 if(runeCost[RUNE_DEATH] > 0)
3386 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3388 return 0;
3391 void Spell::TakeRunePower()
3393 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3394 return;
3396 Player *plr = (Player*)m_caster;
3398 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3399 return;
3401 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3403 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3404 return;
3406 m_runesState = plr->GetRunesState(); // store previous state
3408 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3410 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3412 runeCost[i] = src->RuneCost[i];
3415 runeCost[RUNE_DEATH] = 0; // calculated later
3417 for(uint32 i = 0; i < MAX_RUNES; ++i)
3419 uint8 rune = plr->GetCurrentRune(i);
3420 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3422 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3423 runeCost[rune]--;
3427 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3429 if(runeCost[RUNE_DEATH] > 0)
3431 for(uint32 i = 0; i < MAX_RUNES; ++i)
3433 uint8 rune = plr->GetCurrentRune(i);
3434 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3436 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3437 runeCost[rune]--;
3438 plr->ConvertRune(i, plr->GetBaseRune(i));
3439 if(runeCost[RUNE_DEATH] == 0)
3440 break;
3445 // you can gain some runic power when use runes
3446 float rp = src->runePowerGain;;
3447 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3448 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3451 void Spell::TakeReagents()
3453 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3454 return;
3456 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3457 return;
3459 Player* p_caster = (Player*)m_caster;
3460 if (p_caster->CanNoReagentCast(m_spellInfo))
3461 return;
3463 for(uint32 x=0;x<8;x++)
3465 if(m_spellInfo->Reagent[x] <= 0)
3466 continue;
3468 uint32 itemid = m_spellInfo->Reagent[x];
3469 uint32 itemcount = m_spellInfo->ReagentCount[x];
3471 // if CastItem is also spell reagent
3472 if (m_CastItem)
3474 ItemPrototype const *proto = m_CastItem->GetProto();
3475 if( proto && proto->ItemId == itemid )
3477 for(int s=0;s<5;s++)
3479 // CastItem will be used up and does not count as reagent
3480 int32 charges = m_CastItem->GetSpellCharges(s);
3481 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3483 ++itemcount;
3484 break;
3488 m_CastItem = NULL;
3492 // if getItemTarget is also spell reagent
3493 if (m_targets.getItemTargetEntry()==itemid)
3494 m_targets.setItemTarget(NULL);
3496 p_caster->DestroyItemCount(itemid, itemcount, true);
3500 void Spell::HandleThreatSpells(uint32 spellId)
3502 if(!m_targets.getUnitTarget() || !spellId)
3503 return;
3505 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3506 return;
3508 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3509 if(!threatSpell)
3510 return;
3512 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3514 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3517 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3519 unitTarget = pUnitTarget;
3520 itemTarget = pItemTarget;
3521 gameObjTarget = pGOTarget;
3523 uint8 eff = m_spellInfo->Effect[i];
3525 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3527 sLog.outDebug( "Spell: Effect : %u", eff);
3529 if(eff<TOTAL_SPELL_EFFECTS)
3531 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3532 (*this.*SpellEffects[eff])(i);
3535 else
3537 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3538 if (m_CastItem)
3539 EffectEnchantItemTmp(i);
3540 else
3542 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3543 eff, m_spellInfo->Id);
3549 void Spell::TriggerSpell()
3551 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3553 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3554 spell->prepare(&m_targets); // use original spell original targets
3558 uint8 Spell::CanCast(bool strict)
3560 // check cooldowns to prevent cheating
3561 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3563 if(m_triggeredByAuraSpell)
3564 return SPELL_FAILED_DONT_REPORT;
3565 else
3566 return SPELL_FAILED_NOT_READY;
3569 // only allow triggered spells if at an ended battleground
3570 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3571 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3572 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3573 return SPELL_FAILED_DONT_REPORT;
3575 // only check at first call, Stealth auras are already removed at second call
3576 // for now, ignore triggered spells
3577 if( strict && !m_IsTriggeredSpell)
3579 bool checkForm = true;
3580 // Ignore form req aura
3581 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3582 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3584 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3585 continue;
3586 checkForm = false;
3587 break;
3589 if (checkForm)
3591 // Cannot be used in this stance/form
3592 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3593 return shapeError;
3595 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3596 return SPELL_FAILED_ONLY_STEALTHED;
3600 // caster state requirements
3601 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3602 return SPELL_FAILED_CASTER_AURASTATE;
3603 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3604 return SPELL_FAILED_CASTER_AURASTATE;
3606 // Caster aura req check if need
3607 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3608 return SPELL_FAILED_CASTER_AURASTATE;
3609 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3610 return SPELL_FAILED_CASTER_AURASTATE;
3612 // cancel autorepeat spells if cast start when moving
3613 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3614 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3616 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3617 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3618 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3619 return SPELL_FAILED_MOVING;
3622 Unit *target = m_targets.getUnitTarget();
3624 if(target)
3626 // target state requirements (not allowed state), apply to self also
3627 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3628 return SPELL_FAILED_TARGET_AURASTATE;
3630 // Target aura req check if need
3631 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3632 return SPELL_FAILED_CASTER_AURASTATE;
3633 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3634 return SPELL_FAILED_CASTER_AURASTATE;
3636 if(target != m_caster)
3638 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3639 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3640 return SPELL_FAILED_TARGET_AURASTATE;
3642 // Not allow casting on flying player
3643 if (target->isInFlight())
3644 return SPELL_FAILED_BAD_TARGETS;
3646 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3647 return SPELL_FAILED_LINE_OF_SIGHT;
3649 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3650 // this case can be triggered if rank not found (too low-level target for first rank)
3651 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3653 for(int i=0;i<3;i++)
3655 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3656 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3657 return SPELL_FAILED_LOWLEVEL;
3661 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3663 // Additional check for some spells
3664 // If 0 spell effect empty - client not send target data (need use selection)
3665 // TODO: check it on next client version
3666 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3667 m_spellInfo->Effect[0] == 0 && m_spellInfo->EffectImplicitTargetA[1] != TARGET_SELF)
3669 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3670 m_targets.setUnitTarget(target);
3671 else
3672 return SPELL_FAILED_BAD_TARGETS;
3676 // check pet presents
3677 for(int j=0;j<3;j++)
3679 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3681 target = m_caster->GetPet();
3682 if(!target)
3684 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3685 return SPELL_FAILED_DONT_REPORT;
3686 else
3687 return SPELL_FAILED_NO_PET;
3689 break;
3693 //check creature type
3694 //ignore self casts (including area casts when caster selected as target)
3695 if(target != m_caster)
3697 if(!CheckTargetCreatureType(target))
3699 if(target->GetTypeId()==TYPEID_PLAYER)
3700 return SPELL_FAILED_TARGET_IS_PLAYER;
3701 else
3702 return SPELL_FAILED_BAD_TARGETS;
3706 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3707 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3708 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3710 // check correctness positive/negative cast target (pet cast real check and cheating check)
3711 if(IsPositiveSpell(m_spellInfo->Id))
3713 if(m_caster->IsHostileTo(target))
3714 return SPELL_FAILED_BAD_TARGETS;
3716 else
3718 if(m_caster->IsFriendlyTo(target))
3719 return SPELL_FAILED_BAD_TARGETS;
3723 if(IsPositiveSpell(m_spellInfo->Id))
3725 if(target->IsImmunedToSpell(m_spellInfo))
3726 return SPELL_FAILED_TARGET_AURASTATE;
3729 //Must be behind the target.
3730 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3732 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3733 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3735 SendInterrupted(2);
3736 return SPELL_FAILED_NOT_BEHIND;
3740 //Target must be facing you.
3741 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3743 SendInterrupted(2);
3744 return SPELL_FAILED_NOT_INFRONT;
3747 // check if target is in combat
3748 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3750 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3753 // Spell casted only on battleground
3754 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3755 if(!((Player*)m_caster)->InBattleGround())
3756 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3758 // do not allow spells to be cast in arenas
3759 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3760 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3761 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3762 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3763 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3764 if(mapEntry->IsBattleArena())
3765 return SPELL_FAILED_NOT_IN_ARENA;
3767 // zone check
3768 if(uint8 res= GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3769 return res;
3771 // not let players cast spells at mount (and let do it to creatures)
3772 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3773 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3775 if(m_caster->isInFlight())
3776 return SPELL_FAILED_NOT_FLYING;
3777 else
3778 return SPELL_FAILED_NOT_MOUNTED;
3781 // always (except passive spells) check items (focus object can be required for any type casts)
3782 if(!IsPassiveSpell(m_spellInfo->Id))
3783 if(uint8 castResult = CheckItems())
3784 return castResult;
3786 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3787 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3789 for(uint8 j = 0; j < 3; j++)
3791 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3792 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3793 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3794 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3796 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3797 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3798 if(lower==upper)
3799 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);
3801 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3802 float range = GetSpellMaxRange(srange);
3804 Creature* creatureScriptTarget = NULL;
3805 GameObject* goScriptTarget = NULL;
3807 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3809 switch(i_spellST->second.type)
3811 case SPELL_TARGET_TYPE_GAMEOBJECT:
3813 GameObject* p_GameObject = NULL;
3815 if(i_spellST->second.targetEntry)
3817 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3818 Cell cell(p);
3819 cell.data.Part.reserved = ALL_DISTRICT;
3821 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3822 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
3824 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3825 CellLock<GridReadGuard> cell_lock(cell, p);
3826 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3828 if(p_GameObject)
3830 // remember found target and range, next attempt will find more near target with another entry
3831 creatureScriptTarget = NULL;
3832 goScriptTarget = p_GameObject;
3833 range = go_check.GetLastRange();
3836 else if( focusObject ) //Focus Object
3838 float frange = m_caster->GetDistance(focusObject);
3839 if(range >= frange)
3841 creatureScriptTarget = NULL;
3842 goScriptTarget = focusObject;
3843 range = frange;
3846 break;
3848 case SPELL_TARGET_TYPE_CREATURE:
3849 case SPELL_TARGET_TYPE_DEAD:
3850 default:
3852 Creature *p_Creature = NULL;
3854 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3855 Cell cell(p);
3856 cell.data.Part.reserved = ALL_DISTRICT;
3857 cell.SetNoCreate(); // Really don't know what is that???
3859 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3860 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
3862 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3864 CellLock<GridReadGuard> cell_lock(cell, p);
3865 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
3867 if(p_Creature )
3869 creatureScriptTarget = p_Creature;
3870 goScriptTarget = NULL;
3871 range = u_check.GetLastRange();
3873 break;
3878 if(creatureScriptTarget)
3880 // store coordinates for TARGET_SCRIPT_COORDINATES
3881 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3882 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3884 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3886 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3887 AddUnitTarget(creatureScriptTarget, j);
3889 // store explicit target for TARGET_SCRIPT
3890 else
3891 AddUnitTarget(creatureScriptTarget, j);
3893 else if(goScriptTarget)
3895 // store coordinates for TARGET_SCRIPT_COORDINATES
3896 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3897 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3899 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3901 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3902 AddGOTarget(goScriptTarget, j);
3904 // store explicit target for TARGET_SCRIPT
3905 else
3906 AddGOTarget(goScriptTarget, j);
3908 //Missing DB Entry or targets for this spellEffect.
3909 else
3911 // not report target not existence for triggered spells
3912 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3913 return SPELL_FAILED_DONT_REPORT;
3914 else
3915 return SPELL_FAILED_BAD_TARGETS;
3921 if(!m_IsTriggeredSpell)
3922 if(uint8 castResult = CheckRange(strict))
3923 return castResult;
3926 if(uint8 castResult = CheckPower())
3927 return castResult;
3930 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
3931 if(uint8 castResult = CheckCasterAuras())
3932 return castResult;
3934 for (int i = 0; i < 3; i++)
3936 // for effects of spells that have only one target
3937 switch(m_spellInfo->Effect[i])
3939 case SPELL_EFFECT_DUMMY:
3941 if(m_spellInfo->SpellIconID == 1648) // Execute
3943 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3944 return SPELL_FAILED_BAD_TARGETS;
3946 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
3948 if(m_caster->IsInWater())
3949 return SPELL_FAILED_ONLY_ABOVEWATER;
3951 else if(m_spellInfo->SpellIconID==156) // Holy Shock
3953 // spell different for friends and enemies
3954 // hart version required facing
3955 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3956 return SPELL_FAILED_UNIT_NOT_INFRONT;
3958 break;
3960 case SPELL_EFFECT_SCHOOL_DAMAGE:
3962 // Hammer of Wrath
3963 if(m_spellInfo->SpellVisual[0] == 7250)
3965 if (!m_targets.getUnitTarget())
3966 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3968 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3969 return SPELL_FAILED_BAD_TARGETS;
3971 break;
3973 case SPELL_EFFECT_TAMECREATURE:
3975 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3976 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3978 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3979 return SPELL_FAILED_HIGHLEVEL;
3981 // use SMSG_PET_TAME_FAILURE?
3982 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
3983 return SPELL_FAILED_BAD_TARGETS;
3985 if(m_caster->GetPetGUID())
3986 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3988 if(m_caster->GetCharmGUID())
3989 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3991 break;
3993 case SPELL_EFFECT_LEARN_SPELL:
3995 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
3996 break;
3998 Pet* pet = m_caster->GetPet();
4000 if(!pet)
4001 return SPELL_FAILED_NO_PET;
4003 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4005 if(!learn_spellproto)
4006 return SPELL_FAILED_NOT_KNOWN;
4008 if(m_spellInfo->spellLevel > pet->getLevel())
4009 return SPELL_FAILED_LOWLEVEL;
4011 break;
4013 case SPELL_EFFECT_LEARN_PET_SPELL:
4015 Pet* pet = m_caster->GetPet();
4017 if(!pet)
4018 return SPELL_FAILED_NO_PET;
4020 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4022 if(!learn_spellproto)
4023 return SPELL_FAILED_NOT_KNOWN;
4025 if(m_spellInfo->spellLevel > pet->getLevel())
4026 return SPELL_FAILED_LOWLEVEL;
4028 break;
4030 case SPELL_EFFECT_FEED_PET:
4032 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4033 return SPELL_FAILED_BAD_TARGETS;
4035 Item* foodItem = m_targets.getItemTarget();
4036 if(!foodItem)
4037 return SPELL_FAILED_BAD_TARGETS;
4039 Pet* pet = m_caster->GetPet();
4041 if(!pet)
4042 return SPELL_FAILED_NO_PET;
4044 if(!pet->HaveInDiet(foodItem->GetProto()))
4045 return SPELL_FAILED_WRONG_PET_FOOD;
4047 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4048 return SPELL_FAILED_FOOD_LOWLEVEL;
4050 if(m_caster->isInCombat() || pet->isInCombat())
4051 return SPELL_FAILED_AFFECTING_COMBAT;
4053 break;
4055 case SPELL_EFFECT_POWER_BURN:
4056 case SPELL_EFFECT_POWER_DRAIN:
4058 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4059 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4060 if(Unit* target = m_targets.getUnitTarget())
4061 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
4062 return SPELL_FAILED_BAD_TARGETS;
4063 break;
4065 case SPELL_EFFECT_CHARGE:
4067 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4068 return SPELL_FAILED_ROOTED;
4070 break;
4072 case SPELL_EFFECT_SKINNING:
4074 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4075 return SPELL_FAILED_BAD_TARGETS;
4077 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4078 return SPELL_FAILED_TARGET_UNSKINNABLE;
4080 Creature* creature = (Creature*)m_targets.getUnitTarget();
4081 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4083 return SPELL_FAILED_TARGET_NOT_LOOTED;
4086 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4088 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4089 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4090 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
4091 if (ReqValue > skillValue)
4092 return SPELL_FAILED_LOW_CASTLEVEL;
4094 // chance for fail at orange skinning attempt
4095 if( (m_selfContainer && (*m_selfContainer) == this) &&
4096 skillValue < sWorld.GetConfigMaxSkillValue() &&
4097 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
4098 return SPELL_FAILED_TRY_AGAIN;
4100 break;
4102 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4103 case SPELL_EFFECT_OPEN_LOCK:
4105 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4106 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4107 break;
4109 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4110 // we need a go target in case of TARGET_GAMEOBJECT
4111 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4112 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4113 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4114 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4115 return SPELL_FAILED_BAD_TARGETS;
4117 // In BattleGround players can use only flags and banners
4118 if( ((Player*)m_caster)->InBattleGround() &&
4119 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
4120 return SPELL_FAILED_TRY_AGAIN;
4122 // get the lock entry
4123 LockEntry const *lockInfo = NULL;
4124 if (GameObject* go=m_targets.getGOTarget())
4125 lockInfo = sLockStore.LookupEntry(go->GetLockId());
4126 else if(Item* itm=m_targets.getItemTarget())
4127 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
4129 // check lock compatibility
4130 if (lockInfo)
4132 // check for lock - key pair (checked by client also, just prevent cheating
4133 bool ok_key = false;
4134 for(int it = 0; it < 8; ++it)
4136 switch(lockInfo->Type[it])
4138 case LOCK_KEY_NONE:
4139 break;
4140 case LOCK_KEY_ITEM:
4142 if(lockInfo->Index[it])
4144 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4145 ok_key =true;
4146 break;
4149 case LOCK_KEY_SKILL:
4151 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->Index[it])
4152 break;
4154 switch(lockInfo->Index[it])
4156 case LOCKTYPE_HERBALISM:
4157 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
4158 ok_key =true;
4159 break;
4160 case LOCKTYPE_MINING:
4161 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
4162 ok_key =true;
4163 break;
4164 default:
4165 ok_key =true;
4166 break;
4170 if(ok_key)
4171 break;
4174 if(!ok_key)
4175 return SPELL_FAILED_BAD_TARGETS;
4178 // chance for fail at orange mining/herb/LockPicking gathering attempt
4179 if (!m_selfContainer || ((*m_selfContainer) != this))
4180 break;
4182 // get the skill value of the player
4183 int32 SkillValue = 0;
4184 bool canFailAtMax = true;
4185 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
4187 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
4188 canFailAtMax = false;
4190 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
4192 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
4193 canFailAtMax = false;
4195 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4196 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
4198 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
4199 if(m_CastItem)
4200 SkillValue = 0;
4202 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
4203 SkillValue += m_currentBasePoints[i]+1;
4205 // get the required lock value
4206 int32 ReqValue=0;
4207 if (lockInfo)
4209 // check for lock - key pair
4210 bool ok = false;
4211 for(int it = 0; it < 8; ++it)
4213 if(lockInfo->Type[it]==LOCK_KEY_ITEM && lockInfo->Index[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4215 // if so, we're good to go
4216 ok = true;
4217 break;
4220 if(ok)
4221 break;
4223 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4224 ReqValue = lockInfo->Skill[1];
4225 else
4226 ReqValue = lockInfo->Skill[0];
4229 // skill doesn't meet the required value
4230 if (ReqValue > SkillValue)
4231 return SPELL_FAILED_LOW_CASTLEVEL;
4233 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4234 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
4235 return SPELL_FAILED_TRY_AGAIN;
4237 break;
4239 case SPELL_EFFECT_SUMMON_DEAD_PET:
4241 Creature *pet = m_caster->GetPet();
4242 if(!pet)
4243 return SPELL_FAILED_NO_PET;
4245 if(pet->isAlive())
4246 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4248 break;
4250 // This is generic summon effect
4251 case SPELL_EFFECT_SUMMON:
4253 switch(m_spellInfo->EffectMiscValueB[i])
4255 case SUMMON_TYPE_POSESSED:
4256 case SUMMON_TYPE_POSESSED2:
4257 case SUMMON_TYPE_DEMON:
4258 case SUMMON_TYPE_SUMMON:
4260 if(m_caster->GetPetGUID())
4261 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4263 if(m_caster->GetCharmGUID())
4264 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4265 break;
4268 break;
4270 // Not used for summon?
4271 case SPELL_EFFECT_SUMMON_PHANTASM:
4273 if(m_caster->GetPetGUID())
4274 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4276 if(m_caster->GetCharmGUID())
4277 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4279 break;
4281 case SPELL_EFFECT_SUMMON_PET:
4283 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4286 Pet* pet = ((Player*)m_caster)->GetPet();
4288 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4290 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4291 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4293 else
4294 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4297 if(m_caster->GetCharmGUID())
4298 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4300 break;
4302 case SPELL_EFFECT_SUMMON_PLAYER:
4304 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4305 return SPELL_FAILED_BAD_TARGETS;
4306 if(!((Player*)m_caster)->GetSelection())
4307 return SPELL_FAILED_BAD_TARGETS;
4309 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4310 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4311 return SPELL_FAILED_BAD_TARGETS;
4313 // check if our map is dungeon
4314 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4316 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4317 if(!instance)
4318 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4319 if ( instance->levelMin > target->getLevel() )
4320 return SPELL_FAILED_LOWLEVEL;
4321 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4322 return SPELL_FAILED_HIGHLEVEL;
4324 break;
4326 case SPELL_EFFECT_LEAP:
4327 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4329 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4330 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4331 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4332 // teleport a bit above terrain level to avoid falling below it
4333 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4334 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4335 return SPELL_FAILED_TRY_AGAIN;
4337 float caster_pos_z = m_caster->GetPositionZ();
4338 // Control the caster to not climb or drop when +-fz > 8
4339 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4340 return SPELL_FAILED_TRY_AGAIN;
4342 // not allow use this effect at battleground until battleground start
4343 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4344 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4345 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4346 return SPELL_FAILED_TRY_AGAIN;
4347 break;
4349 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4351 if (m_targets.getUnitTarget()==m_caster)
4352 return SPELL_FAILED_BAD_TARGETS;
4353 break;
4355 default:break;
4359 for (int i = 0; i < 3; i++)
4361 switch(m_spellInfo->EffectApplyAuraName[i])
4363 case SPELL_AURA_MOD_POSSESS:
4364 case SPELL_AURA_MOD_CHARM:
4366 if(m_caster->GetPetGUID())
4367 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4369 if(m_caster->GetCharmGUID())
4370 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4372 if(m_caster->GetCharmerGUID())
4373 return SPELL_FAILED_CHARMED;
4375 if(!m_targets.getUnitTarget())
4376 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4378 if(m_targets.getUnitTarget()->GetCharmerGUID())
4379 return SPELL_FAILED_CHARMED;
4381 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4382 return SPELL_FAILED_HIGHLEVEL;
4384 break;
4386 case SPELL_AURA_MOUNTED:
4388 if (m_caster->IsInWater())
4389 return SPELL_FAILED_ONLY_ABOVEWATER;
4391 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4392 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4394 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4395 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4396 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4398 ShapeshiftForm form = m_caster->m_form;
4399 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4400 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4401 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4402 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4403 return SPELL_FAILED_NOT_SHAPESHIFT;
4405 break;
4407 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4409 if(!m_targets.getUnitTarget())
4410 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4412 // can be casted at non-friendly unit or own pet/charm
4413 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4414 return SPELL_FAILED_TARGET_FRIENDLY;
4416 break;
4418 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4419 case SPELL_AURA_FLY:
4421 // not allow cast fly spells at old maps by players (all spells is self target)
4422 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4424 uint32 v_map = GetVirtualMapForMapAndZone(m_caster->GetMapId(), m_caster->GetZoneId());
4425 if( !((Player*)m_caster)->isGameMaster() && v_map != 530 && !(v_map == 571 && ((Player*)m_caster)->HasSpell(54197)))
4426 return SPELL_FAILED_NOT_HERE;
4429 break;
4431 case SPELL_AURA_PERIODIC_MANA_LEECH:
4433 if (!m_targets.getUnitTarget())
4434 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4436 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4437 break;
4439 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4440 return SPELL_FAILED_BAD_TARGETS;
4442 break;
4444 default:
4445 break;
4449 // all ok
4450 return 0;
4453 int16 Spell::PetCanCast(Unit* target)
4455 if(!m_caster->isAlive())
4456 return SPELL_FAILED_CASTER_DEAD;
4458 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4459 return SPELL_FAILED_SPELL_IN_PROGRESS;
4460 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4461 return SPELL_FAILED_AFFECTING_COMBAT;
4463 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4465 //dead owner (pets still alive when owners ressed?)
4466 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4467 return SPELL_FAILED_CASTER_DEAD;
4469 if(!target && m_targets.getUnitTarget())
4470 target = m_targets.getUnitTarget();
4472 bool need = false;
4473 for(uint32 i = 0;i<3;i++)
4475 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)
4477 need = true;
4478 if(!target)
4479 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4480 break;
4483 if(need)
4484 m_targets.setUnitTarget(target);
4486 Unit* _target = m_targets.getUnitTarget();
4488 if(_target) //for target dead/target not valid
4490 if(!_target->isAlive())
4491 return SPELL_FAILED_BAD_TARGETS;
4493 if(IsPositiveSpell(m_spellInfo->Id))
4495 if(m_caster->IsHostileTo(_target))
4496 return SPELL_FAILED_BAD_TARGETS;
4498 else
4500 bool duelvsplayertar = false;
4501 for(int j=0;j<3;j++)
4503 //TARGET_DUELVSPLAYER is positive AND negative
4504 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4506 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4508 return SPELL_FAILED_BAD_TARGETS;
4512 //cooldown
4513 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4514 return SPELL_FAILED_NOT_READY;
4517 uint16 result = CanCast(true);
4518 if(result != 0)
4519 return result;
4520 else
4521 return -1; //this allows to check spell fail 0, in combat
4524 uint8 Spell::CheckCasterAuras() const
4526 // Flag drop spells totally immuned to caster auras
4527 // FIXME: find more nice check for all totally immuned spells
4528 // AttributesEx3 & 0x10000000?
4529 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4530 return 0;
4532 uint8 school_immune = 0;
4533 uint32 mechanic_immune = 0;
4534 uint32 dispel_immune = 0;
4536 //Check if the spell grants school or mechanic immunity.
4537 //We use bitmasks so the loop is done only once and not on every aura check below.
4538 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4540 for(int i = 0;i < 3; i ++)
4542 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4543 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4544 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4545 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4546 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4547 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4549 //immune movement impairment and loss of control
4550 if(m_spellInfo->Id==(uint32)42292)
4551 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4554 //Check whether the cast should be prevented by any state you might have.
4555 uint8 prevented_reason = 0;
4556 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4557 if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4558 prevented_reason = SPELL_FAILED_STUNNED;
4559 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4560 prevented_reason = SPELL_FAILED_CONFUSED;
4561 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4562 prevented_reason = SPELL_FAILED_FLEEING;
4563 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4564 prevented_reason = SPELL_FAILED_SILENCED;
4565 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4566 prevented_reason = SPELL_FAILED_PACIFIED;
4568 // Attr must make flag drop spell totally immune from all effects
4569 if(prevented_reason)
4571 if(school_immune || mechanic_immune || dispel_immune)
4573 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4574 Unit::AuraMap const& auras = m_caster->GetAuras();
4575 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4577 if(itr->second)
4579 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4580 continue;
4581 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4582 continue;
4583 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4584 continue;
4586 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4587 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4588 switch(itr->second->GetModifier()->m_auraname)
4590 case SPELL_AURA_MOD_STUN:
4591 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4592 return SPELL_FAILED_STUNNED;
4593 break;
4594 case SPELL_AURA_MOD_CONFUSE:
4595 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4596 return SPELL_FAILED_CONFUSED;
4597 break;
4598 case SPELL_AURA_MOD_FEAR:
4599 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4600 return SPELL_FAILED_FLEEING;
4601 break;
4602 case SPELL_AURA_MOD_SILENCE:
4603 case SPELL_AURA_MOD_PACIFY:
4604 case SPELL_AURA_MOD_PACIFY_SILENCE:
4605 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4606 return SPELL_FAILED_PACIFIED;
4607 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4608 return SPELL_FAILED_SILENCED;
4609 break;
4614 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4615 else
4616 return prevented_reason;
4618 return 0; // all ok
4621 bool Spell::CanAutoCast(Unit* target)
4623 uint64 targetguid = target->GetGUID();
4625 for(uint32 j = 0;j<3;j++)
4627 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4629 if( m_spellInfo->StackAmount <= 1)
4631 if( target->HasAura(m_spellInfo->Id, j) )
4632 return false;
4634 else
4636 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4637 return false;
4640 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4642 if( target->HasAura(m_spellInfo->Id, j) )
4643 return false;
4647 int16 result = PetCanCast(target);
4649 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4651 FillTargetMap();
4652 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4653 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4654 if( ihit->targetGUID == targetguid )
4655 return true;
4657 return false; //target invalid
4660 uint8 Spell::CheckRange(bool strict)
4662 float range_mod;
4664 // self cast doesn't need range checking -- also for Starshards fix
4665 if (m_spellInfo->rangeIndex == 1) return 0;
4667 if (strict) //add radius of caster
4668 range_mod = 1.25;
4669 else //add radius of caster and ~5 yds "give"
4670 range_mod = 6.25;
4672 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4673 float max_range = GetSpellMaxRange(srange) + range_mod;
4674 float min_range = GetSpellMinRange(srange);
4676 if(Player* modOwner = m_caster->GetSpellModOwner())
4677 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4679 Unit *target = m_targets.getUnitTarget();
4681 if(target && target != m_caster)
4683 // distance from target center in checks
4684 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4685 if(dist > max_range)
4686 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4687 if(dist < min_range)
4688 return SPELL_FAILED_TOO_CLOSE;
4689 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4690 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4691 return SPELL_FAILED_UNIT_NOT_INFRONT;
4694 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4696 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4697 if(dist > max_range)
4698 return SPELL_FAILED_OUT_OF_RANGE;
4699 if(dist < min_range)
4700 return SPELL_FAILED_TOO_CLOSE;
4703 return 0; // ok
4706 int32 Spell::CalculatePowerCost()
4708 // item cast not used power
4709 if(m_CastItem)
4710 return 0;
4712 // Spell drain all exist power on cast (Only paladin lay of Hands)
4713 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4715 // If power type - health drain all
4716 if (m_spellInfo->powerType == POWER_HEALTH)
4717 return m_caster->GetHealth();
4718 // Else drain all power
4719 if (m_spellInfo->powerType < MAX_POWERS)
4720 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4721 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4722 return 0;
4725 // Base powerCost
4726 int32 powerCost = m_spellInfo->manaCost;
4727 // PCT cost from total amount
4728 if (m_spellInfo->ManaCostPercentage)
4730 switch (m_spellInfo->powerType)
4732 // health as power used
4733 case POWER_HEALTH:
4734 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4735 break;
4736 case POWER_MANA:
4737 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4738 break;
4739 case POWER_RAGE:
4740 case POWER_FOCUS:
4741 case POWER_ENERGY:
4742 case POWER_HAPPINESS:
4743 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4744 break;
4745 case POWER_RUNE:
4746 case POWER_RUNIC_POWER:
4747 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4748 break;
4749 default:
4750 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4751 return 0;
4754 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4755 // Flat mod from caster auras by spell school
4756 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4757 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4758 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4759 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4760 // Apply cost mod by spell
4761 if(Player* modOwner = m_caster->GetSpellModOwner())
4762 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4764 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4765 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4767 // PCT mod from user auras by school
4768 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4769 if (powerCost < 0)
4770 powerCost = 0;
4771 return powerCost;
4774 uint8 Spell::CheckPower()
4776 // item cast not used power
4777 if(m_CastItem)
4778 return 0;
4780 // health as power used - need check health amount
4781 if(m_spellInfo->powerType == POWER_HEALTH)
4783 if(m_caster->GetHealth() <= m_powerCost)
4784 return SPELL_FAILED_CASTER_AURASTATE;
4785 return 0;
4787 // Check valid power type
4788 if( m_spellInfo->powerType >= MAX_POWERS )
4790 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4791 return SPELL_FAILED_UNKNOWN;
4794 uint8 failReason = CheckRuneCost(m_spellInfo->runeCostID);
4795 if(failReason)
4796 return failReason;
4798 // Check power amount
4799 Powers powerType = Powers(m_spellInfo->powerType);
4800 if(m_caster->GetPower(powerType) < m_powerCost)
4801 return SPELL_FAILED_NO_POWER;
4802 else
4803 return 0;
4806 uint8 Spell::CheckItems()
4808 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4809 return 0;
4811 uint32 itemid, itemcount;
4812 Player* p_caster = (Player*)m_caster;
4814 if(m_CastItem)
4816 itemid = m_CastItem->GetEntry();
4817 if( !p_caster->HasItemCount(itemid,1) )
4818 return SPELL_FAILED_ITEM_NOT_READY;
4819 else
4821 ItemPrototype const *proto = m_CastItem->GetProto();
4822 if(!proto)
4823 return SPELL_FAILED_ITEM_NOT_READY;
4825 for (int i = 0; i<5; i++)
4827 if (proto->Spells[i].SpellCharges)
4829 if(m_CastItem->GetSpellCharges(i)==0)
4830 return SPELL_FAILED_NO_CHARGES_REMAIN;
4834 uint32 ItemClass = proto->Class;
4835 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4837 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4838 uint8 failReason = 0;
4839 for (int i = 0; i < 3; i++)
4841 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4842 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4843 continue;
4845 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4847 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4849 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4850 continue;
4852 else
4854 failReason = 0;
4855 break;
4859 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4860 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4862 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4864 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4865 continue;
4868 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4869 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4871 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4872 continue;
4874 else
4876 failReason = 0;
4877 break;
4881 if (failReason)
4882 return failReason;
4887 if(m_targets.getItemTargetGUID())
4889 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4890 return SPELL_FAILED_BAD_TARGETS;
4892 if(!m_targets.getItemTarget())
4893 return SPELL_FAILED_ITEM_GONE;
4895 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4896 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4898 // if not item target then required item must be equipped
4899 else
4901 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4902 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4905 if(m_spellInfo->RequiresSpellFocus)
4907 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4908 Cell cell(p);
4909 cell.data.Part.reserved = ALL_DISTRICT;
4911 GameObject* ok = NULL;
4912 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4913 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(ok,go_check);
4915 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4916 CellLock<GridReadGuard> cell_lock(cell, p);
4917 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4919 if(!ok)
4920 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4922 focusObject = ok; // game object found in range
4925 if (!p_caster->CanNoReagentCast(m_spellInfo))
4927 for(uint32 i=0;i<8;i++)
4929 if(m_spellInfo->Reagent[i] <= 0)
4930 continue;
4932 itemid = m_spellInfo->Reagent[i];
4933 itemcount = m_spellInfo->ReagentCount[i];
4935 // if CastItem is also spell reagent
4936 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4938 ItemPrototype const *proto = m_CastItem->GetProto();
4939 if(!proto)
4940 return SPELL_FAILED_ITEM_NOT_READY;
4941 for(int s=0;s<5;s++)
4943 // CastItem will be used up and does not count as reagent
4944 int32 charges = m_CastItem->GetSpellCharges(s);
4945 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4947 ++itemcount;
4948 break;
4952 if( !p_caster->HasItemCount(itemid,itemcount) )
4953 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
4957 uint32 totems = 2;
4958 for(int i=0;i<2;++i)
4960 if(m_spellInfo->Totem[i] != 0)
4962 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4964 totems -= 1;
4965 continue;
4967 }else
4968 totems -= 1;
4970 if(totems != 0)
4971 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
4973 //Check items for TotemCategory
4974 uint32 TotemCategory = 2;
4975 for(int i=0;i<2;++i)
4977 if(m_spellInfo->TotemCategory[i] != 0)
4979 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4981 TotemCategory -= 1;
4982 continue;
4985 else
4986 TotemCategory -= 1;
4988 if(TotemCategory != 0)
4989 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
4991 for(int i = 0; i < 3; i++)
4993 switch (m_spellInfo->Effect[i])
4995 case SPELL_EFFECT_CREATE_ITEM:
4997 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4999 ItemPosCountVec dest;
5000 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
5001 if (msg != EQUIP_ERR_OK )
5003 p_caster->SendEquipError( msg, NULL, NULL );
5004 return SPELL_FAILED_DONT_REPORT;
5007 break;
5009 case SPELL_EFFECT_ENCHANT_ITEM:
5011 Item* targetItem = m_targets.getItemTarget();
5012 if(!targetItem)
5013 return SPELL_FAILED_ITEM_NOT_FOUND;
5015 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5016 return SPELL_FAILED_LOWLEVEL;
5017 // Not allow enchant in trade slot for some enchant type
5018 if( targetItem->GetOwner() != m_caster )
5020 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5021 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5022 if(!pEnchant)
5023 return SPELL_FAILED_ERROR;
5024 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5025 return SPELL_FAILED_NOT_TRADEABLE;
5027 break;
5029 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5031 Item *item = m_targets.getItemTarget();
5032 if(!item)
5033 return SPELL_FAILED_ITEM_NOT_FOUND;
5034 // Not allow enchant in trade slot for some enchant type
5035 if( item->GetOwner() != m_caster )
5037 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5038 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5039 if(!pEnchant)
5040 return SPELL_FAILED_ERROR;
5041 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5042 return SPELL_FAILED_NOT_TRADEABLE;
5044 break;
5046 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5047 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5048 break;
5049 case SPELL_EFFECT_DISENCHANT:
5051 if(!m_targets.getItemTarget())
5052 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5054 // prevent disenchanting in trade slot
5055 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5056 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5058 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5059 if(!itemProto)
5060 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5062 uint32 item_quality = itemProto->Quality;
5063 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5064 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5065 if (item_disenchantskilllevel == uint32(-1))
5066 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5067 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5068 return SPELL_FAILED_LOW_CASTLEVEL;
5069 if(item_quality > 4 || item_quality < 2)
5070 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5071 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5072 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5073 if (!itemProto->DisenchantID)
5074 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5075 break;
5077 case SPELL_EFFECT_PROSPECTING:
5079 if(!m_targets.getItemTarget())
5080 return SPELL_FAILED_CANT_BE_PROSPECTED;
5081 //ensure item is a prospectable ore
5082 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5083 return SPELL_FAILED_CANT_BE_PROSPECTED;
5084 //prevent prospecting in trade slot
5085 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5086 return SPELL_FAILED_CANT_BE_PROSPECTED;
5087 //Check for enough skill in jewelcrafting
5088 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5089 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5090 return SPELL_FAILED_LOW_CASTLEVEL;
5091 //make sure the player has the required ores in inventory
5092 if(m_targets.getItemTarget()->GetCount() < 5)
5093 return SPELL_FAILED_NEED_MORE_ITEMS;
5095 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5096 return SPELL_FAILED_CANT_BE_PROSPECTED;
5098 break;
5100 case SPELL_EFFECT_MILLING:
5102 if(!m_targets.getItemTarget())
5103 return SPELL_FAILED_CANT_BE_MILLED;
5104 //ensure item is a millable herb
5105 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5106 return SPELL_FAILED_CANT_BE_MILLED;
5107 //prevent milling in trade slot
5108 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5109 return SPELL_FAILED_CANT_BE_MILLED;
5110 //Check for enough skill in inscription
5111 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5112 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5113 return SPELL_FAILED_LOW_CASTLEVEL;
5114 //make sure the player has the required herbs in inventory
5115 if(m_targets.getItemTarget()->GetCount() < 5)
5116 return SPELL_FAILED_NEED_MORE_ITEMS;
5118 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5119 return SPELL_FAILED_CANT_BE_MILLED;
5121 break;
5123 case SPELL_EFFECT_WEAPON_DAMAGE:
5124 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5126 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5127 if( m_attackType != RANGED_ATTACK )
5128 break;
5129 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5130 if(!pItem || pItem->IsBroken())
5131 return SPELL_FAILED_EQUIPPED_ITEM;
5133 switch(pItem->GetProto()->SubClass)
5135 case ITEM_SUBCLASS_WEAPON_THROWN:
5137 uint32 ammo = pItem->GetEntry();
5138 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5139 return SPELL_FAILED_NO_AMMO;
5140 }; break;
5141 case ITEM_SUBCLASS_WEAPON_GUN:
5142 case ITEM_SUBCLASS_WEAPON_BOW:
5143 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5145 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5146 if(!ammo)
5148 // Requires No Ammo
5149 if(m_caster->GetDummyAura(46699))
5150 break; // skip other checks
5152 return SPELL_FAILED_NO_AMMO;
5155 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5156 if(!ammoProto)
5157 return SPELL_FAILED_NO_AMMO;
5159 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5160 return SPELL_FAILED_NO_AMMO;
5162 // check ammo ws. weapon compatibility
5163 switch(pItem->GetProto()->SubClass)
5165 case ITEM_SUBCLASS_WEAPON_BOW:
5166 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5167 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5168 return SPELL_FAILED_NO_AMMO;
5169 break;
5170 case ITEM_SUBCLASS_WEAPON_GUN:
5171 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5172 return SPELL_FAILED_NO_AMMO;
5173 break;
5174 default:
5175 return SPELL_FAILED_NO_AMMO;
5178 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5179 return SPELL_FAILED_NO_AMMO;
5180 }; break;
5181 case ITEM_SUBCLASS_WEAPON_WAND:
5182 default:
5183 break;
5185 break;
5187 default:break;
5191 return uint8(0);
5194 void Spell::Delayed()
5196 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5197 return;
5199 if (m_spellState == SPELL_STATE_DELAYED)
5200 return; // spell is active and can't be time-backed
5202 // spells not loosing casting time ( slam, dynamites, bombs.. )
5203 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5204 return;
5206 //check resist chance
5207 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5208 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5209 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5210 if (roll_chance_i(resistChance))
5211 return;
5213 int32 delaytime = GetNextDelayAtDamageMsTime();
5215 if(int32(m_timer) + delaytime > m_casttime)
5217 delaytime = m_casttime - m_timer;
5218 m_timer = m_casttime;
5220 else
5221 m_timer += delaytime;
5223 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5225 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5226 data.append(m_caster->GetPackGUID());
5227 data << uint32(delaytime);
5229 m_caster->SendMessageToSet(&data,true);
5232 void Spell::DelayedChannel()
5234 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5235 return;
5237 //check resist chance
5238 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5239 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5240 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5241 if (roll_chance_i(resistChance))
5242 return;
5244 int32 delaytime = GetNextDelayAtDamageMsTime();
5246 if(int32(m_timer) < delaytime)
5248 delaytime = m_timer;
5249 m_timer = 0;
5251 else
5252 m_timer -= delaytime;
5254 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5256 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5258 if ((*ihit).missCondition == SPELL_MISS_NONE)
5260 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5261 if (unit)
5263 for (int j=0;j<3;j++)
5264 if( ihit->effectMask & (1<<j) )
5265 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5271 for(int j = 0; j < 3; j++)
5273 // partially interrupt persistent area auras
5274 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5275 if(dynObj)
5276 dynObj->Delay(delaytime);
5279 SendChannelUpdate(m_timer);
5282 void Spell::UpdatePointers()
5284 if(m_originalCasterGUID==m_caster->GetGUID())
5285 m_originalCaster = m_caster;
5286 else
5288 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5289 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5292 m_targets.Update(m_caster);
5295 bool Spell::IsAffectedByAura(Aura *aura)
5297 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5300 bool Spell::CheckTargetCreatureType(Unit* target) const
5302 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5304 // Curse of Doom : not find another way to fix spell target check :/
5305 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5307 // not allow cast at player
5308 if(target->GetTypeId()==TYPEID_PLAYER)
5309 return false;
5311 spellCreatureTargetMask = 0x7FF;
5314 // Dismiss Pet and Taming Lesson skipped
5315 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5316 spellCreatureTargetMask = 0;
5318 if (spellCreatureTargetMask)
5320 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5322 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5324 return true;
5327 CurrentSpellTypes Spell::GetCurrentContainer()
5329 if (IsNextMeleeSwingSpell())
5330 return(CURRENT_MELEE_SPELL);
5331 else if (IsAutoRepeat())
5332 return(CURRENT_AUTOREPEAT_SPELL);
5333 else if (IsChanneledSpell(m_spellInfo))
5334 return(CURRENT_CHANNELED_SPELL);
5335 else
5336 return(CURRENT_GENERIC_SPELL);
5339 bool Spell::CheckTarget( Unit* target, uint32 eff )
5341 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5342 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5344 if (!CheckTargetCreatureType(target))
5345 return false;
5348 // Check Aura spell req (need for AoE spells)
5349 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5350 return false;
5351 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5352 return false;
5354 // Check targets for not_selectable unit flag and remove
5355 // A player can cast spells on his pet (or other controlled unit) though in any state
5356 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5358 // any unattackable target skipped
5359 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5360 return false;
5362 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5363 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5364 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5365 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5366 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5367 return false;
5370 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5371 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5373 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5374 return false;
5376 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5377 return false;
5380 //Check targets for LOS visibility (except spells without range limitations )
5381 switch(m_spellInfo->Effect[eff])
5383 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5384 break;
5385 case SPELL_EFFECT_DUMMY:
5386 if(m_spellInfo->Id!=20577) // Cannibalize
5387 break;
5388 //fall through
5389 case SPELL_EFFECT_RESURRECT_NEW:
5390 // player far away, maybe his corpse near?
5391 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5393 if(!m_targets.getCorpseTargetGUID())
5394 return false;
5396 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5397 if(!corpse)
5398 return false;
5400 if(target->GetGUID()!=corpse->GetOwnerGUID())
5401 return false;
5403 if(!corpse->IsWithinLOSInMap(m_caster))
5404 return false;
5407 // all ok by some way or another, skip normal check
5408 break;
5409 default: // normal case
5410 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5411 return false;
5412 break;
5415 return true;
5418 Unit* Spell::SelectMagnetTarget()
5420 Unit* target = m_targets.getUnitTarget();
5422 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
5424 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
5425 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
5427 if(Unit* magnet = (*itr)->GetCaster())
5429 if(magnet->IsWithinLOSInMap(m_caster))
5431 target = magnet;
5432 m_targets.setUnitTarget(target);
5433 break;
5439 return target;
5442 bool Spell::IsNeedSendToClient() const
5444 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5445 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5448 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5450 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5451 if(itr->effectMask & (1<<effect))
5452 return true;
5454 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5455 if(itr->effectMask & (1<<effect))
5456 return true;
5458 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5459 if(itr->effectMask & (1<<effect))
5460 return true;
5462 return false;
5465 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5467 m_Spell = spell;
5470 SpellEvent::~SpellEvent()
5472 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5473 m_Spell->cancel();
5475 if (m_Spell->IsDeletable())
5477 delete m_Spell;
5479 else
5481 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5482 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5486 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5488 // update spell if it is not finished
5489 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5490 m_Spell->update(p_time);
5492 // check spell state to process
5493 switch (m_Spell->getState())
5495 case SPELL_STATE_FINISHED:
5497 // spell was finished, check deletable state
5498 if (m_Spell->IsDeletable())
5500 // check, if we do have unfinished triggered spells
5502 return(true); // spell is deletable, finish event
5504 // event will be re-added automatically at the end of routine)
5505 } break;
5507 case SPELL_STATE_CASTING:
5509 // this spell is in channeled state, process it on the next update
5510 // event will be re-added automatically at the end of routine)
5511 } break;
5513 case SPELL_STATE_DELAYED:
5515 // first, check, if we have just started
5516 if (m_Spell->GetDelayStart() != 0)
5518 // no, we aren't, do the typical update
5519 // check, if we have channeled spell on our hands
5520 if (IsChanneledSpell(m_Spell->m_spellInfo))
5522 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5523 // check, if we have casting anything else except this channeled spell and autorepeat
5524 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5526 // another non-melee non-delayed spell is casted now, abort
5527 m_Spell->cancel();
5529 else
5531 // do the action (pass spell to channeling state)
5532 m_Spell->handle_immediate();
5534 // event will be re-added automatically at the end of routine)
5536 else
5538 // run the spell handler and think about what we can do next
5539 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5540 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5541 if (n_offset)
5543 // re-add us to the queue
5544 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5545 return(false); // event not complete
5547 // event complete
5548 // finish update event will be re-added automatically at the end of routine)
5551 else
5553 // delaying had just started, record the moment
5554 m_Spell->SetDelayStart(e_time);
5555 // re-plan the event for the delay moment
5556 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5557 return(false); // event not complete
5559 } break;
5561 default:
5563 // all other states
5564 // event will be re-added automatically at the end of routine)
5565 } break;
5568 // spell processing not complete, plan event on the next update interval
5569 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5570 return(false); // event not complete
5573 void SpellEvent::Abort(uint64 /*e_time*/)
5575 // oops, the spell we try to do is aborted
5576 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5577 m_Spell->cancel();
5580 bool SpellEvent::IsDeletable() const
5582 return m_Spell->IsDeletable();