[6997] Fixed: In 3.0.3 spell data have area group id instead area id.
[getmangos.git] / src / game / Spell.cpp
blob0e6380c4985ad4641be1e28908cfdb7ec349f9d6
1 /*
2 * Copyright (C) 2005-2008 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 | TARGET_FLAG_OBJECT_UNK ))
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_SOURCE_LOCATION )
182 if(data->rpos()+4+4+4 > data->size())
183 return false;
185 *data >> m_srcX >> m_srcY >> m_srcZ;
186 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
187 return false;
190 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
192 if(data->rpos()+4+4+4 > data->size())
193 return false;
195 *data >> m_destX >> m_destY >> m_destZ;
196 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
197 return false;
200 if( m_targetMask & TARGET_FLAG_STRING )
202 if(data->rpos()+1 > data->size())
203 return false;
205 *data >> m_strTarget;
208 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
209 if(!data->readPackGUID(m_CorpseTargetGUID))
210 return false;
212 // find real units/GOs
213 Update(caster);
214 return true;
217 void SpellCastTargets::write ( WorldPacket * data )
219 *data << uint32(m_targetMask);
221 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
223 if(m_targetMask & TARGET_FLAG_UNIT)
225 if(m_unitTarget)
226 data->append(m_unitTarget->GetPackGUID());
227 else
228 *data << uint8(0);
230 else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
232 if(m_GOTarget)
233 data->append(m_GOTarget->GetPackGUID());
234 else
235 *data << uint8(0);
237 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
238 data->appendPackGUID(m_CorpseTargetGUID);
239 else
240 *data << uint8(0);
243 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
245 if(m_itemTarget)
246 data->append(m_itemTarget->GetPackGUID());
247 else
248 *data << uint8(0);
251 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
252 *data << m_srcX << m_srcY << m_srcZ;
254 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
255 *data << m_destX << m_destY << m_destZ;
257 if( m_targetMask & TARGET_FLAG_STRING )
258 *data << m_strTarget;
261 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
263 ASSERT( Caster != NULL && info != NULL );
264 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
266 m_spellInfo = info;
267 m_caster = Caster;
268 m_selfContainer = NULL;
269 m_triggeringContainer = triggeringContainer;
270 m_referencedFromCurrentSpell = false;
271 m_executedCurrently = false;
272 m_delayStart = 0;
273 m_delayAtDamageCount = 0;
275 m_applyMultiplierMask = 0;
277 // Get data for type of attack
278 switch (m_spellInfo->DmgClass)
280 case SPELL_DAMAGE_CLASS_MELEE:
281 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
282 m_attackType = OFF_ATTACK;
283 else
284 m_attackType = BASE_ATTACK;
285 break;
286 case SPELL_DAMAGE_CLASS_RANGED:
287 m_attackType = RANGED_ATTACK;
288 break;
289 default:
290 // Wands
291 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_WAND)
292 m_attackType = RANGED_ATTACK;
293 else
294 m_attackType = BASE_ATTACK;
295 break;
298 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
300 if(m_attackType == RANGED_ATTACK)
302 // wand case
303 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
305 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
306 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
309 // Set health leech amount to zero
310 m_healthLeech = 0;
312 if(originalCasterGUID)
313 m_originalCasterGUID = originalCasterGUID;
314 else
315 m_originalCasterGUID = m_caster->GetGUID();
317 if(m_originalCasterGUID==m_caster->GetGUID())
318 m_originalCaster = m_caster;
319 else
321 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
322 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
325 for(int i=0; i <3; ++i)
326 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
328 m_spellState = SPELL_STATE_NULL;
330 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
331 m_TriggerSpells.clear();
332 m_IsTriggeredSpell = triggered;
333 //m_AreaAura = false;
334 m_CastItem = NULL;
336 unitTarget = NULL;
337 itemTarget = NULL;
338 gameObjTarget = NULL;
339 focusObject = NULL;
340 m_cast_count = 0;
341 m_glyphIndex = 0;
342 m_triggeredByAuraSpell = NULL;
344 //Auto Shot & Shoot (wand)
345 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
347 m_runesState = 0;
348 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
349 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
350 m_timer = 0; // will set to castime in prepare
352 m_needAliveTargetMask = 0;
354 // determine reflection
355 m_canReflect = false;
357 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
359 for(int j=0;j<3;j++)
361 if (m_spellInfo->Effect[j]==0)
362 continue;
364 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
365 m_canReflect = true;
366 else
367 m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
369 if(m_canReflect)
370 continue;
371 else
372 break;
376 CleanupTargetList();
379 Spell::~Spell()
383 void Spell::FillTargetMap()
385 // TODO: ADD the correct target FILLS!!!!!!
387 for(uint32 i=0;i<3;i++)
389 // not call for empty effect.
390 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
391 if(m_spellInfo->Effect[i]==0)
392 continue;
394 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
395 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
396 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
397 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
398 continue;
400 // TODO: find a way so this is not needed?
401 // for area auras always add caster as target (needed for totems for example)
402 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
403 AddUnitTarget(m_caster, i);
405 std::list<Unit*> tmpUnitMap;
407 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
408 // but need it support in some know cases
409 switch(m_spellInfo->EffectImplicitTargetA[i])
411 case TARGET_ALL_AROUND_CASTER:
412 if( m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_PARTY ||
413 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER ||
414 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_RAID_AROUND_CASTER )
416 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
418 // Note: this hack with search required until GO casting not implemented
419 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
420 // currently each enemy selected explicitly and self cast damage
421 else if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
423 if(m_targets.getUnitTarget())
424 tmpUnitMap.push_back(m_targets.getUnitTarget());
426 else
428 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
429 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
431 break;
432 case TARGET_TABLE_X_Y_Z_COORDINATES:
433 // Only if target A, for target B (used in teleports) dest select in effect
434 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
435 break;
436 default:
437 switch(m_spellInfo->EffectImplicitTargetB[i])
439 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
440 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
441 break;
442 default:
443 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
444 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
445 break;
447 break;
450 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
451 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
453 // add here custom effects that need default target.
454 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
455 switch(m_spellInfo->Effect[i])
457 case SPELL_EFFECT_DUMMY:
459 switch(m_spellInfo->Id)
461 case 20577: // Cannibalize
463 // non-standard target selection
464 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
465 float max_range = GetSpellMaxRange(srange);
467 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
468 Cell cell(p);
469 cell.data.Part.reserved = ALL_DISTRICT;
470 cell.SetNoCreate();
472 WorldObject* result = NULL;
474 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
475 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(result, u_check);
477 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
478 CellLock<GridReadGuard> cell_lock(cell, p);
479 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
481 if(!result)
483 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
484 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
487 if(result)
489 switch(result->GetTypeId())
491 case TYPEID_UNIT:
492 case TYPEID_PLAYER:
493 tmpUnitMap.push_back((Unit*)result);
494 break;
495 case TYPEID_CORPSE:
496 m_targets.setCorpseTarget((Corpse*)result);
497 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
498 tmpUnitMap.push_back(owner);
499 break;
502 else
504 // clear cooldown at fail
505 if(m_caster->GetTypeId()==TYPEID_PLAYER)
507 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
509 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
510 data << uint32(m_spellInfo->Id);
511 data << uint64(m_caster->GetGUID());
512 ((Player*)m_caster)->GetSession()->SendPacket(&data);
515 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
516 finish(false);
518 break;
520 default:
521 if(m_targets.getUnitTarget())
522 tmpUnitMap.push_back(m_targets.getUnitTarget());
523 break;
525 break;
527 case SPELL_EFFECT_RESURRECT:
528 case SPELL_EFFECT_PARRY:
529 case SPELL_EFFECT_BLOCK:
530 case SPELL_EFFECT_CREATE_ITEM:
531 case SPELL_EFFECT_TRIGGER_SPELL:
532 case SPELL_EFFECT_TRIGGER_MISSILE:
533 case SPELL_EFFECT_LEARN_SPELL:
534 case SPELL_EFFECT_SKILL_STEP:
535 case SPELL_EFFECT_PROFICIENCY:
536 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
537 case SPELL_EFFECT_SELF_RESURRECT:
538 case SPELL_EFFECT_REPUTATION:
539 if(m_targets.getUnitTarget())
540 tmpUnitMap.push_back(m_targets.getUnitTarget());
541 break;
542 case SPELL_EFFECT_SUMMON_PLAYER:
543 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
545 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
546 if(target)
547 tmpUnitMap.push_back(target);
549 break;
550 case SPELL_EFFECT_RESURRECT_NEW:
551 if(m_targets.getUnitTarget())
552 tmpUnitMap.push_back(m_targets.getUnitTarget());
553 if(m_targets.getCorpseTargetGUID())
555 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
556 if(corpse)
558 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
559 if(owner)
560 tmpUnitMap.push_back(owner);
563 break;
564 case SPELL_EFFECT_SUMMON:
565 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
567 if(m_targets.getUnitTarget())
568 tmpUnitMap.push_back(m_targets.getUnitTarget());
570 else
571 tmpUnitMap.push_back(m_caster);
572 break;
573 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
574 case SPELL_EFFECT_SUMMON_WILD:
575 case SPELL_EFFECT_SUMMON_GUARDIAN:
576 case SPELL_EFFECT_TRANS_DOOR:
577 case SPELL_EFFECT_ADD_FARSIGHT:
578 case SPELL_EFFECT_APPLY_GLYPH:
579 case SPELL_EFFECT_STUCK:
580 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
581 case SPELL_EFFECT_SUMMON_DEMON:
582 case SPELL_EFFECT_SKILL:
583 tmpUnitMap.push_back(m_caster);
584 break;
585 case SPELL_EFFECT_LEARN_PET_SPELL:
586 if(Pet* pet = m_caster->GetPet())
587 tmpUnitMap.push_back(pet);
588 break;
589 case SPELL_EFFECT_ENCHANT_ITEM:
590 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
591 case SPELL_EFFECT_DISENCHANT:
592 case SPELL_EFFECT_FEED_PET:
593 case SPELL_EFFECT_PROSPECTING:
594 case SPELL_EFFECT_MILLING:
595 if(m_targets.getItemTarget())
596 AddItemTarget(m_targets.getItemTarget(), i);
597 break;
598 case SPELL_EFFECT_APPLY_AURA:
599 switch(m_spellInfo->EffectApplyAuraName[i])
601 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)
602 case SPELL_AURA_ADD_PCT_MODIFIER:
603 tmpUnitMap.push_back(m_caster);
604 break;
605 default: // apply to target in other case
606 if(m_targets.getUnitTarget())
607 tmpUnitMap.push_back(m_targets.getUnitTarget());
608 break;
610 break;
611 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
612 // AreaAura
613 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
614 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
615 break;
616 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
617 if(m_targets.getUnitTarget())
619 tmpUnitMap.push_back(m_targets.getUnitTarget());
621 else if (m_targets.getCorpseTargetGUID())
623 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
624 if(corpse)
626 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
627 if(owner)
628 tmpUnitMap.push_back(owner);
631 break;
632 default:
633 break;
636 if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
637 m_needAliveTargetMask |= (1<<i);
639 if(m_caster->GetTypeId() == TYPEID_PLAYER)
641 Player *me = (Player*)m_caster;
642 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
644 Unit *owner = (*itr)->GetOwner();
645 Unit *u = owner ? owner : (*itr);
646 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
648 me->UpdatePvP(true);
649 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
650 break;
655 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
657 if (!CheckTarget (*itr, i))
659 itr = tmpUnitMap.erase(itr);
660 continue;
662 else
663 ++itr;
666 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
667 AddUnitTarget((*iunit), i);
671 void Spell::prepareDataForTriggerSystem()
673 //==========================================================================================
674 // Now fill data for trigger system, need know:
675 // Ñan spell trigger another or not ( m_canTrigger )
676 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
677 //==========================================================================================
679 // Fill flag can spell trigger or not
680 if (!m_IsTriggeredSpell)
681 m_canTrigger = true; // Normal cast - can trigger
682 else if (!m_triggeredByAuraSpell)
683 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
684 else // Exceptions (some periodic triggers)
686 m_canTrigger = false; // Triggered spells can`t trigger another
687 switch (m_spellInfo->SpellFamilyName)
689 case SPELLFAMILY_MAGE: // Arcane Missles triggers need do it
690 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200000LL) m_canTrigger = true;
691 break;
692 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
693 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
694 break;
695 case SPELLFAMILY_HUNTER: // Hunter Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect
696 if (m_spellInfo->SpellFamilyFlags & 0x0000200000000014LL) m_canTrigger = true;
697 break;
698 case SPELLFAMILY_PALADIN: // For Holy Shock triggers need do it
699 if (m_spellInfo->SpellFamilyFlags & 0x0001000000200000LL) m_canTrigger = true;
700 break;
703 // Do not trigger from item cast spell
704 if (m_CastItem)
705 m_canTrigger = false;
707 // Get data for type of attack and fill base info for trigger
708 switch (m_spellInfo->DmgClass)
710 case SPELL_DAMAGE_CLASS_MELEE:
711 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
712 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
713 break;
714 case SPELL_DAMAGE_CLASS_RANGED:
715 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
716 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
717 break;
718 default:
719 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
721 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
722 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
724 // Wands
725 else if (IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT)
727 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
728 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
730 else
732 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
733 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
735 break;
737 // Hunter traps spells (for Entrapment trigger)
738 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
739 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x0000200000000014LL)
740 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
743 void Spell::CleanupTargetList()
745 m_UniqueTargetInfo.clear();
746 m_UniqueGOTargetInfo.clear();
747 m_UniqueItemInfo.clear();
748 m_countOfHit = 0;
749 m_countOfMiss = 0;
750 m_delayMoment = 0;
753 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
755 if( m_spellInfo->Effect[effIndex]==0 )
756 return;
758 uint64 targetGUID = pVictim->GetGUID();
760 // Lookup target in already in list
761 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
763 if (targetGUID == ihit->targetGUID) // Found in list
765 ihit->effectMask |= 1<<effIndex; // Add only effect mask
766 return;
770 // This is new target calculate data for him
772 // Get spell hit result on target
773 TargetInfo target;
774 target.targetGUID = targetGUID; // Store target GUID
775 target.effectMask = 1<<effIndex; // Store index of effect
776 target.processed = false; // Effects not apply on target
778 // Calculate hit result
779 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
780 if (target.missCondition == SPELL_MISS_NONE)
781 ++m_countOfHit;
782 else
783 ++m_countOfMiss;
785 // Spell have speed - need calculate incoming time
786 if (m_spellInfo->speed > 0.0f)
788 // calculate spell incoming interval
789 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
790 if (dist < 5.0f) dist = 5.0f;
791 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
793 // Calculate minimum incoming time
794 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
795 m_delayMoment = target.timeDelay;
797 else
798 target.timeDelay = 0LL;
800 // If target reflect spell back to caster
801 if (target.missCondition==SPELL_MISS_REFLECT)
803 // Calculate reflected spell result on caster
804 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
806 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
807 target.reflectResult = SPELL_MISS_PARRY;
809 // Increase time interval for reflected spells by 1.5
810 target.timeDelay+=target.timeDelay>>1;
812 else
813 target.reflectResult = SPELL_MISS_NONE;
815 // Add target to list
816 m_UniqueTargetInfo.push_back(target);
819 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
821 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
822 if (unit)
823 AddUnitTarget(unit, effIndex);
826 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
828 if( m_spellInfo->Effect[effIndex]==0 )
829 return;
831 uint64 targetGUID = pVictim->GetGUID();
833 // Lookup target in already in list
834 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
836 if (targetGUID == ihit->targetGUID) // Found in list
838 ihit->effectMask |= 1<<effIndex; // Add only effect mask
839 return;
843 // This is new target calculate data for him
845 GOTargetInfo target;
846 target.targetGUID = targetGUID;
847 target.effectMask = 1<<effIndex;
848 target.processed = false; // Effects not apply on target
850 // Spell have speed - need calculate incoming time
851 if (m_spellInfo->speed > 0.0f)
853 // calculate spell incoming interval
854 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
855 if (dist < 5.0f) dist = 5.0f;
856 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
857 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
858 m_delayMoment = target.timeDelay;
860 else
861 target.timeDelay = 0LL;
863 ++m_countOfHit;
865 // Add target to list
866 m_UniqueGOTargetInfo.push_back(target);
869 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
871 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
872 if (go)
873 AddGOTarget(go, effIndex);
876 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
878 if( m_spellInfo->Effect[effIndex]==0 )
879 return;
881 // Lookup target in already in list
882 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
884 if (pitem == ihit->item) // Found in list
886 ihit->effectMask |= 1<<effIndex; // Add only effect mask
887 return;
891 // This is new target add data
893 ItemTargetInfo target;
894 target.item = pitem;
895 target.effectMask = 1<<effIndex;
896 m_UniqueItemInfo.push_back(target);
899 void Spell::DoAllEffectOnTarget(TargetInfo *target)
901 if (target->processed) // Check target
902 return;
903 target->processed = true; // Target checked in apply effects procedure
905 // Get mask of effects for target
906 uint32 mask = target->effectMask;
907 if (mask == 0) // No effects
908 return;
910 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
911 if (!unit)
912 return;
914 // Get original caster (if exist) and calculate damage/healing from him data
915 Unit *caster = m_originalCasterGUID ? m_originalCaster : m_caster;
917 // Skip if m_originalCaster not avaiable
918 if (!caster)
919 return;
921 SpellMissInfo missInfo = target->missCondition;
922 // Need init unitTarget by default unit (can changed in code on reflect)
923 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
924 unitTarget = unit;
926 // Reset damage/healing counter
927 m_damage = 0;
928 m_healing = 0;
930 // Fill base trigger info
931 uint32 procAttacker = m_procAttacker;
932 uint32 procVictim = m_procVictim;
933 uint32 procEx = PROC_EX_NONE;
935 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
936 DoSpellHitOnUnit(unit, mask);
937 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
939 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
940 DoSpellHitOnUnit(m_caster, mask);
943 // All calculated do it!
944 // Do healing and triggers
945 if (m_healing)
947 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
948 uint32 addhealth = m_healing;
949 if (crit)
951 procEx |= PROC_EX_CRITICAL_HIT;
952 addhealth = caster->SpellCriticalBonus(m_spellInfo, addhealth, NULL);
954 else
955 procEx |= PROC_EX_NORMAL_HIT;
957 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
959 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
960 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
961 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
963 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
965 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
966 if(caster->GetTypeId()==TYPEID_PLAYER)
967 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
968 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
970 // Do damage and triggers
971 else if (m_damage)
973 // Fill base damage struct (unitTarget - is real spell target)
974 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
976 // Add bonuses and fill damageInfo struct
977 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
979 // Send log damage message to client
980 caster->SendSpellNonMeleeDamageLog(&damageInfo);
982 procEx = createProcExtendMask(&damageInfo, missInfo);
983 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
985 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
986 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
987 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
989 caster->DealSpellDamage(&damageInfo, true);
991 // Judgement of Blood
992 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
994 int32 damagePoint = damageInfo.damage * 33 / 100;
995 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
997 // Bloodthirst
998 else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && m_spellInfo->SpellFamilyFlags & 0x40000000000LL)
1000 uint32 BTAura = 0;
1001 switch(m_spellInfo->Id)
1003 case 23881: BTAura = 23885; break;
1004 case 23892: BTAura = 23886; break;
1005 case 23893: BTAura = 23887; break;
1006 case 23894: BTAura = 23888; break;
1007 case 25251: BTAura = 25252; break;
1008 case 30335: BTAura = 30339; break;
1009 default:
1010 sLog.outError("Spell::EffectSchoolDMG: Spell %u not handled in BTAura",m_spellInfo->Id);
1011 break;
1013 if (BTAura)
1014 m_caster->CastSpell(m_caster,BTAura,true);
1017 // Passive spell hits/misses or active spells only misses (only triggers)
1018 else
1020 // Fill base damage struct (unitTarget - is real spell target)
1021 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1022 procEx = createProcExtendMask(&damageInfo, missInfo);
1023 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1024 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1025 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1028 // Call scripted function for AI if this spell is casted upon a creature (except pets)
1029 if(IS_CREATURE_GUID(target->targetGUID))
1031 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1032 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1033 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1034 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1036 if(((Creature*)unit)->AI())
1037 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1041 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1043 if(!unit || !effectMask)
1044 return;
1046 // Recheck immune (only for delayed spells)
1047 if( m_spellInfo->speed && (
1048 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo),true) ||
1049 unit->IsImmunedToSpell(m_spellInfo,true) ))
1051 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1052 return;
1055 if (unit->GetTypeId() == TYPEID_PLAYER)
1057 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1058 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1061 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1063 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1066 if( m_caster != unit )
1068 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1069 if (m_spellInfo->speed > 0.0f &&
1070 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1071 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1073 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1074 return;
1077 if( !m_caster->IsFriendlyTo(unit) )
1079 // for delayed spells ignore not visible explicit target
1080 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1082 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1083 return;
1086 // exclude Arcane Missiles Dummy Aura aura for now (attack on hit)
1087 // TODO: find way to not need this?
1088 if(!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE &&
1089 m_spellInfo->SpellFamilyFlags & 0x800LL))
1091 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1093 if( !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
1095 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1096 unit->SetStandState(PLAYER_STATE_NONE);
1098 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1099 ((Creature*)unit)->AI()->AttackStart(m_caster);
1101 unit->SetInCombatWith(m_caster);
1102 m_caster->SetInCombatWith(unit);
1104 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1106 m_caster->SetContestedPvP(attackedPlayer);
1108 unit->AddThreat(m_caster, 0.0f);
1112 else
1114 // for delayed spells ignore negative spells (after duel end) for friendly targets
1115 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1117 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1118 return;
1121 // assisting case, healing and resurrection
1122 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1123 m_caster->SetContestedPvP();
1124 if( unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
1126 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1127 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1132 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1133 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1134 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1135 // Increase Diminishing on unit, current informations for actually casts will use values above
1136 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1137 unit->IncrDiminishing(m_diminishGroup);
1139 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1141 if (effectMask & (1<<effectNumber))
1143 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1144 if ( m_applyMultiplierMask & (1 << effectNumber) )
1146 // Get multiplier
1147 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1148 // Apply multiplier mods
1149 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1150 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1151 m_damageMultipliers[effectNumber] *= multiplier;
1157 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1159 if (target->processed) // Check target
1160 return;
1161 target->processed = true; // Target checked in apply effects procedure
1163 uint32 effectMask = target->effectMask;
1164 if(!effectMask)
1165 return;
1167 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1168 if(!go)
1169 return;
1171 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1172 if (effectMask & (1<<effectNumber))
1173 HandleEffects(NULL,NULL,go,effectNumber);
1175 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1176 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1177 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1178 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1181 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1183 uint32 effectMask = target->effectMask;
1184 if(!target->item || !effectMask)
1185 return;
1187 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1188 if (effectMask & (1<<effectNumber))
1189 HandleEffects(NULL, target->item, NULL, effectNumber);
1192 bool Spell::IsAliveUnitPresentInTargetList()
1194 // Not need check return true
1195 if (m_needAliveTargetMask == 0)
1196 return true;
1198 uint8 needAliveTargetMask = m_needAliveTargetMask;
1200 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1202 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1204 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1206 if (unit && unit->isAlive())
1207 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1211 // is all effects from m_needAliveTargetMask have alive targets
1212 return needAliveTargetMask==0;
1215 // Helper for Chain Healing
1216 // Spell target first
1217 // Raidmates then descending by injury suffered (MaxHealth - Health)
1218 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1219 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1221 const Unit* MainTarget;
1222 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1223 // functor for operator ">"
1224 bool operator()(Unit const* _Left, Unit const* _Right) const
1226 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1228 int32 ChainHealingHash(Unit const* Target) const
1230 if (Target == MainTarget)
1231 return 0;
1232 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1233 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1235 if (Target->GetHealth() == Target->GetMaxHealth())
1236 return 40000;
1237 else
1238 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1240 else
1241 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1245 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1247 public:
1248 const Unit* MainTarget;
1249 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1251 bool operator()(const Unit* Target)
1253 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1257 // Helper for targets nearest to the spell target
1258 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1259 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1261 const Unit* MainTarget;
1262 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1263 // functor for operator ">"
1264 bool operator()(const Unit* _Left, const Unit* _Right) const
1266 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1270 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1272 float radius;
1273 if (m_spellInfo->EffectRadiusIndex[i])
1274 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1275 else
1276 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1278 if(m_originalCaster)
1279 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1280 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1282 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1283 if(m_originalCaster)
1284 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1285 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1287 // Get spell max affected targets
1288 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1289 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1290 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1292 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1293 continue;
1294 unMaxTargets+=(*m)->GetModifier()->m_amount;
1296 switch(cur)
1298 case TARGET_TOTEM_EARTH:
1299 case TARGET_TOTEM_WATER:
1300 case TARGET_TOTEM_AIR:
1301 case TARGET_TOTEM_FIRE:
1302 case TARGET_SELF:
1303 case TARGET_SELF2:
1304 case TARGET_DYNAMIC_OBJECT:
1305 case TARGET_AREAEFFECT_CUSTOM:
1306 case TARGET_AREAEFFECT_CUSTOM_2:
1307 case TARGET_SUMMON:
1309 TagUnitMap.push_back(m_caster);
1310 break;
1312 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1314 m_targets.m_targetMask = 0;
1315 unMaxTargets = EffectChainTarget;
1316 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1318 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1319 Cell cell(p);
1320 cell.data.Part.reserved = ALL_DISTRICT;
1321 cell.SetNoCreate();
1323 std::list<Unit *> tempUnitMap;
1326 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1327 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1329 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1330 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1332 CellLock<GridReadGuard> cell_lock(cell, p);
1333 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1334 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1337 if(tempUnitMap.empty())
1338 break;
1340 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1342 //Now to get us a random target that's in the initial range of the spell
1343 uint32 t = 0;
1344 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1345 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1346 ++t, ++itr;
1348 if(!t)
1349 break;
1351 itr = tempUnitMap.begin();
1352 std::advance(itr, rand()%t);
1353 Unit *pUnitTarget = *itr;
1354 TagUnitMap.push_back(pUnitTarget);
1356 tempUnitMap.erase(itr);
1358 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1360 t = unMaxTargets - 1;
1361 Unit *prev = pUnitTarget;
1362 std::list<Unit*>::iterator next = tempUnitMap.begin();
1364 while(t && next != tempUnitMap.end() )
1366 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1367 break;
1369 if(!prev->IsWithinLOSInMap(*next))
1371 ++next;
1372 continue;
1375 prev = *next;
1376 TagUnitMap.push_back(prev);
1377 tempUnitMap.erase(next);
1378 tempUnitMap.sort(TargetDistanceOrder(prev));
1379 next = tempUnitMap.begin();
1381 --t;
1383 }break;
1384 case TARGET_PET:
1386 Pet* tmpUnit = m_caster->GetPet();
1387 if (!tmpUnit) break;
1388 TagUnitMap.push_back(tmpUnit);
1389 break;
1391 case TARGET_CHAIN_DAMAGE:
1393 if (EffectChainTarget <= 1)
1395 Unit* pUnitTarget = SelectMagnetTarget();
1396 if(pUnitTarget)
1397 TagUnitMap.push_back(pUnitTarget);
1399 else
1401 Unit* pUnitTarget = m_targets.getUnitTarget();
1402 if(!pUnitTarget)
1403 break;
1405 unMaxTargets = EffectChainTarget;
1407 float max_range;
1408 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1409 max_range = radius; //
1410 else
1411 //FIXME: This very like horrible hack and wrong for most spells
1412 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1414 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1415 Cell cell(p);
1416 cell.data.Part.reserved = ALL_DISTRICT;
1417 cell.SetNoCreate();
1419 Unit* originalCaster = GetOriginalCaster();
1420 if(originalCaster)
1422 std::list<Unit *> tempUnitMap;
1425 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1426 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1428 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1429 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1431 CellLock<GridReadGuard> cell_lock(cell, p);
1432 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1433 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1436 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1438 if(tempUnitMap.empty())
1439 break;
1441 if(*tempUnitMap.begin() == pUnitTarget)
1442 tempUnitMap.erase(tempUnitMap.begin());
1444 TagUnitMap.push_back(pUnitTarget);
1445 uint32 t = unMaxTargets - 1;
1446 Unit *prev = pUnitTarget;
1447 std::list<Unit*>::iterator next = tempUnitMap.begin();
1449 while(t && next != tempUnitMap.end() )
1451 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1452 break;
1454 if(!prev->IsWithinLOSInMap(*next))
1456 ++next;
1457 continue;
1460 prev = *next;
1461 TagUnitMap.push_back(prev);
1462 tempUnitMap.erase(next);
1463 tempUnitMap.sort(TargetDistanceOrder(prev));
1464 next = tempUnitMap.begin();
1466 --t;
1470 }break;
1471 case TARGET_ALL_ENEMY_IN_AREA:
1473 }break;
1474 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1476 // targets the ground, not the units in the area
1477 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1479 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1480 Cell cell(p);
1481 cell.data.Part.reserved = ALL_DISTRICT;
1482 cell.SetNoCreate();
1484 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1486 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1487 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1489 CellLock<GridReadGuard> cell_lock(cell, p);
1490 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1491 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1493 // exclude caster (this can be important if this not original caster)
1494 TagUnitMap.remove(m_caster);
1496 }break;
1497 case TARGET_DUELVSPLAYER_COORDINATES:
1499 if(Unit* currentTarget = m_targets.getUnitTarget())
1501 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1502 TagUnitMap.push_back(currentTarget);
1504 }break;
1505 case TARGET_ALL_PARTY_AROUND_CASTER:
1506 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1507 case TARGET_ALL_PARTY:
1508 case TARGET_ALL_RAID_AROUND_CASTER:
1510 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1511 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1513 if(pGroup)
1515 uint8 subgroup = pTarget->GetSubGroup();
1517 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1519 Player* Target = itr->getSource();
1521 // IsHostileTo check duel and controlled by enemy
1522 if( Target &&
1523 (cur==TARGET_ALL_RAID_AROUND_CASTER || Target->GetSubGroup()==subgroup) &&
1524 !m_caster->IsHostileTo(Target) )
1526 if( m_caster->IsWithinDistInMap(Target, radius) )
1527 TagUnitMap.push_back(Target);
1529 if(Pet* pet = Target->GetPet())
1530 if( m_caster->IsWithinDistInMap(pet, radius) )
1531 TagUnitMap.push_back(pet);
1535 else
1537 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1538 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1539 TagUnitMap.push_back(ownerOrSelf);
1540 if(Pet* pet = ownerOrSelf->GetPet())
1541 if( m_caster->IsWithinDistInMap(pet, radius) )
1542 TagUnitMap.push_back(pet);
1544 }break;
1545 case TARGET_SINGLE_FRIEND:
1546 case TARGET_SINGLE_FRIEND_2:
1548 if(m_targets.getUnitTarget())
1549 TagUnitMap.push_back(m_targets.getUnitTarget());
1550 }break;
1551 case TARGET_NONCOMBAT_PET:
1553 if(Unit* target = m_targets.getUnitTarget())
1554 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1555 TagUnitMap.push_back(target);
1556 }break;
1557 case TARGET_ALL_AROUND_CASTER:
1559 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1560 Cell cell(p);
1561 cell.data.Part.reserved = ALL_DISTRICT;
1562 cell.SetNoCreate();
1564 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1566 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1567 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1569 CellLock<GridReadGuard> cell_lock(cell, p);
1570 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1571 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1572 }break;
1573 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1575 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1576 Cell cell(p);
1577 cell.data.Part.reserved = ALL_DISTRICT;
1578 cell.SetNoCreate();
1580 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1582 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1583 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1585 CellLock<GridReadGuard> cell_lock(cell, p);
1586 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1587 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1588 }break;
1589 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1591 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1592 Cell cell(p);
1593 cell.data.Part.reserved = ALL_DISTRICT;
1594 cell.SetNoCreate();
1596 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1598 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1599 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1601 CellLock<GridReadGuard> cell_lock(cell, p);
1602 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1603 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1604 }break;
1605 // 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..)
1606 case TARGET_SINGLE_PARTY:
1608 Unit *target = m_targets.getUnitTarget();
1609 // Thoses spells apparently can't be casted on the caster.
1610 if( target && target != m_caster)
1612 // Can only be casted on group's members or its pets
1613 Group *pGroup = NULL;
1615 Unit* owner = m_caster->GetCharmerOrOwner();
1616 Unit *targetOwner = target->GetCharmerOrOwner();
1617 if(owner)
1619 if(owner->GetTypeId() == TYPEID_PLAYER)
1621 if( target == owner )
1623 TagUnitMap.push_back(target);
1624 break;
1626 pGroup = ((Player*)owner)->GetGroup();
1629 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1631 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1633 TagUnitMap.push_back(target);
1634 break;
1636 pGroup = ((Player*)m_caster)->GetGroup();
1639 if(pGroup)
1641 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1642 if(targetOwner)
1644 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1645 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1646 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1647 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1649 TagUnitMap.push_back(target);
1652 // 1Our target can be a player who is on our group
1653 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1655 TagUnitMap.push_back(target);
1659 }break;
1660 case TARGET_GAMEOBJECT:
1662 if(m_targets.getGOTarget())
1663 AddGOTarget(m_targets.getGOTarget(), i);
1664 }break;
1665 case TARGET_IN_FRONT_OF_CASTER:
1667 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1668 Cell cell(p);
1669 cell.data.Part.reserved = ALL_DISTRICT;
1670 cell.SetNoCreate();
1672 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1673 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1675 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1676 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1678 CellLock<GridReadGuard> cell_lock(cell, p);
1679 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1680 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1681 }break;
1682 case TARGET_DUELVSPLAYER:
1684 Unit *target = m_targets.getUnitTarget();
1685 if(target)
1687 if(m_caster->IsFriendlyTo(target))
1689 TagUnitMap.push_back(target);
1691 else
1693 Unit* pUnitTarget = SelectMagnetTarget();
1694 if(pUnitTarget)
1695 TagUnitMap.push_back(pUnitTarget);
1698 }break;
1699 case TARGET_GAMEOBJECT_ITEM:
1701 if(m_targets.getGOTargetGUID())
1702 AddGOTarget(m_targets.getGOTarget(), i);
1703 else if(m_targets.getItemTarget())
1704 AddItemTarget(m_targets.getItemTarget(), i);
1705 break;
1707 case TARGET_MASTER:
1709 if(Unit* owner = m_caster->GetCharmerOrOwner())
1710 TagUnitMap.push_back(owner);
1711 break;
1713 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1715 // targets the ground, not the units in the area
1716 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1718 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1719 Cell cell(p);
1720 cell.data.Part.reserved = ALL_DISTRICT;
1721 cell.SetNoCreate();
1723 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1725 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1726 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1728 CellLock<GridReadGuard> cell_lock(cell, p);
1729 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1730 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1732 }break;
1733 case TARGET_MINION:
1735 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1736 TagUnitMap.push_back(m_caster);
1737 }break;
1738 case TARGET_SINGLE_ENEMY:
1740 Unit* pUnitTarget = SelectMagnetTarget();
1741 if(pUnitTarget)
1742 TagUnitMap.push_back(pUnitTarget);
1743 }break;
1744 case TARGET_AREAEFFECT_PARTY:
1746 Unit* owner = m_caster->GetCharmerOrOwner();
1747 Player *pTarget = NULL;
1749 if(owner)
1751 TagUnitMap.push_back(m_caster);
1752 if(owner->GetTypeId() == TYPEID_PLAYER)
1753 pTarget = (Player*)owner;
1755 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1757 if(Unit* target = m_targets.getUnitTarget())
1759 if( target->GetTypeId() != TYPEID_PLAYER)
1761 if(((Creature*)target)->isPet())
1763 Unit *targetOwner = target->GetOwner();
1764 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1765 pTarget = (Player*)targetOwner;
1768 else
1769 pTarget = (Player*)target;
1773 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1775 if(pGroup)
1777 uint8 subgroup = pTarget->GetSubGroup();
1779 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1781 Player* Target = itr->getSource();
1783 // IsHostileTo check duel and controlled by enemy
1784 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1786 if( pTarget->IsWithinDistInMap(Target, radius) )
1787 TagUnitMap.push_back(Target);
1789 if(Pet* pet = Target->GetPet())
1790 if( pTarget->IsWithinDistInMap(pet, radius) )
1791 TagUnitMap.push_back(pet);
1795 else if (owner)
1797 if(m_caster->IsWithinDistInMap(owner, radius))
1798 TagUnitMap.push_back(owner);
1800 else if(pTarget)
1802 TagUnitMap.push_back(pTarget);
1804 if(Pet* pet = pTarget->GetPet())
1805 if( m_caster->IsWithinDistInMap(pet, radius) )
1806 TagUnitMap.push_back(pet);
1809 }break;
1810 case TARGET_SCRIPT:
1812 if(m_targets.getUnitTarget())
1813 TagUnitMap.push_back(m_targets.getUnitTarget());
1814 if(m_targets.getItemTarget())
1815 AddItemTarget(m_targets.getItemTarget(), i);
1816 }break;
1817 case TARGET_SELF_FISHING:
1819 TagUnitMap.push_back(m_caster);
1820 }break;
1821 case TARGET_CHAIN_HEAL:
1823 Unit* pUnitTarget = m_targets.getUnitTarget();
1824 if(!pUnitTarget)
1825 break;
1827 if (EffectChainTarget <= 1)
1828 TagUnitMap.push_back(pUnitTarget);
1829 else
1831 unMaxTargets = EffectChainTarget;
1832 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1834 std::list<Unit *> tempUnitMap;
1837 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1838 Cell cell(p);
1839 cell.data.Part.reserved = ALL_DISTRICT;
1840 cell.SetNoCreate();
1842 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1844 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1845 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1847 CellLock<GridReadGuard> cell_lock(cell, p);
1848 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1849 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1853 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1854 tempUnitMap.push_front(m_caster);
1856 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1858 if(tempUnitMap.empty())
1859 break;
1861 if(*tempUnitMap.begin() == pUnitTarget)
1862 tempUnitMap.erase(tempUnitMap.begin());
1864 TagUnitMap.push_back(pUnitTarget);
1865 uint32 t = unMaxTargets - 1;
1866 Unit *prev = pUnitTarget;
1867 std::list<Unit*>::iterator next = tempUnitMap.begin();
1869 while(t && next != tempUnitMap.end() )
1871 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1872 break;
1874 if(!prev->IsWithinLOSInMap(*next))
1876 ++next;
1877 continue;
1880 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1882 next = tempUnitMap.erase(next);
1883 continue;
1886 prev = *next;
1887 TagUnitMap.push_back(prev);
1888 tempUnitMap.erase(next);
1889 tempUnitMap.sort(TargetDistanceOrder(prev));
1890 next = tempUnitMap.begin();
1892 --t;
1895 }break;
1896 case TARGET_CURRENT_ENEMY_COORDINATES:
1898 Unit* currentTarget = m_targets.getUnitTarget();
1899 if(currentTarget)
1901 TagUnitMap.push_back(currentTarget);
1902 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1903 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1905 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1906 Cell cell(p);
1907 cell.data.Part.reserved = ALL_DISTRICT;
1908 cell.SetNoCreate();
1909 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1910 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1911 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1912 CellLock<GridReadGuard> cell_lock(cell, p);
1913 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1914 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1917 }break;
1918 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1920 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1921 ? (Player*)m_targets.getUnitTarget() : NULL;
1923 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1924 if(pGroup)
1926 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1928 Player* Target = itr->getSource();
1930 // IsHostileTo check duel and controlled by enemy
1931 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1932 targetPlayer->getClass() == Target->getClass() &&
1933 !m_caster->IsHostileTo(Target) )
1935 TagUnitMap.push_back(Target);
1939 else if(m_targets.getUnitTarget())
1940 TagUnitMap.push_back(m_targets.getUnitTarget());
1941 break;
1943 case TARGET_TABLE_X_Y_Z_COORDINATES:
1945 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
1946 if(st)
1948 if (st->target_mapId == m_caster->GetMapId())
1949 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1951 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
1952 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
1954 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1955 Cell cell(p);
1956 cell.data.Part.reserved = ALL_DISTRICT;
1957 cell.SetNoCreate();
1959 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1960 // Select friendly targets for positive effect
1961 if (IsPositiveEffect(m_spellInfo->Id, i))
1962 targetB = SPELL_TARGETS_FRIENDLY;
1964 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
1966 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1967 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1969 CellLock<GridReadGuard> cell_lock(cell, p);
1970 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1971 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1974 else
1975 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1976 }break;
1977 case TARGET_BEHIND_VICTIM:
1979 Unit *pTarget = m_caster->getVictim();
1980 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
1981 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
1983 if(pTarget)
1985 float _target_x, _target_y, _target_z;
1986 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
1987 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
1988 m_targets.setDestination(_target_x, _target_y, _target_z);
1990 }break;
1991 default:
1992 break;
1995 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
1997 // make sure one unit is always removed per iteration
1998 uint32 removed_utarget = 0;
1999 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2001 next = itr;
2002 ++next;
2003 if (!*itr) continue;
2004 if ((*itr) == m_targets.getUnitTarget())
2006 TagUnitMap.erase(itr);
2007 removed_utarget = 1;
2008 // break;
2011 // remove random units from the map
2012 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2014 uint32 poz = urand(0, TagUnitMap.size()-1);
2015 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2017 if (!*itr) continue;
2018 if (!poz)
2020 TagUnitMap.erase(itr);
2021 break;
2025 // the player's target will always be added to the map
2026 if (removed_utarget && m_targets.getUnitTarget())
2027 TagUnitMap.push_back(m_targets.getUnitTarget());
2031 void Spell::prepare(SpellCastTargets * targets, Aura* triggeredByAura)
2033 m_targets = *targets;
2035 m_spellState = SPELL_STATE_PREPARING;
2037 m_castPositionX = m_caster->GetPositionX();
2038 m_castPositionY = m_caster->GetPositionY();
2039 m_castPositionZ = m_caster->GetPositionZ();
2040 m_castOrientation = m_caster->GetOrientation();
2042 if(triggeredByAura)
2043 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2045 // create and add update event for this spell
2046 SpellEvent* Event = new SpellEvent(this);
2047 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2049 //Prevent casting at cast another spell (ServerSide check)
2050 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2052 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2053 finish(false);
2054 return;
2057 // Fill cost data
2058 m_powerCost = CalculatePowerCost();
2060 uint8 result = CanCast(true);
2061 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2063 if(triggeredByAura)
2065 SendChannelUpdate(0);
2066 triggeredByAura->SetAuraDuration(0);
2068 SendCastResult(result);
2069 finish(false);
2070 return;
2073 // Prepare data for triggers
2074 prepareDataForTriggerSystem();
2076 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2077 m_casttime = GetSpellCastTime(m_spellInfo, this);
2079 // set timer base at cast time
2080 ReSetTimer();
2082 // stealth must be removed at cast starting (at show channel bar)
2083 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2084 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2086 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2087 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2090 if(m_IsTriggeredSpell)
2091 cast(true);
2092 else
2094 m_caster->SetCurrentCastedSpell( this );
2095 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2096 SendSpellStart();
2100 void Spell::cancel()
2102 if(m_spellState == SPELL_STATE_FINISHED)
2103 return;
2105 m_autoRepeat = false;
2106 switch (m_spellState)
2108 case SPELL_STATE_PREPARING:
2109 case SPELL_STATE_DELAYED:
2111 SendInterrupted(0);
2112 SendCastResult(SPELL_FAILED_INTERRUPTED);
2113 } break;
2115 case SPELL_STATE_CASTING:
2117 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2119 if( ihit->missCondition == SPELL_MISS_NONE )
2121 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2122 if( unit && unit->isAlive() )
2123 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2127 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2128 SendChannelUpdate(0);
2129 SendInterrupted(0);
2130 SendCastResult(SPELL_FAILED_INTERRUPTED);
2131 } break;
2133 default:
2135 } break;
2138 finish(false);
2139 m_caster->RemoveDynObject(m_spellInfo->Id);
2140 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2143 void Spell::cast(bool skipCheck)
2145 SetExecutedCurrently(true);
2147 uint8 castResult = 0;
2149 // update pointers base at GUIDs to prevent access to non-existed already object
2150 UpdatePointers();
2152 // cancel at lost main target unit
2153 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2155 cancel();
2156 SetExecutedCurrently(false);
2157 return;
2160 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2161 m_caster->SetInFront(m_targets.getUnitTarget());
2163 castResult = CheckPower();
2164 if(castResult != 0)
2166 SendCastResult(castResult);
2167 finish(false);
2168 SetExecutedCurrently(false);
2169 return;
2172 // triggered cast called from Spell::prepare where it was already checked
2173 if(!skipCheck)
2175 castResult = CanCast(false);
2176 if(castResult != 0)
2178 SendCastResult(castResult);
2179 finish(false);
2180 SetExecutedCurrently(false);
2181 return;
2185 // Conflagrate - consumes immolate
2186 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2188 // for caster applied auras only
2189 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2190 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2192 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2193 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2195 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2196 break;
2201 // traded items have trade slot instead of guid in m_itemTargetGUID
2202 // set to real guid to be sent later to the client
2203 m_targets.updateTradeSlotItem();
2205 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2207 if (m_CastItem)
2208 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2210 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2213 // CAST SPELL
2214 SendSpellCooldown();
2216 TakePower();
2217 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2218 FillTargetMap();
2220 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2222 SetExecutedCurrently(false);
2223 return;
2226 SendCastResult(castResult);
2227 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2229 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2230 if (m_spellInfo->speed > 0.0f)
2233 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2234 // in case delayed spell remove item at cast delay start
2235 TakeCastItem();
2237 // Okay, maps created, now prepare flags
2238 m_immediateHandled = false;
2239 m_spellState = SPELL_STATE_DELAYED;
2240 SetDelayStart(0);
2242 else
2244 // Immediate spell, no big deal
2245 handle_immediate();
2248 SetExecutedCurrently(false);
2251 void Spell::handle_immediate()
2253 // start channeling if applicable
2254 if(IsChanneledSpell(m_spellInfo))
2256 m_spellState = SPELL_STATE_CASTING;
2257 SendChannelStart(GetSpellDuration(m_spellInfo));
2260 // process immediate effects (items, ground, etc.) also initialize some variables
2261 _handle_immediate_phase();
2263 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2264 DoAllEffectOnTarget(&(*ihit));
2266 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2267 DoAllEffectOnTarget(&(*ihit));
2269 // spell is finished, perform some last features of the spell here
2270 _handle_finish_phase();
2272 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2273 TakeCastItem();
2275 if(m_spellState != SPELL_STATE_CASTING)
2276 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2279 uint64 Spell::handle_delayed(uint64 t_offset)
2281 uint64 next_time = 0;
2283 if (!m_immediateHandled)
2285 _handle_immediate_phase();
2286 m_immediateHandled = true;
2289 // 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)
2290 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2292 if (ihit->processed == false)
2294 if ( ihit->timeDelay <= t_offset )
2295 DoAllEffectOnTarget(&(*ihit));
2296 else if( next_time == 0 || ihit->timeDelay < next_time )
2297 next_time = ihit->timeDelay;
2301 // now recheck gameobject targeting correctness
2302 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2304 if (ighit->processed == false)
2306 if ( ighit->timeDelay <= t_offset )
2307 DoAllEffectOnTarget(&(*ighit));
2308 else if( next_time == 0 || ighit->timeDelay < next_time )
2309 next_time = ighit->timeDelay;
2312 // All targets passed - need finish phase
2313 if (next_time == 0)
2315 // spell is finished, perform some last features of the spell here
2316 _handle_finish_phase();
2318 finish(true); // successfully finish spell cast
2320 // return zero, spell is finished now
2321 return 0;
2323 else
2325 // spell is unfinished, return next execution time
2326 return next_time;
2330 void Spell::_handle_immediate_phase()
2332 // handle some immediate features of the spell here
2333 HandleThreatSpells(m_spellInfo->Id);
2335 m_needSpellLog = IsNeedSendToClient();
2336 for(uint32 j = 0;j<3;j++)
2338 if(m_spellInfo->Effect[j]==0)
2339 continue;
2341 // apply Send Event effect to ground in case empty target lists
2342 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2344 HandleEffects(NULL,NULL,NULL, j);
2345 continue;
2348 // Don't do spell log, if is school damage spell
2349 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2350 m_needSpellLog = false;
2352 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2353 if(m_originalCaster)
2354 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2355 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2357 // initialize multipliers
2358 m_damageMultipliers[j] = 1.0f;
2359 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2360 (EffectChainTarget > 1) )
2361 m_applyMultiplierMask |= 1 << j;
2364 // initialize Diminishing Returns Data
2365 m_diminishLevel = DIMINISHING_LEVEL_1;
2366 m_diminishGroup = DIMINISHING_NONE;
2368 // process items
2369 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2370 DoAllEffectOnTarget(&(*ihit));
2372 // process ground
2373 for(uint32 j = 0;j<3;j++)
2375 // persistent area auras target only the ground
2376 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2377 HandleEffects(NULL,NULL,NULL, j);
2381 void Spell::_handle_finish_phase()
2383 // spell log
2384 if(m_needSpellLog)
2385 SendLogExecute();
2388 void Spell::SendSpellCooldown()
2390 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2391 return;
2393 Player* _player = (Player*)m_caster;
2394 // Add cooldown for max (disable spell)
2395 // Cooldown started on SendCooldownEvent call
2396 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2398 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2399 return;
2402 // init cooldown values
2403 uint32 cat = 0;
2404 int32 rec = -1;
2405 int32 catrec = -1;
2407 // some special item spells without correct cooldown in SpellInfo
2408 // cooldown information stored in item prototype
2409 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2411 if(m_CastItem)
2413 ItemPrototype const* proto = m_CastItem->GetProto();
2414 if(proto)
2416 for(int idx = 0; idx < 5; ++idx)
2418 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2420 cat = proto->Spells[idx].SpellCategory;
2421 rec = proto->Spells[idx].SpellCooldown;
2422 catrec = proto->Spells[idx].SpellCategoryCooldown;
2423 break;
2429 // if no cooldown found above then base at DBC data
2430 if(rec < 0 && catrec < 0)
2432 cat = m_spellInfo->Category;
2433 rec = m_spellInfo->RecoveryTime;
2434 catrec = m_spellInfo->CategoryRecoveryTime;
2437 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2438 // prevent 0 cooldowns set by another way
2439 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT))
2440 rec = _player->GetAttackTime(RANGED_ATTACK);
2442 // Now we have cooldown data (if found any), time to apply mods
2443 if(rec > 0)
2444 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2446 if(catrec > 0)
2447 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2449 // replace negative cooldowns by 0
2450 if (rec < 0) rec = 0;
2451 if (catrec < 0) catrec = 0;
2453 // no cooldown after applying spell mods
2454 if( rec == 0 && catrec == 0)
2455 return;
2457 time_t curTime = time(NULL);
2459 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2460 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2462 // self spell cooldown
2463 if(recTime > 0)
2464 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2466 // category spells
2467 if (catrec > 0)
2469 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2470 if(i_scstore != sSpellCategoryStore.end())
2472 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2474 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2475 continue;
2477 _player->AddSpellCooldown(*i_scset, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2483 void Spell::update(uint32 difftime)
2485 // update pointers based at it's GUIDs
2486 UpdatePointers();
2488 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2490 cancel();
2491 return;
2494 // check if the player caster has moved before the spell finished
2495 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2496 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2497 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2499 // always cancel for channeled spells
2500 if( m_spellState == SPELL_STATE_CASTING )
2501 cancel();
2502 // don't cancel for melee, autorepeat, triggered and instant spells
2503 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2504 cancel();
2507 switch(m_spellState)
2509 case SPELL_STATE_PREPARING:
2511 if(m_timer)
2513 if(difftime >= m_timer)
2514 m_timer = 0;
2515 else
2516 m_timer -= difftime;
2519 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2520 cast();
2521 } break;
2522 case SPELL_STATE_CASTING:
2524 if(m_timer > 0)
2526 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2528 // check if player has jumped before the channeling finished
2529 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2530 cancel();
2532 // check for incapacitating player states
2533 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2534 cancel();
2536 // check if player has turned if flag is set
2537 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2538 cancel();
2541 // check if there are alive targets left
2542 if (!IsAliveUnitPresentInTargetList())
2544 SendChannelUpdate(0);
2545 finish();
2548 if(difftime >= m_timer)
2549 m_timer = 0;
2550 else
2551 m_timer -= difftime;
2554 if(m_timer == 0)
2556 SendChannelUpdate(0);
2558 // channeled spell processed independently for quest targeting
2559 // cast at creature (or GO) quest objectives update at successful cast channel finished
2560 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2561 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2563 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2565 TargetInfo* target = &*ihit;
2566 if(!IS_CREATURE_GUID(target->targetGUID))
2567 continue;
2569 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2570 if (unit==NULL)
2571 continue;
2573 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2576 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2578 GOTargetInfo* target = &*ihit;
2580 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2581 if(!go)
2582 continue;
2584 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2588 finish();
2590 } break;
2591 default:
2593 }break;
2597 void Spell::finish(bool ok)
2599 if(!m_caster)
2600 return;
2602 if(m_spellState == SPELL_STATE_FINISHED)
2603 return;
2605 m_spellState = SPELL_STATE_FINISHED;
2607 // other code related only to successfully finished spells
2608 if(!ok)
2609 return;
2611 //remove spell mods
2612 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2613 ((Player*)m_caster)->RemoveSpellMods(this);
2615 //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2616 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2617 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2619 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2620 uint32 auraSpellIdx = (*i)->GetEffIndex();
2621 if (IsAffectedByAura((*i)))
2623 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2624 if( ihit->effectMask & (1<<auraSpellIdx) )
2626 // check m_caster->GetGUID() let load auras at login and speedup most often case
2627 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2628 if (unit && unit->isAlive())
2630 // Calculate chance at that moment (can be depend for example from combo points)
2631 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2633 if(roll_chance_i(chance))
2634 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2640 // Heal caster for all health leech from all targets
2641 if (m_healthLeech)
2643 m_caster->ModifyHealth(m_healthLeech);
2644 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2647 if (IsMeleeAttackResetSpell())
2649 m_caster->resetAttackTimer(BASE_ATTACK);
2650 if(m_caster->haveOffhandWeapon())
2651 m_caster->resetAttackTimer(OFF_ATTACK);
2654 /*if (IsRangedAttackResetSpell())
2655 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2657 // Clear combo at finish state
2658 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2660 // Not drop combopoints if negative spell and if any miss on enemy exist
2661 bool needDrop = true;
2662 if (!IsPositiveSpell(m_spellInfo->Id))
2663 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2664 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2666 needDrop = false;
2667 break;
2669 if (needDrop)
2670 ((Player*)m_caster)->ClearComboPoints();
2673 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2674 if(!m_TriggerSpells.empty())
2675 TriggerSpell();
2677 // Stop Attack for some spells
2678 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2679 m_caster->AttackStop();
2682 void Spell::SendCastResult(uint8 result)
2684 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2685 return;
2687 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2688 return;
2690 if(result != 0)
2692 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2693 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2694 data << uint32(m_spellInfo->Id);
2695 data << uint8(result); // problem
2696 switch (result)
2698 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2699 data << uint32(m_spellInfo->RequiresSpellFocus);
2700 break;
2701 case SPELL_FAILED_REQUIRES_AREA:
2702 // hardcode areas limitation case
2703 switch(m_spellInfo->Id)
2705 case 41617: // Cenarion Mana Salve
2706 case 41619: // Cenarion Healing Salve
2707 data << uint32(3905);
2708 break;
2709 case 41618: // Bottled Nethergon Energy
2710 case 41620: // Bottled Nethergon Vapor
2711 data << uint32(3842);
2712 break;
2713 case 45373: // Bloodberry Elixir
2714 data << uint32(4075);
2715 break;
2716 default: // default case (don't must be)
2717 data << uint32(0);
2718 break;
2720 break;
2721 case SPELL_FAILED_TOTEMS:
2722 if(m_spellInfo->Totem[0])
2723 data << uint32(m_spellInfo->Totem[0]);
2724 if(m_spellInfo->Totem[1])
2725 data << uint32(m_spellInfo->Totem[1]);
2726 break;
2727 case SPELL_FAILED_TOTEM_CATEGORY:
2728 if(m_spellInfo->TotemCategory[0])
2729 data << uint32(m_spellInfo->TotemCategory[0]);
2730 if(m_spellInfo->TotemCategory[1])
2731 data << uint32(m_spellInfo->TotemCategory[1]);
2732 break;
2733 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2734 data << uint32(m_spellInfo->EquippedItemClass);
2735 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2736 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2737 break;
2739 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2743 void Spell::SendSpellStart()
2745 if(!IsNeedSendToClient())
2746 return;
2748 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2750 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2751 if(IsRangedSpell())
2752 castFlags |= CAST_FLAG_AMMO;
2754 if(m_spellInfo->runeCostID)
2755 castFlags |= CAST_FLAG_UNKNOWN10;
2757 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2759 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2760 if(m_CastItem)
2761 data.append(m_CastItem->GetPackGUID());
2762 else
2763 data.append(m_caster->GetPackGUID());
2765 data.append(m_caster->GetPackGUID());
2766 data << uint8(m_cast_count); // pending spell cast?
2767 data << uint32(m_spellInfo->Id); // spellId
2768 data << uint32(castFlags); // cast flags
2769 data << uint32(m_timer); // delay?
2771 m_targets.write(&data);
2773 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2774 data << uint32(0);
2776 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2778 uint8 v1 = 0;//m_runesState;
2779 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2780 data << uint8(v1); // runes state before
2781 data << uint8(v2); // runes state after
2782 for(uint8 i = 0; i < MAX_RUNES; ++i)
2784 uint8 m = (1 << i);
2785 if(m & v1) // usable before...
2786 if(!(m & v2)) // ...but on cooldown now...
2787 data << uint8(0); // some unknown byte (time?)
2791 if ( castFlags & CAST_FLAG_AMMO )
2792 WriteAmmoToPacket(&data);
2794 m_caster->SendMessageToSet(&data, true);
2797 void Spell::SendSpellGo()
2799 // not send invisible spell casting
2800 if(!IsNeedSendToClient())
2801 return;
2803 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2805 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2807 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2808 if(IsRangedSpell())
2809 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2811 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2813 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2814 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2815 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2818 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2819 if(m_CastItem)
2820 data.append(m_CastItem->GetPackGUID());
2821 else
2822 data.append(m_caster->GetPackGUID());
2824 data.append(m_caster->GetPackGUID());
2825 data << uint8(m_cast_count); // pending spell cast?
2826 data << uint32(m_spellInfo->Id); // spellId
2827 data << uint32(castFlags); // cast flags
2828 data << uint32(getMSTime()); // timestamp
2830 WriteSpellGoTargets(&data);
2832 m_targets.write(&data);
2834 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2835 data << uint32(0);
2837 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2839 uint8 v1 = m_runesState;
2840 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2841 data << uint8(v1); // runes state before
2842 data << uint8(v2); // runes state after
2843 for(uint8 i = 0; i < MAX_RUNES; ++i)
2845 uint8 m = (1 << i);
2846 if(m & v1) // usable before...
2847 if(!(m & v2)) // ...but on cooldown now...
2848 data << uint8(0); // some unknown byte (time?)
2852 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2854 data << float(0);
2855 data << uint32(0);
2858 if ( castFlags & CAST_FLAG_AMMO )
2859 WriteAmmoToPacket(&data);
2861 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2863 data << uint32(0);
2864 data << uint32(0);
2867 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2869 data << uint8(0);
2872 m_caster->SendMessageToSet(&data, true);
2875 void Spell::WriteAmmoToPacket( WorldPacket * data )
2877 uint32 ammoInventoryType = 0;
2878 uint32 ammoDisplayID = 0;
2880 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2882 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2883 if(pItem)
2885 ammoInventoryType = pItem->GetProto()->InventoryType;
2886 if( ammoInventoryType == INVTYPE_THROWN )
2887 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2888 else
2890 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2891 if(ammoID)
2893 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2894 if(pProto)
2896 ammoDisplayID = pProto->DisplayInfoID;
2897 ammoInventoryType = pProto->InventoryType;
2900 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
2902 ammoDisplayID = 5996; // normal arrow
2903 ammoInventoryType = INVTYPE_AMMO;
2908 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2910 *data << uint32(ammoDisplayID);
2911 *data << uint32(ammoInventoryType);
2914 void Spell::WriteSpellGoTargets( WorldPacket * data )
2916 *data << (uint8)m_countOfHit;
2917 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2918 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
2919 *data << uint64(ihit->targetGUID);
2921 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
2922 *data << uint64(ighit->targetGUID); // Always hits
2924 *data << (uint8)m_countOfMiss;
2925 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2927 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
2929 *data << uint64(ihit->targetGUID);
2930 *data << uint8(ihit->missCondition);
2931 if( ihit->missCondition == SPELL_MISS_REFLECT )
2932 *data << uint8(ihit->reflectResult);
2937 void Spell::SendLogExecute()
2939 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2941 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
2943 if(m_caster->GetTypeId() == TYPEID_PLAYER)
2944 data.append(m_caster->GetPackGUID());
2945 else
2946 data.append(target->GetPackGUID());
2948 data << uint32(m_spellInfo->Id);
2949 uint32 count1 = 1;
2950 data << uint32(count1); // count1 (effect count?)
2951 for(uint32 i = 0; i < count1; ++i)
2953 data << uint32(m_spellInfo->Effect[0]); // spell effect
2954 uint32 count2 = 1;
2955 data << uint32(count2); // count2 (target count?)
2956 for(uint32 j = 0; j < count2; ++j)
2958 switch(m_spellInfo->Effect[0])
2960 case SPELL_EFFECT_POWER_DRAIN:
2961 if(Unit *unit = m_targets.getUnitTarget())
2962 data.append(unit->GetPackGUID());
2963 else
2964 data << uint8(0);
2965 data << uint32(0);
2966 data << uint32(0);
2967 data << float(0);
2968 break;
2969 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
2970 if(Unit *unit = m_targets.getUnitTarget())
2971 data.append(unit->GetPackGUID());
2972 else
2973 data << uint8(0);
2974 data << uint32(0); // count?
2975 break;
2976 case SPELL_EFFECT_INTERRUPT_CAST:
2977 if(Unit *unit = m_targets.getUnitTarget())
2978 data.append(unit->GetPackGUID());
2979 else
2980 data << uint8(0);
2981 data << uint32(0); // spellid
2982 break;
2983 case SPELL_EFFECT_DURABILITY_DAMAGE:
2984 if(Unit *unit = m_targets.getUnitTarget())
2985 data.append(unit->GetPackGUID());
2986 else
2987 data << uint8(0);
2988 data << uint32(0);
2989 data << uint32(0);
2990 break;
2991 case SPELL_EFFECT_OPEN_LOCK:
2992 case SPELL_EFFECT_OPEN_LOCK_ITEM:
2993 if(Item *item = m_targets.getItemTarget())
2994 data.append(item->GetPackGUID());
2995 else
2996 data << uint8(0);
2997 break;
2998 case SPELL_EFFECT_CREATE_ITEM:
2999 case SPELL_EFFECT_157:
3000 data << uint32(m_spellInfo->EffectItemType[0]);
3001 break;
3002 case SPELL_EFFECT_SUMMON:
3003 case SPELL_EFFECT_TRANS_DOOR:
3004 case SPELL_EFFECT_SUMMON_PET:
3005 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3006 case SPELL_EFFECT_CREATE_HOUSE:
3007 case SPELL_EFFECT_DUEL:
3008 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3009 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3010 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3011 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3012 if(Unit *unit = m_targets.getUnitTarget())
3013 data.append(unit->GetPackGUID());
3014 else if(m_targets.getItemTargetGUID())
3015 data.appendPackGUID(m_targets.getItemTargetGUID());
3016 else if(GameObject *go = m_targets.getGOTarget())
3017 data.append(go->GetPackGUID());
3018 else
3019 data << uint8(0); // guid
3020 break;
3021 case SPELL_EFFECT_FEED_PET:
3022 data << uint32(m_targets.getItemTargetEntry());
3023 break;
3024 case SPELL_EFFECT_DISMISS_PET:
3025 if(Unit *unit = m_targets.getUnitTarget())
3026 data.append(unit->GetPackGUID());
3027 else
3028 data << uint8(0);
3029 break;
3030 case SPELL_EFFECT_RESURRECT:
3031 case SPELL_EFFECT_RESURRECT_NEW:
3032 if(Unit *unit = m_targets.getUnitTarget())
3033 data.append(unit->GetPackGUID());
3034 else
3035 data << uint8(0);
3036 break;
3037 default:
3038 return;
3043 m_caster->SendMessageToSet(&data, true);
3046 void Spell::SendInterrupted(uint8 result)
3048 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3049 data.append(m_caster->GetPackGUID());
3050 data << uint8(m_cast_count);
3051 data << uint32(m_spellInfo->Id);
3052 data << uint8(result);
3053 m_caster->SendMessageToSet(&data, true);
3055 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3056 data.append(m_caster->GetPackGUID());
3057 data << uint8(m_cast_count);
3058 data << uint32(m_spellInfo->Id);
3059 data << uint8(result);
3060 m_caster->SendMessageToSet(&data, true);
3063 void Spell::SendChannelUpdate(uint32 time)
3065 if(time == 0)
3067 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3068 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3071 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3072 return;
3074 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3075 data.append(m_caster->GetPackGUID());
3076 data << uint32(time);
3078 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3081 void Spell::SendChannelStart(uint32 duration)
3083 WorldObject* target = NULL;
3085 // select first not resisted target from target list for _0_ effect
3086 if(!m_UniqueTargetInfo.empty())
3088 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3090 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3092 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3093 break;
3097 else if(!m_UniqueGOTargetInfo.empty())
3099 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3101 if(itr->effectMask & (1<<0) )
3103 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3104 break;
3109 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3111 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3112 data.append(m_caster->GetPackGUID());
3113 data << uint32(m_spellInfo->Id);
3114 data << uint32(duration);
3116 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3119 m_timer = duration;
3120 if(target)
3121 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3122 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3125 void Spell::SendResurrectRequest(Player* target)
3127 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3128 // However, the packet structure differs slightly
3130 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3132 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3133 data << uint64(m_caster->GetGUID());
3134 data << uint32(strlen(sentName)+1);
3136 data << sentName;
3137 data << uint8(0);
3139 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3140 target->GetSession()->SendPacket(&data);
3143 void Spell::SendPlaySpellVisual(uint32 SpellID)
3145 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3146 return;
3148 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3149 data << uint64(m_caster->GetGUID());
3150 data << uint32(SpellID); // spell visual id?
3151 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3154 void Spell::TakeCastItem()
3156 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3157 return;
3159 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3160 if(m_IsTriggeredSpell)
3161 return;
3163 ItemPrototype const *proto = m_CastItem->GetProto();
3165 if(!proto)
3167 // This code is to avoid a crash
3168 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3169 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3170 return;
3173 bool expendable = false;
3174 bool withoutCharges = false;
3176 for (int i = 0; i<5; i++)
3178 if (proto->Spells[i].SpellId)
3180 // item has limited charges
3181 if (proto->Spells[i].SpellCharges)
3183 if (proto->Spells[i].SpellCharges < 0)
3184 expendable = true;
3186 int32 charges = m_CastItem->GetSpellCharges(i);
3188 // item has charges left
3189 if (charges)
3191 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3192 if (proto->Stackable < 2)
3193 m_CastItem->SetSpellCharges(i, charges);
3194 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3197 // all charges used
3198 withoutCharges = (charges == 0);
3203 if (expendable && withoutCharges)
3205 uint32 count = 1;
3206 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3208 // prevent crash at access to deleted m_targets.getItemTarget
3209 if(m_CastItem==m_targets.getItemTarget())
3210 m_targets.setItemTarget(NULL);
3212 m_CastItem = NULL;
3216 void Spell::TakePower()
3218 if(m_CastItem || m_triggeredByAuraSpell)
3219 return;
3221 // health as power used
3222 if(m_spellInfo->powerType == POWER_HEALTH)
3224 m_caster->ModifyHealth( -(int32)m_powerCost );
3225 return;
3228 if(m_spellInfo->powerType >= MAX_POWERS)
3230 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3231 return;
3234 Powers powerType = Powers(m_spellInfo->powerType);
3236 if(powerType == POWER_RUNE)
3238 TakeRunePower();
3239 return;
3242 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3244 // Set the five second timer
3245 if (powerType == POWER_MANA && m_powerCost > 0)
3246 m_caster->SetLastManaUse(getMSTime());
3249 uint8 Spell::CheckRuneCost(uint32 runeCostID)
3251 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3252 return 0;
3254 Player *plr = (Player*)m_caster;
3256 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3257 return 0;
3259 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3261 if(!src)
3262 return 0;
3264 if(src->NoRuneCost())
3265 return 0;
3267 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3269 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3271 runeCost[i] = src->RuneCost[i];
3274 runeCost[RUNE_DEATH] = 0; // calculated later
3276 for(uint32 i = 0; i < MAX_RUNES; ++i)
3278 uint8 rune = plr->GetCurrentRune(i);
3279 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3281 runeCost[rune]--;
3285 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3287 if(runeCost[i] > 0)
3289 runeCost[RUNE_DEATH] += runeCost[i];
3293 if(runeCost[RUNE_DEATH] > 0)
3294 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3296 return 0;
3299 void Spell::TakeRunePower()
3301 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3302 return;
3304 Player *plr = (Player*)m_caster;
3306 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3307 return;
3309 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3311 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3312 return;
3314 m_runesState = plr->GetRunesState(); // store previous state
3316 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3318 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3320 runeCost[i] = src->RuneCost[i];
3323 runeCost[RUNE_DEATH] = 0; // calculated later
3325 for(uint32 i = 0; i < MAX_RUNES; ++i)
3327 uint8 rune = plr->GetCurrentRune(i);
3328 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3330 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3331 runeCost[rune]--;
3335 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3337 if(runeCost[RUNE_DEATH] > 0)
3339 for(uint32 i = 0; i < MAX_RUNES; ++i)
3341 uint8 rune = plr->GetCurrentRune(i);
3342 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3344 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3345 runeCost[rune]--;
3346 plr->ConvertRune(i, plr->GetBaseRune(i));
3347 if(runeCost[RUNE_DEATH] == 0)
3348 break;
3353 // you can gain some runic power when use runes
3354 float rp = src->runePowerGain;;
3355 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3356 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3359 void Spell::TakeReagents()
3361 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3362 return;
3364 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3365 return;
3367 Player* p_caster = (Player*)m_caster;
3368 if (p_caster->CanNoReagentCast(m_spellInfo))
3369 return;
3371 for(uint32 x=0;x<8;x++)
3373 if(m_spellInfo->Reagent[x] <= 0)
3374 continue;
3376 uint32 itemid = m_spellInfo->Reagent[x];
3377 uint32 itemcount = m_spellInfo->ReagentCount[x];
3379 // if CastItem is also spell reagent
3380 if (m_CastItem)
3382 ItemPrototype const *proto = m_CastItem->GetProto();
3383 if( proto && proto->ItemId == itemid )
3385 for(int s=0;s<5;s++)
3387 // CastItem will be used up and does not count as reagent
3388 int32 charges = m_CastItem->GetSpellCharges(s);
3389 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3391 ++itemcount;
3392 break;
3396 m_CastItem = NULL;
3400 // if getItemTarget is also spell reagent
3401 if (m_targets.getItemTargetEntry()==itemid)
3402 m_targets.setItemTarget(NULL);
3404 p_caster->DestroyItemCount(itemid, itemcount, true);
3408 void Spell::HandleThreatSpells(uint32 spellId)
3410 if(!m_targets.getUnitTarget() || !spellId)
3411 return;
3413 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3414 return;
3416 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3417 if(!threatSpell)
3418 return;
3420 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3422 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3425 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3427 unitTarget = pUnitTarget;
3428 itemTarget = pItemTarget;
3429 gameObjTarget = pGOTarget;
3431 uint8 eff = m_spellInfo->Effect[i];
3432 uint32 mechanic = m_spellInfo->EffectMechanic[i];
3434 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3436 sLog.outDebug( "Spell: Effect : %u", eff);
3438 //Simply return. Do not display "immune" in red text on client
3439 if(unitTarget && unitTarget->IsImmunedToSpellEffect(eff, mechanic))
3440 return;
3442 if(eff<TOTAL_SPELL_EFFECTS)
3444 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3445 (*this.*SpellEffects[eff])(i);
3448 else
3450 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3451 if (m_CastItem)
3452 EffectEnchantItemTmp(i);
3453 else
3455 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3456 eff, m_spellInfo->Id);
3462 void Spell::TriggerSpell()
3464 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3466 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3467 spell->prepare(&m_targets); // use original spell original targets
3471 uint8 Spell::CanCast(bool strict)
3473 // check cooldowns to prevent cheating
3474 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3476 if(m_triggeredByAuraSpell)
3477 return SPELL_FAILED_DONT_REPORT;
3478 else
3479 return SPELL_FAILED_NOT_READY;
3482 // only allow triggered spells if at an ended battleground
3483 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3484 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3485 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3486 return SPELL_FAILED_DONT_REPORT;
3488 // only check at first call, Stealth auras are already removed at second call
3489 // for now, ignore triggered spells
3490 if( strict && !m_IsTriggeredSpell)
3492 bool checkForm = true;
3493 // Ignore form req aura
3494 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3495 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3497 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3498 continue;
3499 checkForm = false;
3500 break;
3502 if (checkForm)
3504 // Cannot be used in this stance/form
3505 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3506 return shapeError;
3508 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3509 return SPELL_FAILED_ONLY_STEALTHED;
3513 // caster state requirements
3514 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3515 return SPELL_FAILED_CASTER_AURASTATE;
3516 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3517 return SPELL_FAILED_CASTER_AURASTATE;
3519 // cancel autorepeat spells if cast start when moving
3520 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3521 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3523 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3524 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3525 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3526 return SPELL_FAILED_MOVING;
3529 Unit *target = m_targets.getUnitTarget();
3531 if(target)
3533 // target state requirements (not allowed state), apply to self also
3534 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3535 return SPELL_FAILED_TARGET_AURASTATE;
3537 if(target != m_caster)
3539 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3540 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3541 return SPELL_FAILED_TARGET_AURASTATE;
3543 // Not allow casting on flying player
3544 if (target->isInFlight())
3545 return SPELL_FAILED_BAD_TARGETS;
3547 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3548 return SPELL_FAILED_LINE_OF_SIGHT;
3550 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3551 // this case can be triggered if rank not found (too low-level target for first rank)
3552 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3554 for(int i=0;i<3;i++)
3556 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3557 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3558 return SPELL_FAILED_LOWLEVEL;
3563 // check pet presents
3564 for(int j=0;j<3;j++)
3566 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3568 target = m_caster->GetPet();
3569 if(!target)
3571 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3572 return SPELL_FAILED_DONT_REPORT;
3573 else
3574 return SPELL_FAILED_NO_PET;
3576 break;
3580 //check creature type
3581 //ignore self casts (including area casts when caster selected as target)
3582 if(target != m_caster)
3584 if(!CheckTargetCreatureType(target))
3586 if(target->GetTypeId()==TYPEID_PLAYER)
3587 return SPELL_FAILED_TARGET_IS_PLAYER;
3588 else
3589 return SPELL_FAILED_BAD_TARGETS;
3593 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3594 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3595 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3597 // check correctness positive/negative cast target (pet cast real check and cheating check)
3598 if(IsPositiveSpell(m_spellInfo->Id))
3600 if(m_caster->IsHostileTo(target))
3601 return SPELL_FAILED_BAD_TARGETS;
3603 else
3605 if(m_caster->IsFriendlyTo(target))
3606 return SPELL_FAILED_BAD_TARGETS;
3610 if(IsPositiveSpell(m_spellInfo->Id))
3612 if(target->IsImmunedToSpell(m_spellInfo,false))
3613 return SPELL_FAILED_TARGET_AURASTATE;
3616 //Must be behind the target.
3617 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3619 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3620 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3622 SendInterrupted(2);
3623 return SPELL_FAILED_NOT_BEHIND;
3627 //Target must be facing you.
3628 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3630 SendInterrupted(2);
3631 return SPELL_FAILED_NOT_INFRONT;
3634 // check if target is in combat
3635 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3637 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3640 // Spell casted only on battleground
3641 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3642 if(!((Player*)m_caster)->InBattleGround())
3643 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3645 // do not allow spells to be cast in arenas
3646 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3647 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3648 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3649 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3650 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3651 if(mapEntry->IsBattleArena())
3652 return SPELL_FAILED_NOT_IN_ARENA;
3654 // zone check
3655 if(uint8 res= GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3656 return res;
3658 // not let players cast spells at mount (and let do it to creatures)
3659 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3660 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3662 if(m_caster->isInFlight())
3663 return SPELL_FAILED_NOT_FLYING;
3664 else
3665 return SPELL_FAILED_NOT_MOUNTED;
3668 // always (except passive spells) check items (focus object can be required for any type casts)
3669 if(!IsPassiveSpell(m_spellInfo->Id))
3670 if(uint8 castResult = CheckItems())
3671 return castResult;
3673 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3674 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3676 for(uint8 j = 0; j < 3; j++)
3678 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3679 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3680 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3681 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3683 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3684 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3685 if(lower==upper)
3686 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);
3688 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3689 float range = GetSpellMaxRange(srange);
3691 Creature* creatureScriptTarget = NULL;
3692 GameObject* goScriptTarget = NULL;
3694 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3696 switch(i_spellST->second.type)
3698 case SPELL_TARGET_TYPE_GAMEOBJECT:
3700 GameObject* p_GameObject = NULL;
3702 if(i_spellST->second.targetEntry)
3704 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3705 Cell cell(p);
3706 cell.data.Part.reserved = ALL_DISTRICT;
3708 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3709 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
3711 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3712 CellLock<GridReadGuard> cell_lock(cell, p);
3713 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3715 if(p_GameObject)
3717 // remember found target and range, next attempt will find more near target with another entry
3718 creatureScriptTarget = NULL;
3719 goScriptTarget = p_GameObject;
3720 range = go_check.GetLastRange();
3723 else if( focusObject ) //Focus Object
3725 float frange = m_caster->GetDistance(focusObject);
3726 if(range >= frange)
3728 creatureScriptTarget = NULL;
3729 goScriptTarget = focusObject;
3730 range = frange;
3733 break;
3735 case SPELL_TARGET_TYPE_CREATURE:
3736 case SPELL_TARGET_TYPE_DEAD:
3737 default:
3739 Creature *p_Creature = NULL;
3741 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3742 Cell cell(p);
3743 cell.data.Part.reserved = ALL_DISTRICT;
3744 cell.SetNoCreate(); // Really don't know what is that???
3746 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3747 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
3749 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3751 CellLock<GridReadGuard> cell_lock(cell, p);
3752 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
3754 if(p_Creature )
3756 creatureScriptTarget = p_Creature;
3757 goScriptTarget = NULL;
3758 range = u_check.GetLastRange();
3760 break;
3765 if(creatureScriptTarget)
3767 // store coordinates for TARGET_SCRIPT_COORDINATES
3768 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3769 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3771 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3773 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3774 AddUnitTarget(creatureScriptTarget, j);
3776 // store explicit target for TARGET_SCRIPT
3777 else
3778 AddUnitTarget(creatureScriptTarget, j);
3780 else if(goScriptTarget)
3782 // store coordinates for TARGET_SCRIPT_COORDINATES
3783 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3784 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3786 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3788 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3789 AddGOTarget(goScriptTarget, j);
3791 // store explicit target for TARGET_SCRIPT
3792 else
3793 AddGOTarget(goScriptTarget, j);
3795 //Missing DB Entry or targets for this spellEffect.
3796 else
3798 // not report target not existence for triggered spells
3799 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3800 return SPELL_FAILED_DONT_REPORT;
3801 else
3802 return SPELL_FAILED_BAD_TARGETS;
3808 if(!m_triggeredByAuraSpell)
3809 if(uint8 castResult = CheckRange(strict))
3810 return castResult;
3813 if(uint8 castResult = CheckPower())
3814 return castResult;
3817 if(!m_triggeredByAuraSpell) // triggered spell not affected by stun/etc
3818 if(uint8 castResult = CheckCasterAuras())
3819 return castResult;
3821 for (int i = 0; i < 3; i++)
3823 // for effects of spells that have only one target
3824 switch(m_spellInfo->Effect[i])
3826 case SPELL_EFFECT_DUMMY:
3828 if(m_spellInfo->SpellIconID == 1648) // Execute
3830 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3831 return SPELL_FAILED_BAD_TARGETS;
3833 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
3835 if(m_caster->IsInWater())
3836 return SPELL_FAILED_ONLY_ABOVEWATER;
3838 else if(m_spellInfo->SpellIconID==156) // Holy Shock
3840 // spell different for friends and enemies
3841 // hart version required facing
3842 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3843 return SPELL_FAILED_UNIT_NOT_INFRONT;
3845 break;
3847 case SPELL_EFFECT_SCHOOL_DAMAGE:
3849 // Hammer of Wrath
3850 if(m_spellInfo->SpellVisual[0] == 7250)
3852 if (!m_targets.getUnitTarget())
3853 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3855 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3856 return SPELL_FAILED_BAD_TARGETS;
3858 break;
3860 case SPELL_EFFECT_TAMECREATURE:
3862 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3863 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3865 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3866 return SPELL_FAILED_HIGHLEVEL;
3868 // use SMSG_PET_TAME_FAILURE?
3869 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
3870 return SPELL_FAILED_BAD_TARGETS;
3872 if(m_caster->GetPetGUID())
3873 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3875 if(m_caster->GetCharmGUID())
3876 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3878 break;
3880 case SPELL_EFFECT_LEARN_SPELL:
3882 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
3883 break;
3885 Pet* pet = m_caster->GetPet();
3887 if(!pet)
3888 return SPELL_FAILED_NO_PET;
3890 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3892 if(!learn_spellproto)
3893 return SPELL_FAILED_NOT_KNOWN;
3895 if(m_spellInfo->spellLevel > pet->getLevel())
3896 return SPELL_FAILED_LOWLEVEL;
3898 break;
3900 case SPELL_EFFECT_LEARN_PET_SPELL:
3902 Pet* pet = m_caster->GetPet();
3904 if(!pet)
3905 return SPELL_FAILED_NO_PET;
3907 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3909 if(!learn_spellproto)
3910 return SPELL_FAILED_NOT_KNOWN;
3912 if(m_spellInfo->spellLevel > pet->getLevel())
3913 return SPELL_FAILED_LOWLEVEL;
3915 break;
3917 case SPELL_EFFECT_FEED_PET:
3919 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getItemTarget() )
3920 return SPELL_FAILED_BAD_TARGETS;
3922 Pet* pet = m_caster->GetPet();
3924 if(!pet)
3925 return SPELL_FAILED_NO_PET;
3927 if(!pet->HaveInDiet(m_targets.getItemTarget()->GetProto()))
3928 return SPELL_FAILED_WRONG_PET_FOOD;
3930 if(!pet->GetCurrentFoodBenefitLevel(m_targets.getItemTarget()->GetProto()->ItemLevel))
3931 return SPELL_FAILED_FOOD_LOWLEVEL;
3933 if(m_caster->isInCombat() || pet->isInCombat())
3934 return SPELL_FAILED_AFFECTING_COMBAT;
3936 break;
3938 case SPELL_EFFECT_POWER_BURN:
3939 case SPELL_EFFECT_POWER_DRAIN:
3941 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
3942 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3943 if(Unit* target = m_targets.getUnitTarget())
3944 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
3945 return SPELL_FAILED_BAD_TARGETS;
3946 break;
3948 case SPELL_EFFECT_CHARGE:
3950 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
3951 return SPELL_FAILED_ROOTED;
3953 break;
3955 case SPELL_EFFECT_SKINNING:
3957 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
3958 return SPELL_FAILED_BAD_TARGETS;
3960 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
3961 return SPELL_FAILED_TARGET_UNSKINNABLE;
3963 Creature* creature = (Creature*)m_targets.getUnitTarget();
3964 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
3966 return SPELL_FAILED_TARGET_NOT_LOOTED;
3969 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
3971 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
3972 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
3973 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
3974 if (ReqValue > skillValue)
3975 return SPELL_FAILED_LOW_CASTLEVEL;
3977 // chance for fail at orange skinning attempt
3978 if( (m_selfContainer && (*m_selfContainer) == this) &&
3979 skillValue < sWorld.GetConfigMaxSkillValue() &&
3980 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
3981 return SPELL_FAILED_TRY_AGAIN;
3983 break;
3985 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3986 case SPELL_EFFECT_OPEN_LOCK:
3988 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
3989 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
3990 break;
3992 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
3993 // we need a go target in case of TARGET_GAMEOBJECT
3994 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
3995 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
3996 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
3997 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
3998 return SPELL_FAILED_BAD_TARGETS;
4000 // In BattleGround players can use only flags and banners
4001 if( ((Player*)m_caster)->InBattleGround() &&
4002 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
4003 return SPELL_FAILED_TRY_AGAIN;
4005 // get the lock entry
4006 LockEntry const *lockInfo = NULL;
4007 if (GameObject* go=m_targets.getGOTarget())
4008 lockInfo = sLockStore.LookupEntry(go->GetLockId());
4009 else if(Item* itm=m_targets.getItemTarget())
4010 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
4012 // check lock compatibility
4013 if (lockInfo)
4015 // check for lock - key pair (checked by client also, just prevent cheating
4016 bool ok_key = false;
4017 for(int it = 0; it < 8; ++it)
4019 switch(lockInfo->Type[it])
4021 case LOCK_KEY_NONE:
4022 break;
4023 case LOCK_KEY_ITEM:
4025 if(lockInfo->Index[it])
4027 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4028 ok_key =true;
4029 break;
4032 case LOCK_KEY_SKILL:
4034 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->Index[it])
4035 break;
4037 switch(lockInfo->Index[it])
4039 case LOCKTYPE_HERBALISM:
4040 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
4041 ok_key =true;
4042 break;
4043 case LOCKTYPE_MINING:
4044 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
4045 ok_key =true;
4046 break;
4047 default:
4048 ok_key =true;
4049 break;
4053 if(ok_key)
4054 break;
4057 if(!ok_key)
4058 return SPELL_FAILED_BAD_TARGETS;
4061 // chance for fail at orange mining/herb/LockPicking gathering attempt
4062 if (!m_selfContainer || ((*m_selfContainer) != this))
4063 break;
4065 // get the skill value of the player
4066 int32 SkillValue = 0;
4067 bool canFailAtMax = true;
4068 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
4070 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
4071 canFailAtMax = false;
4073 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
4075 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
4076 canFailAtMax = false;
4078 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4079 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
4081 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
4082 if(m_CastItem)
4083 SkillValue = 0;
4085 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
4086 SkillValue += m_currentBasePoints[i]+1;
4088 // get the required lock value
4089 int32 ReqValue=0;
4090 if (lockInfo)
4092 // check for lock - key pair
4093 bool ok = false;
4094 for(int it = 0; it < 8; ++it)
4096 if(lockInfo->Type[it]==LOCK_KEY_ITEM && lockInfo->Index[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4098 // if so, we're good to go
4099 ok = true;
4100 break;
4103 if(ok)
4104 break;
4106 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4107 ReqValue = lockInfo->Skill[1];
4108 else
4109 ReqValue = lockInfo->Skill[0];
4112 // skill doesn't meet the required value
4113 if (ReqValue > SkillValue)
4114 return SPELL_FAILED_LOW_CASTLEVEL;
4116 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4117 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
4118 return SPELL_FAILED_TRY_AGAIN;
4120 break;
4122 case SPELL_EFFECT_SUMMON_DEAD_PET:
4124 Creature *pet = m_caster->GetPet();
4125 if(!pet)
4126 return SPELL_FAILED_NO_PET;
4128 if(pet->isAlive())
4129 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4131 break;
4133 // This is generic summon effect now and don't make this check for summon types similar
4134 // SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
4135 // These won't show up in m_caster->GetPetGUID()
4136 case SPELL_EFFECT_SUMMON:
4138 switch(m_spellInfo->EffectMiscValueB[i])
4140 case SUMMON_TYPE_POSESSED:
4141 case SUMMON_TYPE_POSESSED2:
4142 case SUMMON_TYPE_DEMON:
4143 case SUMMON_TYPE_SUMMON:
4145 if(m_caster->GetPetGUID())
4146 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4148 if(m_caster->GetCharmGUID())
4149 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4150 break;
4153 break;
4155 // Don't make this check for SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
4156 // These won't show up in m_caster->GetPetGUID()
4157 case SPELL_EFFECT_SUMMON_PHANTASM:
4158 case SPELL_EFFECT_SUMMON_DEMON:
4160 if(m_caster->GetPetGUID())
4161 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4163 if(m_caster->GetCharmGUID())
4164 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4166 break;
4168 case SPELL_EFFECT_SUMMON_PET:
4170 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4173 Pet* pet = ((Player*)m_caster)->GetPet();
4175 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4177 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4178 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4180 else
4181 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4184 if(m_caster->GetCharmGUID())
4185 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4187 break;
4189 case SPELL_EFFECT_SUMMON_PLAYER:
4191 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4192 return SPELL_FAILED_BAD_TARGETS;
4193 if(!((Player*)m_caster)->GetSelection())
4194 return SPELL_FAILED_BAD_TARGETS;
4196 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4197 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4198 return SPELL_FAILED_BAD_TARGETS;
4200 // check if our map is dungeon
4201 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4203 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4204 if(!instance)
4205 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4206 if ( instance->levelMin > target->getLevel() )
4207 return SPELL_FAILED_LOWLEVEL;
4208 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4209 return SPELL_FAILED_HIGHLEVEL;
4211 break;
4213 case SPELL_EFFECT_LEAP:
4214 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4216 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4217 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4218 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4219 // teleport a bit above terrain level to avoid falling below it
4220 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4221 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4222 return SPELL_FAILED_TRY_AGAIN;
4224 float caster_pos_z = m_caster->GetPositionZ();
4225 // Control the caster to not climb or drop when +-fz > 8
4226 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4227 return SPELL_FAILED_TRY_AGAIN;
4229 // not allow use this effect at battleground until battleground start
4230 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4231 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4232 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4233 return SPELL_FAILED_TRY_AGAIN;
4234 break;
4236 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4238 if (m_targets.getUnitTarget()==m_caster)
4239 return SPELL_FAILED_BAD_TARGETS;
4240 break;
4242 default:break;
4246 for (int i = 0; i < 3; i++)
4248 switch(m_spellInfo->EffectApplyAuraName[i])
4250 case SPELL_AURA_MOD_POSSESS:
4251 case SPELL_AURA_MOD_CHARM:
4253 if(m_caster->GetPetGUID())
4254 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4256 if(m_caster->GetCharmGUID())
4257 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4259 if(m_caster->GetCharmerGUID())
4260 return SPELL_FAILED_CHARMED;
4262 if(!m_targets.getUnitTarget())
4263 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4265 if(m_targets.getUnitTarget()->GetCharmerGUID())
4266 return SPELL_FAILED_CHARMED;
4268 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4269 return SPELL_FAILED_HIGHLEVEL;
4271 break;
4273 case SPELL_AURA_MOUNTED:
4275 if (m_caster->IsInWater())
4276 return SPELL_FAILED_ONLY_ABOVEWATER;
4278 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4279 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4281 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4282 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4283 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4285 ShapeshiftForm form = m_caster->m_form;
4286 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4287 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4288 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4289 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4290 return SPELL_FAILED_NOT_SHAPESHIFT;
4292 break;
4294 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4296 if(!m_targets.getUnitTarget())
4297 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4299 // can be casted at non-friendly unit or own pet/charm
4300 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4301 return SPELL_FAILED_TARGET_FRIENDLY;
4303 break;
4305 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4306 case SPELL_AURA_FLY:
4308 // not allow cast fly spells at old maps by players (all spells is self target)
4309 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4311 uint32 v_map = GetVirtualMapForMapAndZone(m_caster->GetMapId(), m_caster->GetZoneId());
4312 if( !((Player*)m_caster)->isGameMaster() && v_map != 530 && !(v_map == 571 && ((Player*)m_caster)->HasSpell(54197)))
4313 return SPELL_FAILED_NOT_HERE;
4316 break;
4318 case SPELL_AURA_PERIODIC_MANA_LEECH:
4320 if (!m_targets.getUnitTarget())
4321 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4323 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4324 break;
4326 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4327 return SPELL_FAILED_BAD_TARGETS;
4329 break;
4331 default:
4332 break;
4336 // all ok
4337 return 0;
4340 int16 Spell::PetCanCast(Unit* target)
4342 if(!m_caster->isAlive())
4343 return SPELL_FAILED_CASTER_DEAD;
4345 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4346 return SPELL_FAILED_SPELL_IN_PROGRESS;
4347 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4348 return SPELL_FAILED_AFFECTING_COMBAT;
4350 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4352 //dead owner (pets still alive when owners ressed?)
4353 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4354 return SPELL_FAILED_CASTER_DEAD;
4356 if(!target && m_targets.getUnitTarget())
4357 target = m_targets.getUnitTarget();
4359 bool need = false;
4360 for(uint32 i = 0;i<3;i++)
4362 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)
4364 need = true;
4365 if(!target)
4366 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4367 break;
4370 if(need)
4371 m_targets.setUnitTarget(target);
4373 Unit* _target = m_targets.getUnitTarget();
4375 if(_target) //for target dead/target not valid
4377 if(!_target->isAlive())
4378 return SPELL_FAILED_BAD_TARGETS;
4380 if(IsPositiveSpell(m_spellInfo->Id))
4382 if(m_caster->IsHostileTo(_target))
4383 return SPELL_FAILED_BAD_TARGETS;
4385 else
4387 bool duelvsplayertar = false;
4388 for(int j=0;j<3;j++)
4390 //TARGET_DUELVSPLAYER is positive AND negative
4391 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4393 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4395 return SPELL_FAILED_BAD_TARGETS;
4399 //cooldown
4400 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4401 return SPELL_FAILED_NOT_READY;
4404 uint16 result = CanCast(true);
4405 if(result != 0)
4406 return result;
4407 else
4408 return -1; //this allows to check spell fail 0, in combat
4411 uint8 Spell::CheckCasterAuras() const
4413 // Flag drop spells totally immuned to caster auras
4414 // FIXME: find more nice check for all totally immuned spells
4415 // AttributesEx3 & 0x10000000?
4416 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4417 return 0;
4419 uint8 school_immune = 0;
4420 uint32 mechanic_immune = 0;
4421 uint32 dispel_immune = 0;
4423 //Check if the spell grants school or mechanic immunity.
4424 //We use bitmasks so the loop is done only once and not on every aura check below.
4425 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4427 for(int i = 0;i < 3; i ++)
4429 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4430 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4431 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4432 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4433 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4434 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4436 //immune movement impairment and loss of control
4437 if(m_spellInfo->Id==(uint32)42292)
4438 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4441 //Check whether the cast should be prevented by any state you might have.
4442 uint8 prevented_reason = 0;
4443 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4444 if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4445 prevented_reason = SPELL_FAILED_STUNNED;
4446 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4447 prevented_reason = SPELL_FAILED_CONFUSED;
4448 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4449 prevented_reason = SPELL_FAILED_FLEEING;
4450 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4451 prevented_reason = SPELL_FAILED_SILENCED;
4452 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4453 prevented_reason = SPELL_FAILED_PACIFIED;
4455 // Attr must make flag drop spell totally immune from all effects
4456 if(prevented_reason)
4458 if(school_immune || mechanic_immune || dispel_immune)
4460 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4461 Unit::AuraMap const& auras = m_caster->GetAuras();
4462 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4464 if(itr->second)
4466 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4467 continue;
4468 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4469 continue;
4470 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4471 continue;
4473 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4474 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4475 switch(itr->second->GetModifier()->m_auraname)
4477 case SPELL_AURA_MOD_STUN:
4478 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4479 return SPELL_FAILED_STUNNED;
4480 break;
4481 case SPELL_AURA_MOD_CONFUSE:
4482 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4483 return SPELL_FAILED_CONFUSED;
4484 break;
4485 case SPELL_AURA_MOD_FEAR:
4486 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4487 return SPELL_FAILED_FLEEING;
4488 break;
4489 case SPELL_AURA_MOD_SILENCE:
4490 case SPELL_AURA_MOD_PACIFY:
4491 case SPELL_AURA_MOD_PACIFY_SILENCE:
4492 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4493 return SPELL_FAILED_PACIFIED;
4494 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4495 return SPELL_FAILED_SILENCED;
4496 break;
4501 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4502 else
4503 return prevented_reason;
4505 return 0; // all ok
4508 bool Spell::CanAutoCast(Unit* target)
4510 uint64 targetguid = target->GetGUID();
4512 for(uint32 j = 0;j<3;j++)
4514 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4516 if( m_spellInfo->StackAmount <= 1)
4518 if( target->HasAura(m_spellInfo->Id, j) )
4519 return false;
4521 else
4523 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4524 return false;
4527 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4529 if( target->HasAura(m_spellInfo->Id, j) )
4530 return false;
4534 int16 result = PetCanCast(target);
4536 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4538 FillTargetMap();
4539 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4540 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4541 if( ihit->targetGUID == targetguid )
4542 return true;
4544 return false; //target invalid
4547 uint8 Spell::CheckRange(bool strict)
4549 float range_mod;
4551 // self cast doesn't need range checking -- also for Starshards fix
4552 if (m_spellInfo->rangeIndex == 1) return 0;
4554 if (strict) //add radius of caster
4555 range_mod = 1.25;
4556 else //add radius of caster and ~5 yds "give"
4557 range_mod = 6.25;
4559 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4560 float max_range = GetSpellMaxRange(srange) + range_mod;
4561 float min_range = GetSpellMinRange(srange);
4563 if(Player* modOwner = m_caster->GetSpellModOwner())
4564 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4566 Unit *target = m_targets.getUnitTarget();
4568 if(target && target != m_caster)
4570 // distance from target center in checks
4571 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4572 if(dist > max_range)
4573 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4574 if(dist < min_range)
4575 return SPELL_FAILED_TOO_CLOSE;
4576 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4577 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4578 return SPELL_FAILED_UNIT_NOT_INFRONT;
4581 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4583 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4584 if(dist > max_range)
4585 return SPELL_FAILED_OUT_OF_RANGE;
4586 if(dist < min_range)
4587 return SPELL_FAILED_TOO_CLOSE;
4590 return 0; // ok
4593 int32 Spell::CalculatePowerCost()
4595 // item cast not used power
4596 if(m_CastItem)
4597 return 0;
4599 // Spell drain all exist power on cast (Only paladin lay of Hands)
4600 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4602 // If power type - health drain all
4603 if (m_spellInfo->powerType == POWER_HEALTH)
4604 return m_caster->GetHealth();
4605 // Else drain all power
4606 if (m_spellInfo->powerType < MAX_POWERS)
4607 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4608 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4609 return 0;
4612 // Base powerCost
4613 int32 powerCost = m_spellInfo->manaCost;
4614 // PCT cost from total amount
4615 if (m_spellInfo->ManaCostPercentage)
4617 switch (m_spellInfo->powerType)
4619 // health as power used
4620 case POWER_HEALTH:
4621 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4622 break;
4623 case POWER_MANA:
4624 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4625 break;
4626 case POWER_RAGE:
4627 case POWER_FOCUS:
4628 case POWER_ENERGY:
4629 case POWER_HAPPINESS:
4630 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4631 break;
4632 case POWER_RUNE:
4633 case POWER_RUNIC_POWER:
4634 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4635 break;
4636 default:
4637 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4638 return 0;
4641 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4642 // Flat mod from caster auras by spell school
4643 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4644 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4645 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4646 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4647 // Apply cost mod by spell
4648 if(Player* modOwner = m_caster->GetSpellModOwner())
4649 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4651 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4652 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4654 // PCT mod from user auras by school
4655 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4656 if (powerCost < 0)
4657 powerCost = 0;
4658 return powerCost;
4661 uint8 Spell::CheckPower()
4663 // item cast not used power
4664 if(m_CastItem)
4665 return 0;
4667 // health as power used - need check health amount
4668 if(m_spellInfo->powerType == POWER_HEALTH)
4670 if(m_caster->GetHealth() <= m_powerCost)
4671 return SPELL_FAILED_CASTER_AURASTATE;
4672 return 0;
4674 // Check valid power type
4675 if( m_spellInfo->powerType >= MAX_POWERS )
4677 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4678 return SPELL_FAILED_UNKNOWN;
4681 uint8 failReason = CheckRuneCost(m_spellInfo->runeCostID);
4682 if(failReason)
4683 return failReason;
4685 // Check power amount
4686 Powers powerType = Powers(m_spellInfo->powerType);
4687 if(m_caster->GetPower(powerType) < m_powerCost)
4688 return SPELL_FAILED_NO_POWER;
4689 else
4690 return 0;
4693 uint8 Spell::CheckItems()
4695 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4696 return 0;
4698 uint32 itemid, itemcount;
4699 Player* p_caster = (Player*)m_caster;
4701 if(m_CastItem)
4703 itemid = m_CastItem->GetEntry();
4704 if( !p_caster->HasItemCount(itemid,1) )
4705 return SPELL_FAILED_ITEM_NOT_READY;
4706 else
4708 ItemPrototype const *proto = m_CastItem->GetProto();
4709 if(!proto)
4710 return SPELL_FAILED_ITEM_NOT_READY;
4712 for (int i = 0; i<5; i++)
4714 if (proto->Spells[i].SpellCharges)
4716 if(m_CastItem->GetSpellCharges(i)==0)
4717 return SPELL_FAILED_NO_CHARGES_REMAIN;
4721 uint32 ItemClass = proto->Class;
4722 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4724 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4725 uint8 failReason = 0;
4726 for (int i = 0; i < 3; i++)
4728 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4729 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4730 continue;
4732 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4734 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4736 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4737 continue;
4739 else
4741 failReason = 0;
4742 break;
4746 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4747 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4749 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4751 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4752 continue;
4755 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4756 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4758 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4759 continue;
4761 else
4763 failReason = 0;
4764 break;
4768 if (failReason)
4769 return failReason;
4774 if(m_targets.getItemTargetGUID())
4776 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4777 return SPELL_FAILED_BAD_TARGETS;
4779 if(!m_targets.getItemTarget())
4780 return SPELL_FAILED_ITEM_GONE;
4782 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4783 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4785 // if not item target then required item must be equipped
4786 else
4788 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4789 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4792 if(m_spellInfo->RequiresSpellFocus)
4794 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4795 Cell cell(p);
4796 cell.data.Part.reserved = ALL_DISTRICT;
4798 GameObject* ok = NULL;
4799 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4800 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(ok,go_check);
4802 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4803 CellLock<GridReadGuard> cell_lock(cell, p);
4804 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4806 if(!ok)
4807 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4809 focusObject = ok; // game object found in range
4812 if (!p_caster->CanNoReagentCast(m_spellInfo))
4814 for(uint32 i=0;i<8;i++)
4816 if(m_spellInfo->Reagent[i] <= 0)
4817 continue;
4819 itemid = m_spellInfo->Reagent[i];
4820 itemcount = m_spellInfo->ReagentCount[i];
4822 // if CastItem is also spell reagent
4823 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4825 ItemPrototype const *proto = m_CastItem->GetProto();
4826 if(!proto)
4827 return SPELL_FAILED_ITEM_NOT_READY;
4828 for(int s=0;s<5;s++)
4830 // CastItem will be used up and does not count as reagent
4831 int32 charges = m_CastItem->GetSpellCharges(s);
4832 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4834 ++itemcount;
4835 break;
4839 if( !p_caster->HasItemCount(itemid,itemcount) )
4840 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
4844 uint32 totems = 2;
4845 for(int i=0;i<2;++i)
4847 if(m_spellInfo->Totem[i] != 0)
4849 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4851 totems -= 1;
4852 continue;
4854 }else
4855 totems -= 1;
4857 if(totems != 0)
4858 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
4860 //Check items for TotemCategory
4861 uint32 TotemCategory = 2;
4862 for(int i=0;i<2;++i)
4864 if(m_spellInfo->TotemCategory[i] != 0)
4866 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4868 TotemCategory -= 1;
4869 continue;
4872 else
4873 TotemCategory -= 1;
4875 if(TotemCategory != 0)
4876 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
4878 for(int i = 0; i < 3; i++)
4880 switch (m_spellInfo->Effect[i])
4882 case SPELL_EFFECT_CREATE_ITEM:
4884 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4886 ItemPosCountVec dest;
4887 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
4888 if (msg != EQUIP_ERR_OK )
4890 p_caster->SendEquipError( msg, NULL, NULL );
4891 return SPELL_FAILED_DONT_REPORT;
4894 break;
4896 case SPELL_EFFECT_ENCHANT_ITEM:
4898 Item* targetItem = m_targets.getItemTarget();
4899 if(!targetItem)
4900 return SPELL_FAILED_ITEM_NOT_FOUND;
4902 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
4903 return SPELL_FAILED_LOWLEVEL;
4904 // Not allow enchant in trade slot for some enchant type
4905 if( targetItem->GetOwner() != m_caster )
4907 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4908 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4909 if(!pEnchant)
4910 return SPELL_FAILED_ERROR;
4911 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4912 return SPELL_FAILED_NOT_TRADEABLE;
4914 break;
4916 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
4918 Item *item = m_targets.getItemTarget();
4919 if(!item)
4920 return SPELL_FAILED_ITEM_NOT_FOUND;
4921 // Not allow enchant in trade slot for some enchant type
4922 if( item->GetOwner() != m_caster )
4924 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4925 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4926 if(!pEnchant)
4927 return SPELL_FAILED_ERROR;
4928 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4929 return SPELL_FAILED_NOT_TRADEABLE;
4931 break;
4933 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
4934 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
4935 break;
4936 case SPELL_EFFECT_DISENCHANT:
4938 if(!m_targets.getItemTarget())
4939 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4941 // prevent disenchanting in trade slot
4942 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4943 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4945 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
4946 if(!itemProto)
4947 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4949 uint32 item_quality = itemProto->Quality;
4950 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
4951 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
4952 if (item_disenchantskilllevel == uint32(-1))
4953 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4954 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
4955 return SPELL_FAILED_LOW_CASTLEVEL;
4956 if(item_quality > 4 || item_quality < 2)
4957 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4958 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
4959 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4960 if (!itemProto->DisenchantID)
4961 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4962 break;
4964 case SPELL_EFFECT_PROSPECTING:
4966 if(!m_targets.getItemTarget())
4967 return SPELL_FAILED_CANT_BE_PROSPECTED;
4968 //ensure item is a prospectable ore
4969 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
4970 return SPELL_FAILED_CANT_BE_PROSPECTED;
4971 //prevent prospecting in trade slot
4972 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4973 return SPELL_FAILED_CANT_BE_PROSPECTED;
4974 //Check for enough skill in jewelcrafting
4975 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
4976 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
4977 return SPELL_FAILED_LOW_CASTLEVEL;
4978 //make sure the player has the required ores in inventory
4979 if(m_targets.getItemTarget()->GetCount() < 5)
4980 return SPELL_FAILED_NEED_MORE_ITEMS;
4982 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
4983 return SPELL_FAILED_CANT_BE_PROSPECTED;
4985 break;
4987 case SPELL_EFFECT_MILLING:
4989 if(!m_targets.getItemTarget())
4990 return SPELL_FAILED_CANT_BE_MILLED;
4991 //ensure item is a millable herb
4992 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
4993 return SPELL_FAILED_CANT_BE_MILLED;
4994 //prevent milling in trade slot
4995 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4996 return SPELL_FAILED_CANT_BE_MILLED;
4997 //Check for enough skill in inscription
4998 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
4999 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5000 return SPELL_FAILED_LOW_CASTLEVEL;
5001 //make sure the player has the required herbs in inventory
5002 if(m_targets.getItemTarget()->GetCount() < 5)
5003 return SPELL_FAILED_NEED_MORE_ITEMS;
5005 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5006 return SPELL_FAILED_CANT_BE_MILLED;
5008 break;
5010 case SPELL_EFFECT_WEAPON_DAMAGE:
5011 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5013 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5014 if( m_attackType != RANGED_ATTACK )
5015 break;
5016 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5017 if(!pItem || pItem->IsBroken())
5018 return SPELL_FAILED_EQUIPPED_ITEM;
5020 switch(pItem->GetProto()->SubClass)
5022 case ITEM_SUBCLASS_WEAPON_THROWN:
5024 uint32 ammo = pItem->GetEntry();
5025 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5026 return SPELL_FAILED_NO_AMMO;
5027 }; break;
5028 case ITEM_SUBCLASS_WEAPON_GUN:
5029 case ITEM_SUBCLASS_WEAPON_BOW:
5030 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5032 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5033 if(!ammo)
5035 // Requires No Ammo
5036 if(m_caster->GetDummyAura(46699))
5037 break; // skip other checks
5039 return SPELL_FAILED_NO_AMMO;
5042 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5043 if(!ammoProto)
5044 return SPELL_FAILED_NO_AMMO;
5046 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5047 return SPELL_FAILED_NO_AMMO;
5049 // check ammo ws. weapon compatibility
5050 switch(pItem->GetProto()->SubClass)
5052 case ITEM_SUBCLASS_WEAPON_BOW:
5053 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5054 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5055 return SPELL_FAILED_NO_AMMO;
5056 break;
5057 case ITEM_SUBCLASS_WEAPON_GUN:
5058 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5059 return SPELL_FAILED_NO_AMMO;
5060 break;
5061 default:
5062 return SPELL_FAILED_NO_AMMO;
5065 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5066 return SPELL_FAILED_NO_AMMO;
5067 }; break;
5068 case ITEM_SUBCLASS_WEAPON_WAND:
5069 default:
5070 break;
5072 break;
5074 default:break;
5078 return uint8(0);
5081 void Spell::Delayed()
5083 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5084 return;
5086 if (m_spellState == SPELL_STATE_DELAYED)
5087 return; // spell is active and can't be time-backed
5089 // spells not loosing casting time ( slam, dynamites, bombs.. )
5090 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5091 return;
5093 //check resist chance
5094 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5095 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5096 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5097 if (roll_chance_i(resistChance))
5098 return;
5100 int32 delaytime = GetNextDelayAtDamageMsTime();
5102 if(int32(m_timer) + delaytime > m_casttime)
5104 delaytime = m_casttime - m_timer;
5105 m_timer = m_casttime;
5107 else
5108 m_timer += delaytime;
5110 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5112 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5113 data.append(m_caster->GetPackGUID());
5114 data << uint32(delaytime);
5116 m_caster->SendMessageToSet(&data,true);
5119 void Spell::DelayedChannel()
5121 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5122 return;
5124 //check resist chance
5125 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5126 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5127 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5128 if (roll_chance_i(resistChance))
5129 return;
5131 int32 delaytime = GetNextDelayAtDamageMsTime();
5133 if(int32(m_timer) < delaytime)
5135 delaytime = m_timer;
5136 m_timer = 0;
5138 else
5139 m_timer -= delaytime;
5141 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5143 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5145 if ((*ihit).missCondition == SPELL_MISS_NONE)
5147 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5148 if (unit)
5150 for (int j=0;j<3;j++)
5151 if( ihit->effectMask & (1<<j) )
5152 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5158 for(int j = 0; j < 3; j++)
5160 // partially interrupt persistent area auras
5161 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5162 if(dynObj)
5163 dynObj->Delay(delaytime);
5166 SendChannelUpdate(m_timer);
5169 void Spell::UpdatePointers()
5171 if(m_originalCasterGUID==m_caster->GetGUID())
5172 m_originalCaster = m_caster;
5173 else
5175 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5176 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5179 m_targets.Update(m_caster);
5182 bool Spell::IsAffectedByAura(Aura *aura)
5184 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5187 bool Spell::CheckTargetCreatureType(Unit* target) const
5189 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5191 // Curse of Doom : not find another way to fix spell target check :/
5192 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5194 // not allow cast at player
5195 if(target->GetTypeId()==TYPEID_PLAYER)
5196 return false;
5198 spellCreatureTargetMask = 0x7FF;
5201 // Dismiss Pet and Taming Lesson skipped
5202 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5203 spellCreatureTargetMask = 0;
5205 if (spellCreatureTargetMask)
5207 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5209 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5211 return true;
5214 CurrentSpellTypes Spell::GetCurrentContainer()
5216 if (IsNextMeleeSwingSpell())
5217 return(CURRENT_MELEE_SPELL);
5218 else if (IsAutoRepeat())
5219 return(CURRENT_AUTOREPEAT_SPELL);
5220 else if (IsChanneledSpell(m_spellInfo))
5221 return(CURRENT_CHANNELED_SPELL);
5222 else
5223 return(CURRENT_GENERIC_SPELL);
5226 bool Spell::CheckTarget( Unit* target, uint32 eff )
5228 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5229 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5231 if (!CheckTargetCreatureType(target))
5232 return false;
5235 // Check targets for not_selectable unit flag and remove
5236 // A player can cast spells on his pet (or other controlled unit) though in any state
5237 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5239 // any unattackable target skipped
5240 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5241 return false;
5243 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5244 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5245 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5246 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5247 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5248 return false;
5251 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5252 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5254 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5255 return false;
5257 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5258 return false;
5261 //Check targets for LOS visibility (except spells without range limitations )
5262 switch(m_spellInfo->Effect[eff])
5264 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5265 break;
5266 case SPELL_EFFECT_DUMMY:
5267 if(m_spellInfo->Id!=20577) // Cannibalize
5268 break;
5269 //fall through
5270 case SPELL_EFFECT_RESURRECT_NEW:
5271 // player far away, maybe his corpse near?
5272 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5274 if(!m_targets.getCorpseTargetGUID())
5275 return false;
5277 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5278 if(!corpse)
5279 return false;
5281 if(target->GetGUID()!=corpse->GetOwnerGUID())
5282 return false;
5284 if(!corpse->IsWithinLOSInMap(m_caster))
5285 return false;
5288 // all ok by some way or another, skip normal check
5289 break;
5290 default: // normal case
5291 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5292 return false;
5293 break;
5296 return true;
5299 Unit* Spell::SelectMagnetTarget()
5301 Unit* target = m_targets.getUnitTarget();
5303 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
5305 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
5306 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
5308 if(Unit* magnet = (*itr)->GetCaster())
5310 if(magnet->IsWithinLOSInMap(m_caster))
5312 target = magnet;
5313 m_targets.setUnitTarget(target);
5314 break;
5320 return target;
5323 bool Spell::IsNeedSendToClient() const
5325 return m_spellInfo->SpellVisual!=0 || IsChanneledSpell(m_spellInfo) ||
5326 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5329 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5331 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5332 if(itr->effectMask & (1<<effect))
5333 return true;
5335 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5336 if(itr->effectMask & (1<<effect))
5337 return true;
5339 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5340 if(itr->effectMask & (1<<effect))
5341 return true;
5343 return false;
5346 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5348 m_Spell = spell;
5351 SpellEvent::~SpellEvent()
5353 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5354 m_Spell->cancel();
5356 if (m_Spell->IsDeletable())
5358 delete m_Spell;
5360 else
5362 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5363 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5367 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5369 // update spell if it is not finished
5370 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5371 m_Spell->update(p_time);
5373 // check spell state to process
5374 switch (m_Spell->getState())
5376 case SPELL_STATE_FINISHED:
5378 // spell was finished, check deletable state
5379 if (m_Spell->IsDeletable())
5381 // check, if we do have unfinished triggered spells
5383 return(true); // spell is deletable, finish event
5385 // event will be re-added automatically at the end of routine)
5386 } break;
5388 case SPELL_STATE_CASTING:
5390 // this spell is in channeled state, process it on the next update
5391 // event will be re-added automatically at the end of routine)
5392 } break;
5394 case SPELL_STATE_DELAYED:
5396 // first, check, if we have just started
5397 if (m_Spell->GetDelayStart() != 0)
5399 // no, we aren't, do the typical update
5400 // check, if we have channeled spell on our hands
5401 if (IsChanneledSpell(m_Spell->m_spellInfo))
5403 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5404 // check, if we have casting anything else except this channeled spell and autorepeat
5405 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5407 // another non-melee non-delayed spell is casted now, abort
5408 m_Spell->cancel();
5410 else
5412 // do the action (pass spell to channeling state)
5413 m_Spell->handle_immediate();
5415 // event will be re-added automatically at the end of routine)
5417 else
5419 // run the spell handler and think about what we can do next
5420 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5421 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5422 if (n_offset)
5424 // re-add us to the queue
5425 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5426 return(false); // event not complete
5428 // event complete
5429 // finish update event will be re-added automatically at the end of routine)
5432 else
5434 // delaying had just started, record the moment
5435 m_Spell->SetDelayStart(e_time);
5436 // re-plan the event for the delay moment
5437 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5438 return(false); // event not complete
5440 } break;
5442 default:
5444 // all other states
5445 // event will be re-added automatically at the end of routine)
5446 } break;
5449 // spell processing not complete, plan event on the next update interval
5450 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5451 return(false); // event not complete
5454 void SpellEvent::Abort(uint64 /*e_time*/)
5456 // oops, the spell we try to do is aborted
5457 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5458 m_Spell->cancel();
5461 bool SpellEvent::IsDeletable() const
5463 return m_Spell->IsDeletable();