[7160] Implement (un-)learning skill level dependent spells at skill level change.
[getmangos.git] / src / game / Spell.cpp
blob070c19a73b2548eb8cfe36dcf41944e1ec533bdb
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "SpellAuras.h"
37 #include "Group.h"
38 #include "UpdateData.h"
39 #include "MapManager.h"
40 #include "ObjectAccessor.h"
41 #include "CellImpl.h"
42 #include "Policies/SingletonImp.h"
43 #include "SharedDefines.h"
44 #include "LootMgr.h"
45 #include "VMapFactory.h"
46 #include "BattleGround.h"
47 #include "Util.h"
49 #define SPELL_CHANNEL_UPDATE_INTERVAL 1000
51 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
53 bool IsQuestTameSpell(uint32 spellId)
55 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
56 if (!spellproto) return false;
58 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
59 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
62 SpellCastTargets::SpellCastTargets()
64 m_unitTarget = NULL;
65 m_itemTarget = NULL;
66 m_GOTarget = NULL;
68 m_unitTargetGUID = 0;
69 m_GOTargetGUID = 0;
70 m_CorpseTargetGUID = 0;
71 m_itemTargetGUID = 0;
72 m_itemTargetEntry = 0;
74 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
75 m_strTarget = "";
76 m_targetMask = 0;
79 SpellCastTargets::~SpellCastTargets()
83 void SpellCastTargets::setUnitTarget(Unit *target)
85 if (!target)
86 return;
88 m_destX = target->GetPositionX();
89 m_destY = target->GetPositionY();
90 m_destZ = target->GetPositionZ();
91 m_unitTarget = target;
92 m_unitTargetGUID = target->GetGUID();
93 m_targetMask |= TARGET_FLAG_UNIT;
96 void SpellCastTargets::setDestination(float x, float y, float z)
98 m_destX = x;
99 m_destY = y;
100 m_destZ = z;
101 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
104 void SpellCastTargets::setSource(float x, float y, float z)
106 m_srcX = x;
107 m_srcY = y;
108 m_srcZ = z;
109 m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
112 void SpellCastTargets::setGOTarget(GameObject *target)
114 m_GOTarget = target;
115 m_GOTargetGUID = target->GetGUID();
116 // m_targetMask |= TARGET_FLAG_OBJECT;
119 void SpellCastTargets::setItemTarget(Item* item)
121 if(!item)
122 return;
124 m_itemTarget = item;
125 m_itemTargetGUID = item->GetGUID();
126 m_itemTargetEntry = item->GetEntry();
127 m_targetMask |= TARGET_FLAG_ITEM;
130 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
132 m_CorpseTargetGUID = corpse->GetGUID();
135 void SpellCastTargets::Update(Unit* caster)
137 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
138 m_unitTarget = m_unitTargetGUID ?
139 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
140 NULL;
142 m_itemTarget = NULL;
143 if(caster->GetTypeId()==TYPEID_PLAYER)
145 if(m_targetMask & TARGET_FLAG_ITEM)
146 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
147 else
149 Player* pTrader = ((Player*)caster)->GetTrader();
150 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
151 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
153 if(m_itemTarget)
154 m_itemTargetEntry = m_itemTarget->GetEntry();
158 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
160 if(data->rpos()+4 > data->size())
161 return false;
163 *data >> m_targetMask;
165 if(m_targetMask == TARGET_FLAG_SELF)
167 m_destX = caster->GetPositionX();
168 m_destY = caster->GetPositionY();
169 m_destZ = caster->GetPositionZ();
170 m_unitTarget = caster;
171 m_unitTargetGUID = caster->GetGUID();
172 return true;
175 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
176 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
177 if(!data->readPackGUID(m_unitTargetGUID))
178 return false;
180 if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ))
181 if(!data->readPackGUID(m_GOTargetGUID))
182 return false;
184 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
185 if(!data->readPackGUID(m_itemTargetGUID))
186 return false;
188 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
190 if(data->rpos()+4+4+4 > data->size())
191 return false;
193 *data >> m_srcX >> m_srcY >> m_srcZ;
194 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
195 return false;
198 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
200 if(data->rpos()+4+4+4 > data->size())
201 return false;
203 *data >> m_destX >> m_destY >> m_destZ;
204 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
205 return false;
208 if( m_targetMask & TARGET_FLAG_STRING )
210 if(data->rpos()+1 > data->size())
211 return false;
213 *data >> m_strTarget;
216 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
217 if(!data->readPackGUID(m_CorpseTargetGUID))
218 return false;
220 // find real units/GOs
221 Update(caster);
222 return true;
225 void SpellCastTargets::write ( WorldPacket * data )
227 *data << uint32(m_targetMask);
229 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
231 if(m_targetMask & TARGET_FLAG_UNIT)
233 if(m_unitTarget)
234 data->append(m_unitTarget->GetPackGUID());
235 else
236 *data << uint8(0);
238 else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
240 if(m_GOTarget)
241 data->append(m_GOTarget->GetPackGUID());
242 else
243 *data << uint8(0);
245 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
246 data->appendPackGUID(m_CorpseTargetGUID);
247 else
248 *data << uint8(0);
251 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
253 if(m_itemTarget)
254 data->append(m_itemTarget->GetPackGUID());
255 else
256 *data << uint8(0);
259 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
260 *data << m_srcX << m_srcY << m_srcZ;
262 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
263 *data << m_destX << m_destY << m_destZ;
265 if( m_targetMask & TARGET_FLAG_STRING )
266 *data << m_strTarget;
269 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
271 ASSERT( Caster != NULL && info != NULL );
272 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
274 m_spellInfo = info;
275 m_caster = Caster;
276 m_selfContainer = NULL;
277 m_triggeringContainer = triggeringContainer;
278 m_referencedFromCurrentSpell = false;
279 m_executedCurrently = false;
280 m_delayStart = 0;
281 m_delayAtDamageCount = 0;
283 m_applyMultiplierMask = 0;
285 // Get data for type of attack
286 switch (m_spellInfo->DmgClass)
288 case SPELL_DAMAGE_CLASS_MELEE:
289 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
290 m_attackType = OFF_ATTACK;
291 else
292 m_attackType = BASE_ATTACK;
293 break;
294 case SPELL_DAMAGE_CLASS_RANGED:
295 m_attackType = RANGED_ATTACK;
296 break;
297 default:
298 // Wands
299 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
300 m_attackType = RANGED_ATTACK;
301 else
302 m_attackType = BASE_ATTACK;
303 break;
306 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
308 if(m_attackType == RANGED_ATTACK)
310 // wand case
311 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
313 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
314 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
317 // Set health leech amount to zero
318 m_healthLeech = 0;
320 if(originalCasterGUID)
321 m_originalCasterGUID = originalCasterGUID;
322 else
323 m_originalCasterGUID = m_caster->GetGUID();
325 if(m_originalCasterGUID==m_caster->GetGUID())
326 m_originalCaster = m_caster;
327 else
329 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
330 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
333 for(int i=0; i <3; ++i)
334 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
336 m_spellState = SPELL_STATE_NULL;
338 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
339 m_TriggerSpells.clear();
340 m_IsTriggeredSpell = triggered;
341 //m_AreaAura = false;
342 m_CastItem = NULL;
344 unitTarget = NULL;
345 itemTarget = NULL;
346 gameObjTarget = NULL;
347 focusObject = NULL;
348 m_cast_count = 0;
349 m_glyphIndex = 0;
350 m_triggeredByAuraSpell = NULL;
352 //Auto Shot & Shoot (wand)
353 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
355 m_runesState = 0;
356 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
357 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
358 m_timer = 0; // will set to castime in prepare
360 m_needAliveTargetMask = 0;
362 // determine reflection
363 m_canReflect = false;
365 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
367 for(int j=0;j<3;j++)
369 if (m_spellInfo->Effect[j]==0)
370 continue;
372 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
373 m_canReflect = true;
374 else
375 m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
377 if(m_canReflect)
378 continue;
379 else
380 break;
384 CleanupTargetList();
387 Spell::~Spell()
391 void Spell::FillTargetMap()
393 // TODO: ADD the correct target FILLS!!!!!!
395 for(uint32 i=0;i<3;i++)
397 // not call for empty effect.
398 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
399 if(m_spellInfo->Effect[i]==0)
400 continue;
402 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
403 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
404 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
405 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
406 continue;
408 // TODO: find a way so this is not needed?
409 // for area auras always add caster as target (needed for totems for example)
410 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
411 AddUnitTarget(m_caster, i);
413 std::list<Unit*> tmpUnitMap;
415 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
416 // but need it support in some know cases
417 switch(m_spellInfo->EffectImplicitTargetA[i])
419 case TARGET_CASTER_COORDINATES:
420 // Note: this hack with search required until GO casting not implemented
421 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
422 // currently each enemy selected explicitly and self cast damage
423 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
425 if(m_targets.getUnitTarget())
426 tmpUnitMap.push_back(m_targets.getUnitTarget());
428 else
430 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
431 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
433 break;
434 case TARGET_TABLE_X_Y_Z_COORDINATES:
435 // Only if target A, for target B (used in teleports) dest select in effect
436 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
437 break;
438 default:
439 switch(m_spellInfo->EffectImplicitTargetB[i])
441 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
442 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
443 break;
444 default:
445 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
446 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
447 break;
449 break;
452 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
453 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
455 // add here custom effects that need default target.
456 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
457 switch(m_spellInfo->Effect[i])
459 case SPELL_EFFECT_DUMMY:
461 switch(m_spellInfo->Id)
463 case 20577: // Cannibalize
465 // non-standard target selection
466 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
467 float max_range = GetSpellMaxRange(srange);
469 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
470 Cell cell(p);
471 cell.data.Part.reserved = ALL_DISTRICT;
472 cell.SetNoCreate();
474 WorldObject* result = NULL;
476 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
477 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(result, u_check);
479 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
480 CellLock<GridReadGuard> cell_lock(cell, p);
481 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
483 if(!result)
485 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
486 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
489 if(result)
491 switch(result->GetTypeId())
493 case TYPEID_UNIT:
494 case TYPEID_PLAYER:
495 tmpUnitMap.push_back((Unit*)result);
496 break;
497 case TYPEID_CORPSE:
498 m_targets.setCorpseTarget((Corpse*)result);
499 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
500 tmpUnitMap.push_back(owner);
501 break;
504 else
506 // clear cooldown at fail
507 if(m_caster->GetTypeId()==TYPEID_PLAYER)
509 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
511 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
512 data << uint32(m_spellInfo->Id);
513 data << uint64(m_caster->GetGUID());
514 ((Player*)m_caster)->GetSession()->SendPacket(&data);
517 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
518 finish(false);
520 break;
522 default:
523 if(m_targets.getUnitTarget())
524 tmpUnitMap.push_back(m_targets.getUnitTarget());
525 break;
527 break;
529 case SPELL_EFFECT_RESURRECT:
530 case SPELL_EFFECT_PARRY:
531 case SPELL_EFFECT_BLOCK:
532 case SPELL_EFFECT_CREATE_ITEM:
533 case SPELL_EFFECT_TRIGGER_SPELL:
534 case SPELL_EFFECT_TRIGGER_MISSILE:
535 case SPELL_EFFECT_LEARN_SPELL:
536 case SPELL_EFFECT_SKILL_STEP:
537 case SPELL_EFFECT_PROFICIENCY:
538 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
539 case SPELL_EFFECT_SELF_RESURRECT:
540 case SPELL_EFFECT_REPUTATION:
541 if(m_targets.getUnitTarget())
542 tmpUnitMap.push_back(m_targets.getUnitTarget());
543 break;
544 case SPELL_EFFECT_SUMMON_PLAYER:
545 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
547 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
548 if(target)
549 tmpUnitMap.push_back(target);
551 break;
552 case SPELL_EFFECT_RESURRECT_NEW:
553 if(m_targets.getUnitTarget())
554 tmpUnitMap.push_back(m_targets.getUnitTarget());
555 if(m_targets.getCorpseTargetGUID())
557 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
558 if(corpse)
560 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
561 if(owner)
562 tmpUnitMap.push_back(owner);
565 break;
566 case SPELL_EFFECT_SUMMON:
567 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
569 if(m_targets.getUnitTarget())
570 tmpUnitMap.push_back(m_targets.getUnitTarget());
572 else
573 tmpUnitMap.push_back(m_caster);
574 break;
575 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
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_FEED_PET:
581 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
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_PROSPECTING:
593 case SPELL_EFFECT_MILLING:
594 if(m_targets.getItemTarget())
595 AddItemTarget(m_targets.getItemTarget(), i);
596 break;
597 case SPELL_EFFECT_APPLY_AURA:
598 switch(m_spellInfo->EffectApplyAuraName[i])
600 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)
601 case SPELL_AURA_ADD_PCT_MODIFIER:
602 tmpUnitMap.push_back(m_caster);
603 break;
604 default: // apply to target in other case
605 if(m_targets.getUnitTarget())
606 tmpUnitMap.push_back(m_targets.getUnitTarget());
607 break;
609 break;
610 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
611 // AreaAura
612 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
613 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
614 break;
615 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
616 if(m_targets.getUnitTarget())
618 tmpUnitMap.push_back(m_targets.getUnitTarget());
620 else if (m_targets.getCorpseTargetGUID())
622 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
623 if(corpse)
625 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
626 if(owner)
627 tmpUnitMap.push_back(owner);
630 break;
631 default:
632 break;
635 if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
636 m_needAliveTargetMask |= (1<<i);
638 if(m_caster->GetTypeId() == TYPEID_PLAYER)
640 Player *me = (Player*)m_caster;
641 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
643 Unit *owner = (*itr)->GetOwner();
644 Unit *u = owner ? owner : (*itr);
645 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
647 me->UpdatePvP(true);
648 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
649 break;
654 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
656 if (!CheckTarget (*itr, i))
658 itr = tmpUnitMap.erase(itr);
659 continue;
661 else
662 ++itr;
665 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
666 AddUnitTarget((*iunit), i);
670 void Spell::prepareDataForTriggerSystem()
672 //==========================================================================================
673 // Now fill data for trigger system, need know:
674 // Ñan spell trigger another or not ( m_canTrigger )
675 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
676 //==========================================================================================
677 // Fill flag can spell trigger or not
678 // TODO: possible exist spell attribute for this
679 m_canTrigger = false;
681 if (m_CastItem)
682 m_canTrigger = false; // Do not trigger from item cast spell
683 else if (!m_IsTriggeredSpell)
684 m_canTrigger = true; // Normal cast - can trigger
685 else if (!m_triggeredByAuraSpell)
686 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
688 if (!m_canTrigger) // Exceptions (some periodic triggers)
690 switch (m_spellInfo->SpellFamilyName)
692 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
693 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
694 break;
695 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
696 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
697 break;
698 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
699 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
700 break;
701 case SPELLFAMILY_ROGUE: // For poisons need do it
702 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
703 break;
704 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot
705 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000214LL ||
706 m_spellInfo->SpellFamilyFlags2 & 0x200) m_canTrigger = true;
707 break;
708 case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it
709 if (m_spellInfo->SpellFamilyFlags & 0x0001000900B80400LL) m_canTrigger = true;
710 break;
714 // Get data for type of attack and fill base info for trigger
715 switch (m_spellInfo->DmgClass)
717 case SPELL_DAMAGE_CLASS_MELEE:
718 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
719 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
720 break;
721 case SPELL_DAMAGE_CLASS_RANGED:
722 // Auto attack
723 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
725 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
726 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
728 else // Ranged spell attack
730 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
731 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
733 break;
734 default:
735 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
737 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
738 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
740 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
742 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
743 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
745 else // Negative spell
747 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
748 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
750 break;
752 // Hunter traps spells (for Entrapment trigger)
753 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
754 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x0000200000000014LL)
755 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
758 void Spell::CleanupTargetList()
760 m_UniqueTargetInfo.clear();
761 m_UniqueGOTargetInfo.clear();
762 m_UniqueItemInfo.clear();
763 m_delayMoment = 0;
766 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
768 if( m_spellInfo->Effect[effIndex]==0 )
769 return;
771 // Check for effect immune skip if immuned
772 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
774 uint64 targetGUID = pVictim->GetGUID();
776 // Lookup target in already in list
777 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
779 if (targetGUID == ihit->targetGUID) // Found in list
781 if (!immuned)
782 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
783 return;
787 // This is new target calculate data for him
789 // Get spell hit result on target
790 TargetInfo target;
791 target.targetGUID = targetGUID; // Store target GUID
792 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
793 target.processed = false; // Effects not apply on target
795 // Calculate hit result
796 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
798 // Spell have speed - need calculate incoming time
799 if (m_spellInfo->speed > 0.0f)
801 // calculate spell incoming interval
802 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
803 if (dist < 5.0f) dist = 5.0f;
804 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
806 // Calculate minimum incoming time
807 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
808 m_delayMoment = target.timeDelay;
810 else
811 target.timeDelay = 0LL;
813 // If target reflect spell back to caster
814 if (target.missCondition==SPELL_MISS_REFLECT)
816 // Calculate reflected spell result on caster
817 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
819 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
820 target.reflectResult = SPELL_MISS_PARRY;
822 // Increase time interval for reflected spells by 1.5
823 target.timeDelay+=target.timeDelay>>1;
825 else
826 target.reflectResult = SPELL_MISS_NONE;
828 // Add target to list
829 m_UniqueTargetInfo.push_back(target);
832 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
834 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
835 if (unit)
836 AddUnitTarget(unit, effIndex);
839 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
841 if( m_spellInfo->Effect[effIndex]==0 )
842 return;
844 uint64 targetGUID = pVictim->GetGUID();
846 // Lookup target in already in list
847 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
849 if (targetGUID == ihit->targetGUID) // Found in list
851 ihit->effectMask |= 1<<effIndex; // Add only effect mask
852 return;
856 // This is new target calculate data for him
858 GOTargetInfo target;
859 target.targetGUID = targetGUID;
860 target.effectMask = 1<<effIndex;
861 target.processed = false; // Effects not apply on target
863 // Spell have speed - need calculate incoming time
864 if (m_spellInfo->speed > 0.0f)
866 // calculate spell incoming interval
867 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
868 if (dist < 5.0f) dist = 5.0f;
869 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
870 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
871 m_delayMoment = target.timeDelay;
873 else
874 target.timeDelay = 0LL;
876 // Add target to list
877 m_UniqueGOTargetInfo.push_back(target);
880 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
882 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
883 if (go)
884 AddGOTarget(go, effIndex);
887 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
889 if( m_spellInfo->Effect[effIndex]==0 )
890 return;
892 // Lookup target in already in list
893 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
895 if (pitem == ihit->item) // Found in list
897 ihit->effectMask |= 1<<effIndex; // Add only effect mask
898 return;
902 // This is new target add data
904 ItemTargetInfo target;
905 target.item = pitem;
906 target.effectMask = 1<<effIndex;
907 m_UniqueItemInfo.push_back(target);
910 void Spell::DoAllEffectOnTarget(TargetInfo *target)
912 if (target->processed) // Check target
913 return;
914 target->processed = true; // Target checked in apply effects procedure
916 // Get mask of effects for target
917 uint32 mask = target->effectMask;
919 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
920 if (!unit)
921 return;
923 // Get original caster (if exist) and calculate damage/healing from him data
924 Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
926 // Skip if m_originalCaster not avaiable
927 if (!caster)
928 return;
930 SpellMissInfo missInfo = target->missCondition;
931 // Need init unitTarget by default unit (can changed in code on reflect)
932 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
933 unitTarget = unit;
935 // Reset damage/healing counter
936 m_damage = 0;
937 m_healing = 0;
939 // Fill base trigger info
940 uint32 procAttacker = m_procAttacker;
941 uint32 procVictim = m_procVictim;
942 uint32 procEx = PROC_EX_NONE;
944 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
945 DoSpellHitOnUnit(unit, mask);
946 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
948 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
949 DoSpellHitOnUnit(m_caster, mask);
952 // All calculated do it!
953 // Do healing and triggers
954 if (m_healing)
956 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
957 uint32 addhealth = m_healing;
958 if (crit)
960 procEx |= PROC_EX_CRITICAL_HIT;
961 addhealth = caster->SpellCriticalBonus(m_spellInfo, addhealth, NULL);
963 else
964 procEx |= PROC_EX_NORMAL_HIT;
966 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
968 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
969 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
970 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
972 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
974 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
975 if(caster->GetTypeId()==TYPEID_PLAYER)
976 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
977 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
979 // Do damage and triggers
980 else if (m_damage)
982 // Fill base damage struct (unitTarget - is real spell target)
983 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
985 // Add bonuses and fill damageInfo struct
986 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
988 // Send log damage message to client
989 caster->SendSpellNonMeleeDamageLog(&damageInfo);
991 procEx = createProcExtendMask(&damageInfo, missInfo);
992 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
994 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
995 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
996 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
998 caster->DealSpellDamage(&damageInfo, true);
1000 // Judgement of Blood
1001 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1003 int32 damagePoint = damageInfo.damage * 33 / 100;
1004 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1006 // Bloodthirst
1007 else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && m_spellInfo->SpellFamilyFlags & 0x40000000000LL)
1009 uint32 BTAura = 0;
1010 switch(m_spellInfo->Id)
1012 case 23881: BTAura = 23885; break;
1013 case 23892: BTAura = 23886; break;
1014 case 23893: BTAura = 23887; break;
1015 case 23894: BTAura = 23888; break;
1016 case 25251: BTAura = 25252; break;
1017 case 30335: BTAura = 30339; break;
1018 default:
1019 sLog.outError("Spell::EffectSchoolDMG: Spell %u not handled in BTAura",m_spellInfo->Id);
1020 break;
1022 if (BTAura)
1023 m_caster->CastSpell(m_caster,BTAura,true);
1026 // Passive spell hits/misses or active spells only misses (only triggers)
1027 else
1029 // Fill base damage struct (unitTarget - is real spell target)
1030 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1031 procEx = createProcExtendMask(&damageInfo, missInfo);
1032 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1033 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1034 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1037 // Call scripted function for AI if this spell is casted upon a creature (except pets)
1038 if(IS_CREATURE_GUID(target->targetGUID))
1040 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1041 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1042 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1043 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1045 if(((Creature*)unit)->AI())
1046 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1050 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1052 if(!unit || !effectMask)
1053 return;
1055 // Recheck immune (only for delayed spells)
1056 if( m_spellInfo->speed && (
1057 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1058 unit->IsImmunedToSpell(m_spellInfo)))
1060 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1061 return;
1064 if (unit->GetTypeId() == TYPEID_PLAYER)
1066 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1067 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1070 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1072 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1075 if( m_caster != unit )
1077 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1078 if (m_spellInfo->speed > 0.0f &&
1079 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1080 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1082 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1083 return;
1086 if( !m_caster->IsFriendlyTo(unit) )
1088 // for delayed spells ignore not visible explicit target
1089 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1091 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1092 return;
1095 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1097 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1099 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1100 unit->SetStandState(PLAYER_STATE_NONE);
1102 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1103 ((Creature*)unit)->AI()->AttackStart(m_caster);
1105 unit->SetInCombatWith(m_caster);
1106 m_caster->SetInCombatWith(unit);
1108 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1110 m_caster->SetContestedPvP(attackedPlayer);
1112 unit->AddThreat(m_caster, 0.0f);
1115 else
1117 // for delayed spells ignore negative spells (after duel end) for friendly targets
1118 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1120 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1121 return;
1124 // assisting case, healing and resurrection
1125 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1126 m_caster->SetContestedPvP();
1127 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1129 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1130 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1135 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1136 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1137 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1138 // Increase Diminishing on unit, current informations for actually casts will use values above
1139 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1140 unit->IncrDiminishing(m_diminishGroup);
1142 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1144 if (effectMask & (1<<effectNumber))
1146 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1147 if ( m_applyMultiplierMask & (1 << effectNumber) )
1149 // Get multiplier
1150 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1151 // Apply multiplier mods
1152 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1153 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1154 m_damageMultipliers[effectNumber] *= multiplier;
1160 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1162 if (target->processed) // Check target
1163 return;
1164 target->processed = true; // Target checked in apply effects procedure
1166 uint32 effectMask = target->effectMask;
1167 if(!effectMask)
1168 return;
1170 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1171 if(!go)
1172 return;
1174 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1175 if (effectMask & (1<<effectNumber))
1176 HandleEffects(NULL,NULL,go,effectNumber);
1178 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1179 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1180 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1181 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1184 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1186 uint32 effectMask = target->effectMask;
1187 if(!target->item || !effectMask)
1188 return;
1190 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1191 if (effectMask & (1<<effectNumber))
1192 HandleEffects(NULL, target->item, NULL, effectNumber);
1195 bool Spell::IsAliveUnitPresentInTargetList()
1197 // Not need check return true
1198 if (m_needAliveTargetMask == 0)
1199 return true;
1201 uint8 needAliveTargetMask = m_needAliveTargetMask;
1203 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1205 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1207 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1209 if (unit && unit->isAlive())
1210 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1214 // is all effects from m_needAliveTargetMask have alive targets
1215 return needAliveTargetMask==0;
1218 // Helper for Chain Healing
1219 // Spell target first
1220 // Raidmates then descending by injury suffered (MaxHealth - Health)
1221 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1222 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1224 const Unit* MainTarget;
1225 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1226 // functor for operator ">"
1227 bool operator()(Unit const* _Left, Unit const* _Right) const
1229 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1231 int32 ChainHealingHash(Unit const* Target) const
1233 if (Target == MainTarget)
1234 return 0;
1235 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1236 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1238 if (Target->GetHealth() == Target->GetMaxHealth())
1239 return 40000;
1240 else
1241 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1243 else
1244 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1248 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1250 public:
1251 const Unit* MainTarget;
1252 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1254 bool operator()(const Unit* Target)
1256 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1260 // Helper for targets nearest to the spell target
1261 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1262 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1264 const Unit* MainTarget;
1265 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1266 // functor for operator ">"
1267 bool operator()(const Unit* _Left, const Unit* _Right) const
1269 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1273 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1275 float radius;
1276 if (m_spellInfo->EffectRadiusIndex[i])
1277 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1278 else
1279 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1281 if(m_originalCaster)
1282 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1283 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1285 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1286 if(m_originalCaster)
1287 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1288 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1290 // Get spell max affected targets
1291 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1292 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1293 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1295 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1296 continue;
1297 unMaxTargets+=(*m)->GetModifier()->m_amount;
1299 switch(cur)
1301 case TARGET_TOTEM_EARTH:
1302 case TARGET_TOTEM_WATER:
1303 case TARGET_TOTEM_AIR:
1304 case TARGET_TOTEM_FIRE:
1305 case TARGET_SELF:
1306 case TARGET_SELF2:
1307 case TARGET_DYNAMIC_OBJECT:
1308 case TARGET_AREAEFFECT_CUSTOM:
1309 case TARGET_AREAEFFECT_CUSTOM_2:
1310 case TARGET_SUMMON:
1312 TagUnitMap.push_back(m_caster);
1313 break;
1315 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1317 m_targets.m_targetMask = 0;
1318 unMaxTargets = EffectChainTarget;
1319 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1321 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1322 Cell cell(p);
1323 cell.data.Part.reserved = ALL_DISTRICT;
1324 cell.SetNoCreate();
1326 std::list<Unit *> tempUnitMap;
1329 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1330 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1332 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1333 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1335 CellLock<GridReadGuard> cell_lock(cell, p);
1336 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1337 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1340 if(tempUnitMap.empty())
1341 break;
1343 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1345 //Now to get us a random target that's in the initial range of the spell
1346 uint32 t = 0;
1347 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1348 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1349 ++t, ++itr;
1351 if(!t)
1352 break;
1354 itr = tempUnitMap.begin();
1355 std::advance(itr, rand()%t);
1356 Unit *pUnitTarget = *itr;
1357 TagUnitMap.push_back(pUnitTarget);
1359 tempUnitMap.erase(itr);
1361 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1363 t = unMaxTargets - 1;
1364 Unit *prev = pUnitTarget;
1365 std::list<Unit*>::iterator next = tempUnitMap.begin();
1367 while(t && next != tempUnitMap.end() )
1369 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1370 break;
1372 if(!prev->IsWithinLOSInMap(*next))
1374 ++next;
1375 continue;
1378 prev = *next;
1379 TagUnitMap.push_back(prev);
1380 tempUnitMap.erase(next);
1381 tempUnitMap.sort(TargetDistanceOrder(prev));
1382 next = tempUnitMap.begin();
1384 --t;
1386 }break;
1387 case TARGET_PET:
1389 Pet* tmpUnit = m_caster->GetPet();
1390 if (!tmpUnit) break;
1391 TagUnitMap.push_back(tmpUnit);
1392 break;
1394 case TARGET_CHAIN_DAMAGE:
1396 if (EffectChainTarget <= 1)
1398 Unit* pUnitTarget = SelectMagnetTarget();
1399 if(pUnitTarget)
1400 TagUnitMap.push_back(pUnitTarget);
1402 else
1404 Unit* pUnitTarget = m_targets.getUnitTarget();
1405 if(!pUnitTarget)
1406 break;
1408 unMaxTargets = EffectChainTarget;
1410 float max_range;
1411 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1412 max_range = radius; //
1413 else
1414 //FIXME: This very like horrible hack and wrong for most spells
1415 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1417 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1418 Cell cell(p);
1419 cell.data.Part.reserved = ALL_DISTRICT;
1420 cell.SetNoCreate();
1422 Unit* originalCaster = GetOriginalCaster();
1423 if(originalCaster)
1425 std::list<Unit *> tempUnitMap;
1428 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1429 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1431 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1432 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1434 CellLock<GridReadGuard> cell_lock(cell, p);
1435 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1436 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1439 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1441 if(tempUnitMap.empty())
1442 break;
1444 if(*tempUnitMap.begin() == pUnitTarget)
1445 tempUnitMap.erase(tempUnitMap.begin());
1447 TagUnitMap.push_back(pUnitTarget);
1448 uint32 t = unMaxTargets - 1;
1449 Unit *prev = pUnitTarget;
1450 std::list<Unit*>::iterator next = tempUnitMap.begin();
1452 while(t && next != tempUnitMap.end() )
1454 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1455 break;
1457 if(!prev->IsWithinLOSInMap(*next))
1459 ++next;
1460 continue;
1463 prev = *next;
1464 TagUnitMap.push_back(prev);
1465 tempUnitMap.erase(next);
1466 tempUnitMap.sort(TargetDistanceOrder(prev));
1467 next = tempUnitMap.begin();
1469 --t;
1473 }break;
1474 case TARGET_ALL_ENEMY_IN_AREA:
1476 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1477 Cell cell(p);
1478 cell.data.Part.reserved = ALL_DISTRICT;
1479 cell.SetNoCreate();
1481 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1483 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1484 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1486 CellLock<GridReadGuard> cell_lock(cell, p);
1487 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1488 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1489 }break;
1490 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1492 // targets the ground, not the units in the area
1493 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1495 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1496 Cell cell(p);
1497 cell.data.Part.reserved = ALL_DISTRICT;
1498 cell.SetNoCreate();
1500 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1502 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1503 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1505 CellLock<GridReadGuard> cell_lock(cell, p);
1506 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1507 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1509 // exclude caster (this can be important if this not original caster)
1510 TagUnitMap.remove(m_caster);
1512 }break;
1513 case TARGET_DUELVSPLAYER_COORDINATES:
1515 if(Unit* currentTarget = m_targets.getUnitTarget())
1517 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1518 TagUnitMap.push_back(currentTarget);
1520 }break;
1521 case TARGET_ALL_PARTY_AROUND_CASTER:
1522 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1523 case TARGET_ALL_PARTY:
1524 case TARGET_ALL_RAID_AROUND_CASTER:
1526 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1527 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1529 if(pGroup)
1531 uint8 subgroup = pTarget->GetSubGroup();
1533 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1535 Player* Target = itr->getSource();
1537 // IsHostileTo check duel and controlled by enemy
1538 if( Target &&
1539 (cur==TARGET_ALL_RAID_AROUND_CASTER || Target->GetSubGroup()==subgroup) &&
1540 !m_caster->IsHostileTo(Target) )
1542 if( m_caster->IsWithinDistInMap(Target, radius) )
1543 TagUnitMap.push_back(Target);
1545 if(Pet* pet = Target->GetPet())
1546 if( m_caster->IsWithinDistInMap(pet, radius) )
1547 TagUnitMap.push_back(pet);
1551 else
1553 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1554 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1555 TagUnitMap.push_back(ownerOrSelf);
1556 if(Pet* pet = ownerOrSelf->GetPet())
1557 if( m_caster->IsWithinDistInMap(pet, radius) )
1558 TagUnitMap.push_back(pet);
1560 }break;
1561 case TARGET_SINGLE_FRIEND:
1562 case TARGET_SINGLE_FRIEND_2:
1564 if(m_targets.getUnitTarget())
1565 TagUnitMap.push_back(m_targets.getUnitTarget());
1566 }break;
1567 case TARGET_NONCOMBAT_PET:
1569 if(Unit* target = m_targets.getUnitTarget())
1570 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1571 TagUnitMap.push_back(target);
1572 }break;
1573 case TARGET_CASTER_COORDINATES:
1575 m_targets.setDestination(m_targets.m_srcX, m_targets.m_srcY, m_targets.m_srcZ);
1576 }break;
1577 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1579 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1580 Cell cell(p);
1581 cell.data.Part.reserved = ALL_DISTRICT;
1582 cell.SetNoCreate();
1584 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1586 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1587 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1589 CellLock<GridReadGuard> cell_lock(cell, p);
1590 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1591 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1592 }break;
1593 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1595 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1596 Cell cell(p);
1597 cell.data.Part.reserved = ALL_DISTRICT;
1598 cell.SetNoCreate();
1600 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1602 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1603 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1605 CellLock<GridReadGuard> cell_lock(cell, p);
1606 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1607 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1608 }break;
1609 // 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..)
1610 case TARGET_SINGLE_PARTY:
1612 Unit *target = m_targets.getUnitTarget();
1613 // Thoses spells apparently can't be casted on the caster.
1614 if( target && target != m_caster)
1616 // Can only be casted on group's members or its pets
1617 Group *pGroup = NULL;
1619 Unit* owner = m_caster->GetCharmerOrOwner();
1620 Unit *targetOwner = target->GetCharmerOrOwner();
1621 if(owner)
1623 if(owner->GetTypeId() == TYPEID_PLAYER)
1625 if( target == owner )
1627 TagUnitMap.push_back(target);
1628 break;
1630 pGroup = ((Player*)owner)->GetGroup();
1633 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1635 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1637 TagUnitMap.push_back(target);
1638 break;
1640 pGroup = ((Player*)m_caster)->GetGroup();
1643 if(pGroup)
1645 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1646 if(targetOwner)
1648 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1649 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1650 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1651 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1653 TagUnitMap.push_back(target);
1656 // 1Our target can be a player who is on our group
1657 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1659 TagUnitMap.push_back(target);
1663 }break;
1664 case TARGET_GAMEOBJECT:
1666 if(m_targets.getGOTarget())
1667 AddGOTarget(m_targets.getGOTarget(), i);
1668 }break;
1669 case TARGET_IN_FRONT_OF_CASTER:
1671 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1672 Cell cell(p);
1673 cell.data.Part.reserved = ALL_DISTRICT;
1674 cell.SetNoCreate();
1676 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1677 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1679 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1680 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1682 CellLock<GridReadGuard> cell_lock(cell, p);
1683 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1684 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1685 }break;
1686 case TARGET_DUELVSPLAYER:
1688 Unit *target = m_targets.getUnitTarget();
1689 if(target)
1691 if(m_caster->IsFriendlyTo(target))
1693 TagUnitMap.push_back(target);
1695 else
1697 Unit* pUnitTarget = SelectMagnetTarget();
1698 if(pUnitTarget)
1699 TagUnitMap.push_back(pUnitTarget);
1702 }break;
1703 case TARGET_GAMEOBJECT_ITEM:
1705 if(m_targets.getGOTargetGUID())
1706 AddGOTarget(m_targets.getGOTarget(), i);
1707 else if(m_targets.getItemTarget())
1708 AddItemTarget(m_targets.getItemTarget(), i);
1709 break;
1711 case TARGET_MASTER:
1713 if(Unit* owner = m_caster->GetCharmerOrOwner())
1714 TagUnitMap.push_back(owner);
1715 break;
1717 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1719 // targets the ground, not the units in the area
1720 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1722 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1723 Cell cell(p);
1724 cell.data.Part.reserved = ALL_DISTRICT;
1725 cell.SetNoCreate();
1727 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1729 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1730 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1732 CellLock<GridReadGuard> cell_lock(cell, p);
1733 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1734 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1736 }break;
1737 case TARGET_MINION:
1739 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1740 TagUnitMap.push_back(m_caster);
1741 }break;
1742 case TARGET_SINGLE_ENEMY:
1744 Unit* pUnitTarget = SelectMagnetTarget();
1745 if(pUnitTarget)
1746 TagUnitMap.push_back(pUnitTarget);
1747 }break;
1748 case TARGET_AREAEFFECT_PARTY:
1750 Unit* owner = m_caster->GetCharmerOrOwner();
1751 Player *pTarget = NULL;
1753 if(owner)
1755 TagUnitMap.push_back(m_caster);
1756 if(owner->GetTypeId() == TYPEID_PLAYER)
1757 pTarget = (Player*)owner;
1759 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1761 if(Unit* target = m_targets.getUnitTarget())
1763 if( target->GetTypeId() != TYPEID_PLAYER)
1765 if(((Creature*)target)->isPet())
1767 Unit *targetOwner = target->GetOwner();
1768 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1769 pTarget = (Player*)targetOwner;
1772 else
1773 pTarget = (Player*)target;
1777 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1779 if(pGroup)
1781 uint8 subgroup = pTarget->GetSubGroup();
1783 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1785 Player* Target = itr->getSource();
1787 // IsHostileTo check duel and controlled by enemy
1788 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1790 if( pTarget->IsWithinDistInMap(Target, radius) )
1791 TagUnitMap.push_back(Target);
1793 if(Pet* pet = Target->GetPet())
1794 if( pTarget->IsWithinDistInMap(pet, radius) )
1795 TagUnitMap.push_back(pet);
1799 else if (owner)
1801 if(m_caster->IsWithinDistInMap(owner, radius))
1802 TagUnitMap.push_back(owner);
1804 else if(pTarget)
1806 TagUnitMap.push_back(pTarget);
1808 if(Pet* pet = pTarget->GetPet())
1809 if( m_caster->IsWithinDistInMap(pet, radius) )
1810 TagUnitMap.push_back(pet);
1813 }break;
1814 case TARGET_SCRIPT:
1816 if(m_targets.getUnitTarget())
1817 TagUnitMap.push_back(m_targets.getUnitTarget());
1818 if(m_targets.getItemTarget())
1819 AddItemTarget(m_targets.getItemTarget(), i);
1820 }break;
1821 case TARGET_SELF_FISHING:
1823 TagUnitMap.push_back(m_caster);
1824 }break;
1825 case TARGET_CHAIN_HEAL:
1827 Unit* pUnitTarget = m_targets.getUnitTarget();
1828 if(!pUnitTarget)
1829 break;
1831 if (EffectChainTarget <= 1)
1832 TagUnitMap.push_back(pUnitTarget);
1833 else
1835 unMaxTargets = EffectChainTarget;
1836 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1838 std::list<Unit *> tempUnitMap;
1841 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1842 Cell cell(p);
1843 cell.data.Part.reserved = ALL_DISTRICT;
1844 cell.SetNoCreate();
1846 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1848 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1849 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1851 CellLock<GridReadGuard> cell_lock(cell, p);
1852 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1853 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1857 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1858 tempUnitMap.push_front(m_caster);
1860 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1862 if(tempUnitMap.empty())
1863 break;
1865 if(*tempUnitMap.begin() == pUnitTarget)
1866 tempUnitMap.erase(tempUnitMap.begin());
1868 TagUnitMap.push_back(pUnitTarget);
1869 uint32 t = unMaxTargets - 1;
1870 Unit *prev = pUnitTarget;
1871 std::list<Unit*>::iterator next = tempUnitMap.begin();
1873 while(t && next != tempUnitMap.end() )
1875 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1876 break;
1878 if(!prev->IsWithinLOSInMap(*next))
1880 ++next;
1881 continue;
1884 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1886 next = tempUnitMap.erase(next);
1887 continue;
1890 prev = *next;
1891 TagUnitMap.push_back(prev);
1892 tempUnitMap.erase(next);
1893 tempUnitMap.sort(TargetDistanceOrder(prev));
1894 next = tempUnitMap.begin();
1896 --t;
1899 }break;
1900 case TARGET_CURRENT_ENEMY_COORDINATES:
1902 Unit* currentTarget = m_targets.getUnitTarget();
1903 if(currentTarget)
1905 TagUnitMap.push_back(currentTarget);
1906 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1907 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1909 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1910 Cell cell(p);
1911 cell.data.Part.reserved = ALL_DISTRICT;
1912 cell.SetNoCreate();
1913 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1914 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1915 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1916 CellLock<GridReadGuard> cell_lock(cell, p);
1917 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1918 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1921 }break;
1922 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1924 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1925 ? (Player*)m_targets.getUnitTarget() : NULL;
1927 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1928 if(pGroup)
1930 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1932 Player* Target = itr->getSource();
1934 // IsHostileTo check duel and controlled by enemy
1935 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1936 targetPlayer->getClass() == Target->getClass() &&
1937 !m_caster->IsHostileTo(Target) )
1939 TagUnitMap.push_back(Target);
1943 else if(m_targets.getUnitTarget())
1944 TagUnitMap.push_back(m_targets.getUnitTarget());
1945 break;
1947 case TARGET_TABLE_X_Y_Z_COORDINATES:
1949 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
1950 if(st)
1952 if (st->target_mapId == m_caster->GetMapId())
1953 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1955 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
1956 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
1958 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1959 Cell cell(p);
1960 cell.data.Part.reserved = ALL_DISTRICT;
1961 cell.SetNoCreate();
1963 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1964 // Select friendly targets for positive effect
1965 if (IsPositiveEffect(m_spellInfo->Id, i))
1966 targetB = SPELL_TARGETS_FRIENDLY;
1968 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
1970 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1971 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1973 CellLock<GridReadGuard> cell_lock(cell, p);
1974 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1975 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1978 else
1979 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1980 }break;
1981 case TARGET_BEHIND_VICTIM:
1983 Unit *pTarget = m_caster->getVictim();
1984 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
1985 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
1987 if(pTarget)
1989 float _target_x, _target_y, _target_z;
1990 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
1991 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
1992 m_targets.setDestination(_target_x, _target_y, _target_z);
1994 }break;
1995 case TARGET_DYNAMIC_OBJECT_COORDINATES:
1997 // if parent spell create dynamic object extract area from it
1998 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
1999 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
2000 }break;
2001 default:
2002 break;
2005 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2007 // make sure one unit is always removed per iteration
2008 uint32 removed_utarget = 0;
2009 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2011 next = itr;
2012 ++next;
2013 if (!*itr) continue;
2014 if ((*itr) == m_targets.getUnitTarget())
2016 TagUnitMap.erase(itr);
2017 removed_utarget = 1;
2018 // break;
2021 // remove random units from the map
2022 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2024 uint32 poz = urand(0, TagUnitMap.size()-1);
2025 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2027 if (!*itr) continue;
2028 if (!poz)
2030 TagUnitMap.erase(itr);
2031 break;
2035 // the player's target will always be added to the map
2036 if (removed_utarget && m_targets.getUnitTarget())
2037 TagUnitMap.push_back(m_targets.getUnitTarget());
2041 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2043 m_targets = *targets;
2045 m_spellState = SPELL_STATE_PREPARING;
2047 if (!(m_targets.m_targetMask & TARGET_FLAG_SOURCE_LOCATION))
2049 // Check original caster is GO - set its coordinates as src cast
2050 WorldObject *caster = NULL;
2051 if (m_originalCasterGUID)
2052 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
2053 if (!caster)
2054 caster = m_caster;
2055 // Set cast source for targets
2056 m_targets.setSource(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ());
2059 m_castPositionX = m_caster->GetPositionX();
2060 m_castPositionY = m_caster->GetPositionY();
2061 m_castPositionZ = m_caster->GetPositionZ();
2062 m_castOrientation = m_caster->GetOrientation();
2064 if(triggeredByAura)
2065 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2067 // create and add update event for this spell
2068 SpellEvent* Event = new SpellEvent(this);
2069 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2071 //Prevent casting at cast another spell (ServerSide check)
2072 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2074 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2075 finish(false);
2076 return;
2079 // Fill cost data
2080 m_powerCost = CalculatePowerCost();
2082 uint8 result = CanCast(true);
2083 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2085 if(triggeredByAura)
2087 SendChannelUpdate(0);
2088 triggeredByAura->SetAuraDuration(0);
2090 SendCastResult(result);
2091 finish(false);
2092 return;
2095 // Prepare data for triggers
2096 prepareDataForTriggerSystem();
2098 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2099 m_casttime = GetSpellCastTime(m_spellInfo, this);
2101 // set timer base at cast time
2102 ReSetTimer();
2104 // stealth must be removed at cast starting (at show channel bar)
2105 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2106 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2108 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2109 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2112 if(m_IsTriggeredSpell)
2113 cast(true);
2114 else
2116 m_caster->SetCurrentCastedSpell( this );
2117 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2118 SendSpellStart();
2122 void Spell::cancel()
2124 if(m_spellState == SPELL_STATE_FINISHED)
2125 return;
2127 m_autoRepeat = false;
2128 switch (m_spellState)
2130 case SPELL_STATE_PREPARING:
2131 case SPELL_STATE_DELAYED:
2133 SendInterrupted(0);
2134 SendCastResult(SPELL_FAILED_INTERRUPTED);
2135 } break;
2137 case SPELL_STATE_CASTING:
2139 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2141 if( ihit->missCondition == SPELL_MISS_NONE )
2143 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2144 if( unit && unit->isAlive() )
2145 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2149 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2150 SendChannelUpdate(0);
2151 SendInterrupted(0);
2152 SendCastResult(SPELL_FAILED_INTERRUPTED);
2153 } break;
2155 default:
2157 } break;
2160 finish(false);
2161 m_caster->RemoveDynObject(m_spellInfo->Id);
2162 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2165 void Spell::cast(bool skipCheck)
2167 SetExecutedCurrently(true);
2169 uint8 castResult = 0;
2171 // update pointers base at GUIDs to prevent access to non-existed already object
2172 UpdatePointers();
2174 // cancel at lost main target unit
2175 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2177 cancel();
2178 SetExecutedCurrently(false);
2179 return;
2182 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2183 m_caster->SetInFront(m_targets.getUnitTarget());
2185 castResult = CheckPower();
2186 if(castResult != 0)
2188 SendCastResult(castResult);
2189 finish(false);
2190 SetExecutedCurrently(false);
2191 return;
2194 // triggered cast called from Spell::prepare where it was already checked
2195 if(!skipCheck)
2197 castResult = CanCast(false);
2198 if(castResult != 0)
2200 SendCastResult(castResult);
2201 finish(false);
2202 SetExecutedCurrently(false);
2203 return;
2207 // Conflagrate - consumes immolate
2208 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2210 // for caster applied auras only
2211 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2212 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2214 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2215 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2217 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2218 break;
2223 // traded items have trade slot instead of guid in m_itemTargetGUID
2224 // set to real guid to be sent later to the client
2225 m_targets.updateTradeSlotItem();
2227 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2229 if (m_CastItem)
2230 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2232 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2235 // CAST SPELL
2236 SendSpellCooldown();
2238 TakePower();
2239 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2240 FillTargetMap();
2242 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2244 SetExecutedCurrently(false);
2245 return;
2248 SendCastResult(castResult);
2249 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2251 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2252 if (m_spellInfo->speed > 0.0f)
2255 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2256 // in case delayed spell remove item at cast delay start
2257 TakeCastItem();
2259 // Okay, maps created, now prepare flags
2260 m_immediateHandled = false;
2261 m_spellState = SPELL_STATE_DELAYED;
2262 SetDelayStart(0);
2264 else
2266 // Immediate spell, no big deal
2267 handle_immediate();
2270 SetExecutedCurrently(false);
2273 void Spell::handle_immediate()
2275 // start channeling if applicable
2276 if(IsChanneledSpell(m_spellInfo))
2278 int32 duration = GetSpellDuration(m_spellInfo);
2279 if (duration)
2281 // Apply duration mod
2282 if(Player* modOwner = m_caster->GetSpellModOwner())
2283 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
2284 m_spellState = SPELL_STATE_CASTING;
2285 SendChannelStart(duration);
2289 // process immediate effects (items, ground, etc.) also initialize some variables
2290 _handle_immediate_phase();
2292 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2293 DoAllEffectOnTarget(&(*ihit));
2295 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2296 DoAllEffectOnTarget(&(*ihit));
2298 // spell is finished, perform some last features of the spell here
2299 _handle_finish_phase();
2301 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2302 TakeCastItem();
2304 if(m_spellState != SPELL_STATE_CASTING)
2305 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2308 uint64 Spell::handle_delayed(uint64 t_offset)
2310 uint64 next_time = 0;
2312 if (!m_immediateHandled)
2314 _handle_immediate_phase();
2315 m_immediateHandled = true;
2318 // 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)
2319 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2321 if (ihit->processed == false)
2323 if ( ihit->timeDelay <= t_offset )
2324 DoAllEffectOnTarget(&(*ihit));
2325 else if( next_time == 0 || ihit->timeDelay < next_time )
2326 next_time = ihit->timeDelay;
2330 // now recheck gameobject targeting correctness
2331 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2333 if (ighit->processed == false)
2335 if ( ighit->timeDelay <= t_offset )
2336 DoAllEffectOnTarget(&(*ighit));
2337 else if( next_time == 0 || ighit->timeDelay < next_time )
2338 next_time = ighit->timeDelay;
2341 // All targets passed - need finish phase
2342 if (next_time == 0)
2344 // spell is finished, perform some last features of the spell here
2345 _handle_finish_phase();
2347 finish(true); // successfully finish spell cast
2349 // return zero, spell is finished now
2350 return 0;
2352 else
2354 // spell is unfinished, return next execution time
2355 return next_time;
2359 void Spell::_handle_immediate_phase()
2361 // handle some immediate features of the spell here
2362 HandleThreatSpells(m_spellInfo->Id);
2364 m_needSpellLog = IsNeedSendToClient();
2365 for(uint32 j = 0;j<3;j++)
2367 if(m_spellInfo->Effect[j]==0)
2368 continue;
2370 // apply Send Event effect to ground in case empty target lists
2371 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2373 HandleEffects(NULL,NULL,NULL, j);
2374 continue;
2377 // Don't do spell log, if is school damage spell
2378 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2379 m_needSpellLog = false;
2381 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2382 if(m_originalCaster)
2383 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2384 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2386 // initialize multipliers
2387 m_damageMultipliers[j] = 1.0f;
2388 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2389 (EffectChainTarget > 1) )
2390 m_applyMultiplierMask |= 1 << j;
2393 // initialize Diminishing Returns Data
2394 m_diminishLevel = DIMINISHING_LEVEL_1;
2395 m_diminishGroup = DIMINISHING_NONE;
2397 // process items
2398 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2399 DoAllEffectOnTarget(&(*ihit));
2401 // process ground
2402 for(uint32 j = 0;j<3;j++)
2404 // persistent area auras target only the ground
2405 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2406 HandleEffects(NULL,NULL,NULL, j);
2410 void Spell::_handle_finish_phase()
2412 // spell log
2413 if(m_needSpellLog)
2414 SendLogExecute();
2417 void Spell::SendSpellCooldown()
2419 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2420 return;
2422 Player* _player = (Player*)m_caster;
2423 // Add cooldown for max (disable spell)
2424 // Cooldown started on SendCooldownEvent call
2425 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2427 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2428 return;
2431 // init cooldown values
2432 uint32 cat = 0;
2433 int32 rec = -1;
2434 int32 catrec = -1;
2436 // some special item spells without correct cooldown in SpellInfo
2437 // cooldown information stored in item prototype
2438 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2440 if(m_CastItem)
2442 ItemPrototype const* proto = m_CastItem->GetProto();
2443 if(proto)
2445 for(int idx = 0; idx < 5; ++idx)
2447 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2449 cat = proto->Spells[idx].SpellCategory;
2450 rec = proto->Spells[idx].SpellCooldown;
2451 catrec = proto->Spells[idx].SpellCategoryCooldown;
2452 break;
2458 // if no cooldown found above then base at DBC data
2459 if(rec < 0 && catrec < 0)
2461 cat = m_spellInfo->Category;
2462 rec = m_spellInfo->RecoveryTime;
2463 catrec = m_spellInfo->CategoryRecoveryTime;
2466 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2467 // prevent 0 cooldowns set by another way
2468 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT))
2469 rec = _player->GetAttackTime(RANGED_ATTACK);
2471 // Now we have cooldown data (if found any), time to apply mods
2472 if(rec > 0)
2473 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2475 if(catrec > 0)
2476 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2478 // replace negative cooldowns by 0
2479 if (rec < 0) rec = 0;
2480 if (catrec < 0) catrec = 0;
2482 // no cooldown after applying spell mods
2483 if( rec == 0 && catrec == 0)
2484 return;
2486 time_t curTime = time(NULL);
2488 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2489 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2491 // self spell cooldown
2492 if(recTime > 0)
2493 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2495 // category spells
2496 if (catrec > 0)
2498 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2499 if(i_scstore != sSpellCategoryStore.end())
2501 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2503 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2504 continue;
2506 _player->AddSpellCooldown(*i_scset, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2512 void Spell::update(uint32 difftime)
2514 // update pointers based at it's GUIDs
2515 UpdatePointers();
2517 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2519 cancel();
2520 return;
2523 // check if the player caster has moved before the spell finished
2524 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2525 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2526 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2528 // always cancel for channeled spells
2529 if( m_spellState == SPELL_STATE_CASTING )
2530 cancel();
2531 // don't cancel for melee, autorepeat, triggered and instant spells
2532 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2533 cancel();
2536 switch(m_spellState)
2538 case SPELL_STATE_PREPARING:
2540 if(m_timer)
2542 if(difftime >= m_timer)
2543 m_timer = 0;
2544 else
2545 m_timer -= difftime;
2548 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2549 cast();
2550 } break;
2551 case SPELL_STATE_CASTING:
2553 if(m_timer > 0)
2555 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2557 // check if player has jumped before the channeling finished
2558 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2559 cancel();
2561 // check for incapacitating player states
2562 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2563 cancel();
2565 // check if player has turned if flag is set
2566 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2567 cancel();
2570 // check if there are alive targets left
2571 if (!IsAliveUnitPresentInTargetList())
2573 SendChannelUpdate(0);
2574 finish();
2577 if(difftime >= m_timer)
2578 m_timer = 0;
2579 else
2580 m_timer -= difftime;
2583 if(m_timer == 0)
2585 SendChannelUpdate(0);
2587 // channeled spell processed independently for quest targeting
2588 // cast at creature (or GO) quest objectives update at successful cast channel finished
2589 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2590 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2592 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2594 TargetInfo* target = &*ihit;
2595 if(!IS_CREATURE_GUID(target->targetGUID))
2596 continue;
2598 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2599 if (unit==NULL)
2600 continue;
2602 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2605 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2607 GOTargetInfo* target = &*ihit;
2609 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2610 if(!go)
2611 continue;
2613 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2617 finish();
2619 } break;
2620 default:
2622 }break;
2626 void Spell::finish(bool ok)
2628 if(!m_caster)
2629 return;
2631 if(m_spellState == SPELL_STATE_FINISHED)
2632 return;
2634 m_spellState = SPELL_STATE_FINISHED;
2636 // other code related only to successfully finished spells
2637 if(!ok)
2638 return;
2640 //remove spell mods
2641 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2642 ((Player*)m_caster)->RemoveSpellMods(this);
2644 //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2645 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2646 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2648 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2649 uint32 auraSpellIdx = (*i)->GetEffIndex();
2650 if (IsAffectedByAura((*i)))
2652 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2653 if( ihit->effectMask & (1<<auraSpellIdx) )
2655 // check m_caster->GetGUID() let load auras at login and speedup most often case
2656 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2657 if (unit && unit->isAlive())
2659 // Calculate chance at that moment (can be depend for example from combo points)
2660 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2662 if(roll_chance_i(chance))
2663 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2669 // Heal caster for all health leech from all targets
2670 if (m_healthLeech)
2672 m_caster->ModifyHealth(m_healthLeech);
2673 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2676 if (IsMeleeAttackResetSpell())
2678 m_caster->resetAttackTimer(BASE_ATTACK);
2679 if(m_caster->haveOffhandWeapon())
2680 m_caster->resetAttackTimer(OFF_ATTACK);
2683 /*if (IsRangedAttackResetSpell())
2684 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2686 // Clear combo at finish state
2687 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2689 // Not drop combopoints if negative spell and if any miss on enemy exist
2690 bool needDrop = true;
2691 if (!IsPositiveSpell(m_spellInfo->Id))
2692 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2693 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2695 needDrop = false;
2696 break;
2698 if (needDrop)
2699 ((Player*)m_caster)->ClearComboPoints();
2702 // Post effects apply on spell targets in some spells
2703 if(!m_UniqueTargetInfo.empty())
2705 uint32 spellId = 0;
2706 switch(m_spellInfo->SpellFamilyName)
2708 case SPELLFAMILY_GENERIC:
2710 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2711 spellId = 11196; // Recently Bandaged
2712 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2713 spellId = 23230; // Blood Fury - Healing Reduction
2714 break;
2716 case SPELLFAMILY_MAGE:
2718 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2719 spellId = 41425; // Hypothermia
2720 break;
2722 case SPELLFAMILY_PRIEST:
2724 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2725 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2726 spellId = 6788; // Weakened Soul
2727 break;
2729 case SPELLFAMILY_PALADIN:
2731 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2732 spellId = 25771; // Forbearance
2733 break;
2735 case SPELLFAMILY_SHAMAN:
2737 if (m_spellInfo->Id == 2825) // Bloodlust
2738 spellId = 57724; // Sated
2739 else if (m_spellInfo->Id == 32182) // Heroism
2740 spellId = 57723; // Exhaustion
2741 break;
2743 default:
2744 break;
2746 if (spellId)
2748 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2750 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2751 if (unit)
2753 // TODO: fix me use cast spell (now post spell can immune by this spell)
2754 // m_caster->CastSpell(unit, spellId, true, m_CastItem);
2755 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(spellId);
2756 if (!AdditionalSpellInfo)
2757 continue;
2758 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, 0, &m_currentBasePoints[0], unit, m_caster, m_CastItem);
2759 unit->AddAura(AdditionalAura);
2764 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2765 if(!m_TriggerSpells.empty())
2766 TriggerSpell();
2768 // Stop Attack for some spells
2769 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2770 m_caster->AttackStop();
2773 void Spell::SendCastResult(uint8 result)
2775 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2776 return;
2778 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2779 return;
2781 if(result != 0)
2783 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2784 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2785 data << uint32(m_spellInfo->Id);
2786 data << uint8(result); // problem
2787 switch (result)
2789 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2790 data << uint32(m_spellInfo->RequiresSpellFocus);
2791 break;
2792 case SPELL_FAILED_REQUIRES_AREA:
2793 // hardcode areas limitation case
2794 switch(m_spellInfo->Id)
2796 case 41617: // Cenarion Mana Salve
2797 case 41619: // Cenarion Healing Salve
2798 data << uint32(3905);
2799 break;
2800 case 41618: // Bottled Nethergon Energy
2801 case 41620: // Bottled Nethergon Vapor
2802 data << uint32(3842);
2803 break;
2804 case 45373: // Bloodberry Elixir
2805 data << uint32(4075);
2806 break;
2807 default: // default case (don't must be)
2808 data << uint32(0);
2809 break;
2811 break;
2812 case SPELL_FAILED_TOTEMS:
2813 if(m_spellInfo->Totem[0])
2814 data << uint32(m_spellInfo->Totem[0]);
2815 if(m_spellInfo->Totem[1])
2816 data << uint32(m_spellInfo->Totem[1]);
2817 break;
2818 case SPELL_FAILED_TOTEM_CATEGORY:
2819 if(m_spellInfo->TotemCategory[0])
2820 data << uint32(m_spellInfo->TotemCategory[0]);
2821 if(m_spellInfo->TotemCategory[1])
2822 data << uint32(m_spellInfo->TotemCategory[1]);
2823 break;
2824 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2825 data << uint32(m_spellInfo->EquippedItemClass);
2826 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2827 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2828 break;
2830 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2834 void Spell::SendSpellStart()
2836 if(!IsNeedSendToClient())
2837 return;
2839 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2841 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2842 if(IsRangedSpell())
2843 castFlags |= CAST_FLAG_AMMO;
2845 if(m_spellInfo->runeCostID)
2846 castFlags |= CAST_FLAG_UNKNOWN10;
2848 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2850 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2851 if(m_CastItem)
2852 data.append(m_CastItem->GetPackGUID());
2853 else
2854 data.append(m_caster->GetPackGUID());
2856 data.append(m_caster->GetPackGUID());
2857 data << uint8(m_cast_count); // pending spell cast?
2858 data << uint32(m_spellInfo->Id); // spellId
2859 data << uint32(castFlags); // cast flags
2860 data << uint32(m_timer); // delay?
2862 m_targets.write(&data);
2864 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2865 data << uint32(0);
2867 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2869 uint8 v1 = 0;//m_runesState;
2870 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2871 data << uint8(v1); // runes state before
2872 data << uint8(v2); // runes state after
2873 for(uint8 i = 0; i < MAX_RUNES; ++i)
2875 uint8 m = (1 << i);
2876 if(m & v1) // usable before...
2877 if(!(m & v2)) // ...but on cooldown now...
2878 data << uint8(0); // some unknown byte (time?)
2882 if ( castFlags & CAST_FLAG_AMMO )
2883 WriteAmmoToPacket(&data);
2885 m_caster->SendMessageToSet(&data, true);
2888 void Spell::SendSpellGo()
2890 // not send invisible spell casting
2891 if(!IsNeedSendToClient())
2892 return;
2894 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2896 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2898 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2899 if(IsRangedSpell())
2900 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2902 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2904 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2905 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2906 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2909 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2911 if(m_CastItem)
2912 data.append(m_CastItem->GetPackGUID());
2913 else
2914 data.append(m_caster->GetPackGUID());
2916 data.append(m_caster->GetPackGUID());
2917 data << uint8(m_cast_count); // pending spell cast?
2918 data << uint32(m_spellInfo->Id); // spellId
2919 data << uint32(castFlags); // cast flags
2920 data << uint32(getMSTime()); // timestamp
2922 WriteSpellGoTargets(&data);
2924 m_targets.write(&data);
2926 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2927 data << uint32(0);
2929 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2931 uint8 v1 = m_runesState;
2932 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2933 data << uint8(v1); // runes state before
2934 data << uint8(v2); // runes state after
2935 for(uint8 i = 0; i < MAX_RUNES; ++i)
2937 uint8 m = (1 << i);
2938 if(m & v1) // usable before...
2939 if(!(m & v2)) // ...but on cooldown now...
2940 data << uint8(0); // some unknown byte (time?)
2944 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2946 data << float(0);
2947 data << uint32(0);
2950 if ( castFlags & CAST_FLAG_AMMO )
2951 WriteAmmoToPacket(&data);
2953 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2955 data << uint32(0);
2956 data << uint32(0);
2959 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2961 data << uint8(0);
2964 m_caster->SendMessageToSet(&data, true);
2967 void Spell::WriteAmmoToPacket( WorldPacket * data )
2969 uint32 ammoInventoryType = 0;
2970 uint32 ammoDisplayID = 0;
2972 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2974 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2975 if(pItem)
2977 ammoInventoryType = pItem->GetProto()->InventoryType;
2978 if( ammoInventoryType == INVTYPE_THROWN )
2979 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2980 else
2982 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2983 if(ammoID)
2985 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2986 if(pProto)
2988 ammoDisplayID = pProto->DisplayInfoID;
2989 ammoInventoryType = pProto->InventoryType;
2992 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
2994 ammoDisplayID = 5996; // normal arrow
2995 ammoInventoryType = INVTYPE_AMMO;
3000 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
3002 *data << uint32(ammoDisplayID);
3003 *data << uint32(ammoInventoryType);
3006 void Spell::WriteSpellGoTargets( WorldPacket * data )
3008 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
3009 uint32 miss = 0;
3010 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3012 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
3014 // possibly SPELL_MISS_IMMUNE2 for this??
3015 ihit->missCondition = SPELL_MISS_IMMUNE2;
3016 miss++;
3018 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3019 hit++;
3020 else
3021 miss++;
3024 *data << (uint8)hit;
3025 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3026 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3027 *data << uint64(ihit->targetGUID);
3029 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3030 *data << uint64(ighit->targetGUID); // Always hits
3032 *data << (uint8)miss;
3033 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3035 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3037 *data << uint64(ihit->targetGUID);
3038 *data << uint8(ihit->missCondition);
3039 if( ihit->missCondition == SPELL_MISS_REFLECT )
3040 *data << uint8(ihit->reflectResult);
3045 void Spell::SendLogExecute()
3047 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3049 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3051 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3052 data.append(m_caster->GetPackGUID());
3053 else
3054 data.append(target->GetPackGUID());
3056 data << uint32(m_spellInfo->Id);
3057 uint32 count1 = 1;
3058 data << uint32(count1); // count1 (effect count?)
3059 for(uint32 i = 0; i < count1; ++i)
3061 data << uint32(m_spellInfo->Effect[0]); // spell effect
3062 uint32 count2 = 1;
3063 data << uint32(count2); // count2 (target count?)
3064 for(uint32 j = 0; j < count2; ++j)
3066 switch(m_spellInfo->Effect[0])
3068 case SPELL_EFFECT_POWER_DRAIN:
3069 if(Unit *unit = m_targets.getUnitTarget())
3070 data.append(unit->GetPackGUID());
3071 else
3072 data << uint8(0);
3073 data << uint32(0);
3074 data << uint32(0);
3075 data << float(0);
3076 break;
3077 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3078 if(Unit *unit = m_targets.getUnitTarget())
3079 data.append(unit->GetPackGUID());
3080 else
3081 data << uint8(0);
3082 data << uint32(0); // count?
3083 break;
3084 case SPELL_EFFECT_INTERRUPT_CAST:
3085 if(Unit *unit = m_targets.getUnitTarget())
3086 data.append(unit->GetPackGUID());
3087 else
3088 data << uint8(0);
3089 data << uint32(0); // spellid
3090 break;
3091 case SPELL_EFFECT_DURABILITY_DAMAGE:
3092 if(Unit *unit = m_targets.getUnitTarget())
3093 data.append(unit->GetPackGUID());
3094 else
3095 data << uint8(0);
3096 data << uint32(0);
3097 data << uint32(0);
3098 break;
3099 case SPELL_EFFECT_OPEN_LOCK:
3100 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3101 if(Item *item = m_targets.getItemTarget())
3102 data.append(item->GetPackGUID());
3103 else
3104 data << uint8(0);
3105 break;
3106 case SPELL_EFFECT_CREATE_ITEM:
3107 case SPELL_EFFECT_CREATE_ITEM_2:
3108 data << uint32(m_spellInfo->EffectItemType[0]);
3109 break;
3110 case SPELL_EFFECT_SUMMON:
3111 case SPELL_EFFECT_TRANS_DOOR:
3112 case SPELL_EFFECT_SUMMON_PET:
3113 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3114 case SPELL_EFFECT_CREATE_HOUSE:
3115 case SPELL_EFFECT_DUEL:
3116 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3117 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3118 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3119 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3120 if(Unit *unit = m_targets.getUnitTarget())
3121 data.append(unit->GetPackGUID());
3122 else if(m_targets.getItemTargetGUID())
3123 data.appendPackGUID(m_targets.getItemTargetGUID());
3124 else if(GameObject *go = m_targets.getGOTarget())
3125 data.append(go->GetPackGUID());
3126 else
3127 data << uint8(0); // guid
3128 break;
3129 case SPELL_EFFECT_FEED_PET:
3130 data << uint32(m_targets.getItemTargetEntry());
3131 break;
3132 case SPELL_EFFECT_DISMISS_PET:
3133 if(Unit *unit = m_targets.getUnitTarget())
3134 data.append(unit->GetPackGUID());
3135 else
3136 data << uint8(0);
3137 break;
3138 case SPELL_EFFECT_RESURRECT:
3139 case SPELL_EFFECT_RESURRECT_NEW:
3140 if(Unit *unit = m_targets.getUnitTarget())
3141 data.append(unit->GetPackGUID());
3142 else
3143 data << uint8(0);
3144 break;
3145 default:
3146 return;
3151 m_caster->SendMessageToSet(&data, true);
3154 void Spell::SendInterrupted(uint8 result)
3156 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3157 data.append(m_caster->GetPackGUID());
3158 data << uint8(m_cast_count);
3159 data << uint32(m_spellInfo->Id);
3160 data << uint8(result);
3161 m_caster->SendMessageToSet(&data, true);
3163 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3164 data.append(m_caster->GetPackGUID());
3165 data << uint8(m_cast_count);
3166 data << uint32(m_spellInfo->Id);
3167 data << uint8(result);
3168 m_caster->SendMessageToSet(&data, true);
3171 void Spell::SendChannelUpdate(uint32 time)
3173 if(time == 0)
3175 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3176 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3179 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3180 return;
3182 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3183 data.append(m_caster->GetPackGUID());
3184 data << uint32(time);
3186 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3189 void Spell::SendChannelStart(uint32 duration)
3191 WorldObject* target = NULL;
3193 // select first not resisted target from target list for _0_ effect
3194 if(!m_UniqueTargetInfo.empty())
3196 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3198 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3200 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3201 break;
3205 else if(!m_UniqueGOTargetInfo.empty())
3207 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3209 if(itr->effectMask & (1<<0) )
3211 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3212 break;
3217 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3219 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3220 data.append(m_caster->GetPackGUID());
3221 data << uint32(m_spellInfo->Id);
3222 data << uint32(duration);
3224 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3227 m_timer = duration;
3228 if(target)
3229 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3230 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3233 void Spell::SendResurrectRequest(Player* target)
3235 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3236 // However, the packet structure differs slightly
3238 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3240 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3241 data << uint64(m_caster->GetGUID());
3242 data << uint32(strlen(sentName)+1);
3244 data << sentName;
3245 data << uint8(0);
3247 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3248 target->GetSession()->SendPacket(&data);
3251 void Spell::SendPlaySpellVisual(uint32 SpellID)
3253 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3254 return;
3256 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3257 data << uint64(m_caster->GetGUID());
3258 data << uint32(SpellID); // spell visual id?
3259 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3262 void Spell::TakeCastItem()
3264 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3265 return;
3267 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3268 if(m_IsTriggeredSpell)
3269 return;
3271 ItemPrototype const *proto = m_CastItem->GetProto();
3273 if(!proto)
3275 // This code is to avoid a crash
3276 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3277 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3278 return;
3281 bool expendable = false;
3282 bool withoutCharges = false;
3284 for (int i = 0; i<5; i++)
3286 if (proto->Spells[i].SpellId)
3288 // item has limited charges
3289 if (proto->Spells[i].SpellCharges)
3291 if (proto->Spells[i].SpellCharges < 0)
3292 expendable = true;
3294 int32 charges = m_CastItem->GetSpellCharges(i);
3296 // item has charges left
3297 if (charges)
3299 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3300 if (proto->Stackable == 1)
3301 m_CastItem->SetSpellCharges(i, charges);
3302 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3305 // all charges used
3306 withoutCharges = (charges == 0);
3311 if (expendable && withoutCharges)
3313 uint32 count = 1;
3314 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3316 // prevent crash at access to deleted m_targets.getItemTarget
3317 if(m_CastItem==m_targets.getItemTarget())
3318 m_targets.setItemTarget(NULL);
3320 m_CastItem = NULL;
3324 void Spell::TakePower()
3326 if(m_CastItem || m_triggeredByAuraSpell)
3327 return;
3329 // health as power used
3330 if(m_spellInfo->powerType == POWER_HEALTH)
3332 m_caster->ModifyHealth( -(int32)m_powerCost );
3333 return;
3336 if(m_spellInfo->powerType >= MAX_POWERS)
3338 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3339 return;
3342 Powers powerType = Powers(m_spellInfo->powerType);
3344 if(powerType == POWER_RUNE)
3346 TakeRunePower();
3347 return;
3350 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3352 // Set the five second timer
3353 if (powerType == POWER_MANA && m_powerCost > 0)
3354 m_caster->SetLastManaUse(getMSTime());
3357 uint8 Spell::CheckRuneCost(uint32 runeCostID)
3359 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3360 return 0;
3362 Player *plr = (Player*)m_caster;
3364 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3365 return 0;
3367 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3369 if(!src)
3370 return 0;
3372 if(src->NoRuneCost())
3373 return 0;
3375 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3377 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3379 runeCost[i] = src->RuneCost[i];
3382 runeCost[RUNE_DEATH] = 0; // calculated later
3384 for(uint32 i = 0; i < MAX_RUNES; ++i)
3386 uint8 rune = plr->GetCurrentRune(i);
3387 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3389 runeCost[rune]--;
3393 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3395 if(runeCost[i] > 0)
3397 runeCost[RUNE_DEATH] += runeCost[i];
3401 if(runeCost[RUNE_DEATH] > 0)
3402 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3404 return 0;
3407 void Spell::TakeRunePower()
3409 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3410 return;
3412 Player *plr = (Player*)m_caster;
3414 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3415 return;
3417 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3419 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3420 return;
3422 m_runesState = plr->GetRunesState(); // store previous state
3424 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3426 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3428 runeCost[i] = src->RuneCost[i];
3431 runeCost[RUNE_DEATH] = 0; // calculated later
3433 for(uint32 i = 0; i < MAX_RUNES; ++i)
3435 uint8 rune = plr->GetCurrentRune(i);
3436 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3438 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3439 runeCost[rune]--;
3443 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3445 if(runeCost[RUNE_DEATH] > 0)
3447 for(uint32 i = 0; i < MAX_RUNES; ++i)
3449 uint8 rune = plr->GetCurrentRune(i);
3450 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3452 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3453 runeCost[rune]--;
3454 plr->ConvertRune(i, plr->GetBaseRune(i));
3455 if(runeCost[RUNE_DEATH] == 0)
3456 break;
3461 // you can gain some runic power when use runes
3462 float rp = src->runePowerGain;;
3463 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3464 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3467 void Spell::TakeReagents()
3469 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3470 return;
3472 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3473 return;
3475 Player* p_caster = (Player*)m_caster;
3476 if (p_caster->CanNoReagentCast(m_spellInfo))
3477 return;
3479 for(uint32 x=0;x<8;x++)
3481 if(m_spellInfo->Reagent[x] <= 0)
3482 continue;
3484 uint32 itemid = m_spellInfo->Reagent[x];
3485 uint32 itemcount = m_spellInfo->ReagentCount[x];
3487 // if CastItem is also spell reagent
3488 if (m_CastItem)
3490 ItemPrototype const *proto = m_CastItem->GetProto();
3491 if( proto && proto->ItemId == itemid )
3493 for(int s=0;s<5;s++)
3495 // CastItem will be used up and does not count as reagent
3496 int32 charges = m_CastItem->GetSpellCharges(s);
3497 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3499 ++itemcount;
3500 break;
3504 m_CastItem = NULL;
3508 // if getItemTarget is also spell reagent
3509 if (m_targets.getItemTargetEntry()==itemid)
3510 m_targets.setItemTarget(NULL);
3512 p_caster->DestroyItemCount(itemid, itemcount, true);
3516 void Spell::HandleThreatSpells(uint32 spellId)
3518 if(!m_targets.getUnitTarget() || !spellId)
3519 return;
3521 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3522 return;
3524 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3525 if(!threatSpell)
3526 return;
3528 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3530 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3533 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3535 unitTarget = pUnitTarget;
3536 itemTarget = pItemTarget;
3537 gameObjTarget = pGOTarget;
3539 uint8 eff = m_spellInfo->Effect[i];
3541 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3543 sLog.outDebug( "Spell: Effect : %u", eff);
3545 if(eff<TOTAL_SPELL_EFFECTS)
3547 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3548 (*this.*SpellEffects[eff])(i);
3551 else
3553 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3554 if (m_CastItem)
3555 EffectEnchantItemTmp(i);
3556 else
3558 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3559 eff, m_spellInfo->Id);
3565 void Spell::TriggerSpell()
3567 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3569 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3570 spell->prepare(&m_targets); // use original spell original targets
3574 uint8 Spell::CanCast(bool strict)
3576 // check cooldowns to prevent cheating
3577 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3579 if(m_triggeredByAuraSpell)
3580 return SPELL_FAILED_DONT_REPORT;
3581 else
3582 return SPELL_FAILED_NOT_READY;
3585 // only allow triggered spells if at an ended battleground
3586 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3587 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3588 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3589 return SPELL_FAILED_DONT_REPORT;
3591 // only check at first call, Stealth auras are already removed at second call
3592 // for now, ignore triggered spells
3593 if( strict && !m_IsTriggeredSpell)
3595 bool checkForm = true;
3596 // Ignore form req aura
3597 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3598 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3600 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3601 continue;
3602 checkForm = false;
3603 break;
3605 if (checkForm)
3607 // Cannot be used in this stance/form
3608 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3609 return shapeError;
3611 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3612 return SPELL_FAILED_ONLY_STEALTHED;
3616 // caster state requirements
3617 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3618 return SPELL_FAILED_CASTER_AURASTATE;
3619 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3620 return SPELL_FAILED_CASTER_AURASTATE;
3622 // Caster aura req check if need
3623 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3624 return SPELL_FAILED_CASTER_AURASTATE;
3625 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3626 return SPELL_FAILED_CASTER_AURASTATE;
3628 // cancel autorepeat spells if cast start when moving
3629 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3630 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3632 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3633 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3634 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3635 return SPELL_FAILED_MOVING;
3638 Unit *target = m_targets.getUnitTarget();
3640 if(target)
3642 // target state requirements (not allowed state), apply to self also
3643 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3644 return SPELL_FAILED_TARGET_AURASTATE;
3646 // Target aura req check if need
3647 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3648 return SPELL_FAILED_CASTER_AURASTATE;
3649 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3650 return SPELL_FAILED_CASTER_AURASTATE;
3652 if(target != m_caster)
3654 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3655 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3656 return SPELL_FAILED_TARGET_AURASTATE;
3658 // Not allow casting on flying player
3659 if (target->isInFlight())
3660 return SPELL_FAILED_BAD_TARGETS;
3662 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3663 return SPELL_FAILED_LINE_OF_SIGHT;
3665 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3666 // this case can be triggered if rank not found (too low-level target for first rank)
3667 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3669 for(int i=0;i<3;i++)
3671 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3672 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3673 return SPELL_FAILED_LOWLEVEL;
3677 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3679 // Additional check for some spells
3680 // If 0 spell effect empty - client not send target data (need use selection)
3681 // TODO: check it on next client version
3682 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3683 m_spellInfo->Effect[0] == 0 && m_spellInfo->EffectImplicitTargetA[1] != TARGET_SELF)
3685 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3686 m_targets.setUnitTarget(target);
3687 else
3688 return SPELL_FAILED_BAD_TARGETS;
3692 // check pet presents
3693 for(int j=0;j<3;j++)
3695 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3697 target = m_caster->GetPet();
3698 if(!target)
3700 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3701 return SPELL_FAILED_DONT_REPORT;
3702 else
3703 return SPELL_FAILED_NO_PET;
3705 break;
3709 //check creature type
3710 //ignore self casts (including area casts when caster selected as target)
3711 if(target != m_caster)
3713 if(!CheckTargetCreatureType(target))
3715 if(target->GetTypeId()==TYPEID_PLAYER)
3716 return SPELL_FAILED_TARGET_IS_PLAYER;
3717 else
3718 return SPELL_FAILED_BAD_TARGETS;
3722 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3723 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3724 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3726 // check correctness positive/negative cast target (pet cast real check and cheating check)
3727 if(IsPositiveSpell(m_spellInfo->Id))
3729 if(m_caster->IsHostileTo(target))
3730 return SPELL_FAILED_BAD_TARGETS;
3732 else
3734 if(m_caster->IsFriendlyTo(target))
3735 return SPELL_FAILED_BAD_TARGETS;
3739 if(IsPositiveSpell(m_spellInfo->Id))
3741 if(target->IsImmunedToSpell(m_spellInfo))
3742 return SPELL_FAILED_TARGET_AURASTATE;
3745 //Must be behind the target.
3746 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3748 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3749 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3751 SendInterrupted(2);
3752 return SPELL_FAILED_NOT_BEHIND;
3756 //Target must be facing you.
3757 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3759 SendInterrupted(2);
3760 return SPELL_FAILED_NOT_INFRONT;
3763 // check if target is in combat
3764 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3766 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3769 // Spell casted only on battleground
3770 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3771 if(!((Player*)m_caster)->InBattleGround())
3772 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3774 // do not allow spells to be cast in arenas
3775 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3776 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3777 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3778 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3779 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3780 if(mapEntry->IsBattleArena())
3781 return SPELL_FAILED_NOT_IN_ARENA;
3783 // zone check
3784 if(uint8 res= GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3785 return res;
3787 // not let players cast spells at mount (and let do it to creatures)
3788 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3789 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3791 if(m_caster->isInFlight())
3792 return SPELL_FAILED_NOT_FLYING;
3793 else
3794 return SPELL_FAILED_NOT_MOUNTED;
3797 // always (except passive spells) check items (focus object can be required for any type casts)
3798 if(!IsPassiveSpell(m_spellInfo->Id))
3799 if(uint8 castResult = CheckItems())
3800 return castResult;
3802 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3803 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3805 for(uint8 j = 0; j < 3; j++)
3807 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3808 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3809 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3810 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3812 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3813 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3814 if(lower==upper)
3815 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);
3817 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3818 float range = GetSpellMaxRange(srange);
3820 Creature* creatureScriptTarget = NULL;
3821 GameObject* goScriptTarget = NULL;
3823 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3825 switch(i_spellST->second.type)
3827 case SPELL_TARGET_TYPE_GAMEOBJECT:
3829 GameObject* p_GameObject = NULL;
3831 if(i_spellST->second.targetEntry)
3833 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3834 Cell cell(p);
3835 cell.data.Part.reserved = ALL_DISTRICT;
3837 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3838 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
3840 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3841 CellLock<GridReadGuard> cell_lock(cell, p);
3842 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3844 if(p_GameObject)
3846 // remember found target and range, next attempt will find more near target with another entry
3847 creatureScriptTarget = NULL;
3848 goScriptTarget = p_GameObject;
3849 range = go_check.GetLastRange();
3852 else if( focusObject ) //Focus Object
3854 float frange = m_caster->GetDistance(focusObject);
3855 if(range >= frange)
3857 creatureScriptTarget = NULL;
3858 goScriptTarget = focusObject;
3859 range = frange;
3862 break;
3864 case SPELL_TARGET_TYPE_CREATURE:
3865 case SPELL_TARGET_TYPE_DEAD:
3866 default:
3868 Creature *p_Creature = NULL;
3870 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3871 Cell cell(p);
3872 cell.data.Part.reserved = ALL_DISTRICT;
3873 cell.SetNoCreate(); // Really don't know what is that???
3875 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3876 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
3878 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3880 CellLock<GridReadGuard> cell_lock(cell, p);
3881 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
3883 if(p_Creature )
3885 creatureScriptTarget = p_Creature;
3886 goScriptTarget = NULL;
3887 range = u_check.GetLastRange();
3889 break;
3894 if(creatureScriptTarget)
3896 // store coordinates for TARGET_SCRIPT_COORDINATES
3897 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3898 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3900 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3902 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3903 AddUnitTarget(creatureScriptTarget, j);
3905 // store explicit target for TARGET_SCRIPT
3906 else
3907 AddUnitTarget(creatureScriptTarget, j);
3909 else if(goScriptTarget)
3911 // store coordinates for TARGET_SCRIPT_COORDINATES
3912 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3913 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3915 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3917 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3918 AddGOTarget(goScriptTarget, j);
3920 // store explicit target for TARGET_SCRIPT
3921 else
3922 AddGOTarget(goScriptTarget, j);
3924 //Missing DB Entry or targets for this spellEffect.
3925 else
3927 // not report target not existence for triggered spells
3928 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3929 return SPELL_FAILED_DONT_REPORT;
3930 else
3931 return SPELL_FAILED_BAD_TARGETS;
3937 if(!m_IsTriggeredSpell)
3938 if(uint8 castResult = CheckRange(strict))
3939 return castResult;
3942 if(uint8 castResult = CheckPower())
3943 return castResult;
3946 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
3947 if(uint8 castResult = CheckCasterAuras())
3948 return castResult;
3950 for (int i = 0; i < 3; i++)
3952 // for effects of spells that have only one target
3953 switch(m_spellInfo->Effect[i])
3955 case SPELL_EFFECT_DUMMY:
3957 if(m_spellInfo->SpellIconID == 1648) // Execute
3959 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3960 return SPELL_FAILED_BAD_TARGETS;
3962 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
3964 if(m_caster->IsInWater())
3965 return SPELL_FAILED_ONLY_ABOVEWATER;
3967 else if(m_spellInfo->SpellIconID==156) // Holy Shock
3969 // spell different for friends and enemies
3970 // hart version required facing
3971 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3972 return SPELL_FAILED_UNIT_NOT_INFRONT;
3974 break;
3976 case SPELL_EFFECT_SCHOOL_DAMAGE:
3978 // Hammer of Wrath
3979 if(m_spellInfo->SpellVisual[0] == 7250)
3981 if (!m_targets.getUnitTarget())
3982 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3984 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3985 return SPELL_FAILED_BAD_TARGETS;
3987 break;
3989 case SPELL_EFFECT_TAMECREATURE:
3991 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3992 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3994 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3995 return SPELL_FAILED_HIGHLEVEL;
3997 // use SMSG_PET_TAME_FAILURE?
3998 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
3999 return SPELL_FAILED_BAD_TARGETS;
4001 if(m_caster->GetPetGUID())
4002 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4004 if(m_caster->GetCharmGUID())
4005 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4007 break;
4009 case SPELL_EFFECT_LEARN_SPELL:
4011 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
4012 break;
4014 Pet* pet = m_caster->GetPet();
4016 if(!pet)
4017 return SPELL_FAILED_NO_PET;
4019 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4021 if(!learn_spellproto)
4022 return SPELL_FAILED_NOT_KNOWN;
4024 if(m_spellInfo->spellLevel > pet->getLevel())
4025 return SPELL_FAILED_LOWLEVEL;
4027 break;
4029 case SPELL_EFFECT_LEARN_PET_SPELL:
4031 Pet* pet = m_caster->GetPet();
4033 if(!pet)
4034 return SPELL_FAILED_NO_PET;
4036 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4038 if(!learn_spellproto)
4039 return SPELL_FAILED_NOT_KNOWN;
4041 if(m_spellInfo->spellLevel > pet->getLevel())
4042 return SPELL_FAILED_LOWLEVEL;
4044 break;
4046 case SPELL_EFFECT_FEED_PET:
4048 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4049 return SPELL_FAILED_BAD_TARGETS;
4051 Item* foodItem = m_targets.getItemTarget();
4052 if(!foodItem)
4053 return SPELL_FAILED_BAD_TARGETS;
4055 Pet* pet = m_caster->GetPet();
4057 if(!pet)
4058 return SPELL_FAILED_NO_PET;
4060 if(!pet->HaveInDiet(foodItem->GetProto()))
4061 return SPELL_FAILED_WRONG_PET_FOOD;
4063 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4064 return SPELL_FAILED_FOOD_LOWLEVEL;
4066 if(m_caster->isInCombat() || pet->isInCombat())
4067 return SPELL_FAILED_AFFECTING_COMBAT;
4069 break;
4071 case SPELL_EFFECT_POWER_BURN:
4072 case SPELL_EFFECT_POWER_DRAIN:
4074 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4075 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4076 if(Unit* target = m_targets.getUnitTarget())
4077 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
4078 return SPELL_FAILED_BAD_TARGETS;
4079 break;
4081 case SPELL_EFFECT_CHARGE:
4083 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4084 return SPELL_FAILED_ROOTED;
4086 break;
4088 case SPELL_EFFECT_SKINNING:
4090 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4091 return SPELL_FAILED_BAD_TARGETS;
4093 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4094 return SPELL_FAILED_TARGET_UNSKINNABLE;
4096 Creature* creature = (Creature*)m_targets.getUnitTarget();
4097 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4099 return SPELL_FAILED_TARGET_NOT_LOOTED;
4102 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4104 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4105 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4106 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
4107 if (ReqValue > skillValue)
4108 return SPELL_FAILED_LOW_CASTLEVEL;
4110 // chance for fail at orange skinning attempt
4111 if( (m_selfContainer && (*m_selfContainer) == this) &&
4112 skillValue < sWorld.GetConfigMaxSkillValue() &&
4113 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
4114 return SPELL_FAILED_TRY_AGAIN;
4116 break;
4118 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4119 case SPELL_EFFECT_OPEN_LOCK:
4121 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4122 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4123 break;
4125 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4126 // we need a go target in case of TARGET_GAMEOBJECT
4127 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4128 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4129 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4130 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4131 return SPELL_FAILED_BAD_TARGETS;
4133 // In BattleGround players can use only flags and banners
4134 if( ((Player*)m_caster)->InBattleGround() &&
4135 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
4136 return SPELL_FAILED_TRY_AGAIN;
4138 // get the lock entry
4139 LockEntry const *lockInfo = NULL;
4140 if (GameObject* go=m_targets.getGOTarget())
4141 lockInfo = sLockStore.LookupEntry(go->GetLockId());
4142 else if(Item* itm=m_targets.getItemTarget())
4143 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
4145 // check lock compatibility
4146 if (lockInfo)
4148 // check for lock - key pair (checked by client also, just prevent cheating
4149 bool ok_key = false;
4150 for(int it = 0; it < 8; ++it)
4152 switch(lockInfo->Type[it])
4154 case LOCK_KEY_NONE:
4155 break;
4156 case LOCK_KEY_ITEM:
4158 if(lockInfo->Index[it])
4160 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4161 ok_key =true;
4162 break;
4165 case LOCK_KEY_SKILL:
4167 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->Index[it])
4168 break;
4170 switch(lockInfo->Index[it])
4172 case LOCKTYPE_HERBALISM:
4173 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
4174 ok_key =true;
4175 break;
4176 case LOCKTYPE_MINING:
4177 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
4178 ok_key =true;
4179 break;
4180 default:
4181 ok_key =true;
4182 break;
4186 if(ok_key)
4187 break;
4190 if(!ok_key)
4191 return SPELL_FAILED_BAD_TARGETS;
4194 // chance for fail at orange mining/herb/LockPicking gathering attempt
4195 if (!m_selfContainer || ((*m_selfContainer) != this))
4196 break;
4198 // get the skill value of the player
4199 int32 SkillValue = 0;
4200 bool canFailAtMax = true;
4201 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
4203 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
4204 canFailAtMax = false;
4206 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
4208 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
4209 canFailAtMax = false;
4211 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4212 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
4214 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
4215 if(m_CastItem)
4216 SkillValue = 0;
4218 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
4219 SkillValue += m_currentBasePoints[i]+1;
4221 // get the required lock value
4222 int32 ReqValue=0;
4223 if (lockInfo)
4225 // check for lock - key pair
4226 bool ok = false;
4227 for(int it = 0; it < 8; ++it)
4229 if(lockInfo->Type[it]==LOCK_KEY_ITEM && lockInfo->Index[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4231 // if so, we're good to go
4232 ok = true;
4233 break;
4236 if(ok)
4237 break;
4239 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4240 ReqValue = lockInfo->Skill[1];
4241 else
4242 ReqValue = lockInfo->Skill[0];
4245 // skill doesn't meet the required value
4246 if (ReqValue > SkillValue)
4247 return SPELL_FAILED_LOW_CASTLEVEL;
4249 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4250 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
4251 return SPELL_FAILED_TRY_AGAIN;
4253 break;
4255 case SPELL_EFFECT_SUMMON_DEAD_PET:
4257 Creature *pet = m_caster->GetPet();
4258 if(!pet)
4259 return SPELL_FAILED_NO_PET;
4261 if(pet->isAlive())
4262 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4264 break;
4266 // This is generic summon effect
4267 case SPELL_EFFECT_SUMMON:
4269 switch(m_spellInfo->EffectMiscValueB[i])
4271 case SUMMON_TYPE_POSESSED:
4272 case SUMMON_TYPE_POSESSED2:
4273 case SUMMON_TYPE_DEMON:
4274 case SUMMON_TYPE_SUMMON:
4276 if(m_caster->GetPetGUID())
4277 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4279 if(m_caster->GetCharmGUID())
4280 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4281 break;
4284 break;
4286 // Not used for summon?
4287 case SPELL_EFFECT_SUMMON_PHANTASM:
4289 if(m_caster->GetPetGUID())
4290 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4292 if(m_caster->GetCharmGUID())
4293 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4295 break;
4297 case SPELL_EFFECT_SUMMON_PET:
4299 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4302 Pet* pet = ((Player*)m_caster)->GetPet();
4304 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4306 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4307 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4309 else
4310 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4313 if(m_caster->GetCharmGUID())
4314 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4316 break;
4318 case SPELL_EFFECT_SUMMON_PLAYER:
4320 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4321 return SPELL_FAILED_BAD_TARGETS;
4322 if(!((Player*)m_caster)->GetSelection())
4323 return SPELL_FAILED_BAD_TARGETS;
4325 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4326 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4327 return SPELL_FAILED_BAD_TARGETS;
4329 // check if our map is dungeon
4330 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4332 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4333 if(!instance)
4334 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4335 if ( instance->levelMin > target->getLevel() )
4336 return SPELL_FAILED_LOWLEVEL;
4337 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4338 return SPELL_FAILED_HIGHLEVEL;
4340 break;
4342 case SPELL_EFFECT_LEAP:
4343 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4345 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4346 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4347 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4348 // teleport a bit above terrain level to avoid falling below it
4349 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4350 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4351 return SPELL_FAILED_TRY_AGAIN;
4353 float caster_pos_z = m_caster->GetPositionZ();
4354 // Control the caster to not climb or drop when +-fz > 8
4355 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4356 return SPELL_FAILED_TRY_AGAIN;
4358 // not allow use this effect at battleground until battleground start
4359 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4360 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4361 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4362 return SPELL_FAILED_TRY_AGAIN;
4363 break;
4365 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4367 if (m_targets.getUnitTarget()==m_caster)
4368 return SPELL_FAILED_BAD_TARGETS;
4369 break;
4371 default:break;
4375 for (int i = 0; i < 3; i++)
4377 switch(m_spellInfo->EffectApplyAuraName[i])
4379 case SPELL_AURA_MOD_POSSESS:
4380 case SPELL_AURA_MOD_CHARM:
4382 if(m_caster->GetPetGUID())
4383 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4385 if(m_caster->GetCharmGUID())
4386 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4388 if(m_caster->GetCharmerGUID())
4389 return SPELL_FAILED_CHARMED;
4391 if(!m_targets.getUnitTarget())
4392 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4394 if(m_targets.getUnitTarget()->GetCharmerGUID())
4395 return SPELL_FAILED_CHARMED;
4397 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4398 return SPELL_FAILED_HIGHLEVEL;
4400 break;
4402 case SPELL_AURA_MOUNTED:
4404 if (m_caster->IsInWater())
4405 return SPELL_FAILED_ONLY_ABOVEWATER;
4407 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4408 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4410 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4411 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4412 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4414 ShapeshiftForm form = m_caster->m_form;
4415 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4416 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4417 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4418 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4419 return SPELL_FAILED_NOT_SHAPESHIFT;
4421 break;
4423 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4425 if(!m_targets.getUnitTarget())
4426 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4428 // can be casted at non-friendly unit or own pet/charm
4429 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4430 return SPELL_FAILED_TARGET_FRIENDLY;
4432 break;
4434 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4435 case SPELL_AURA_FLY:
4437 // not allow cast fly spells at old maps by players (all spells is self target)
4438 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4440 if( !((Player*)m_caster)->IsAllowUseFlyMountsHere() )
4441 return SPELL_FAILED_NOT_HERE;
4444 break;
4446 case SPELL_AURA_PERIODIC_MANA_LEECH:
4448 if (!m_targets.getUnitTarget())
4449 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4451 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4452 break;
4454 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4455 return SPELL_FAILED_BAD_TARGETS;
4457 break;
4459 default:
4460 break;
4464 // all ok
4465 return 0;
4468 int16 Spell::PetCanCast(Unit* target)
4470 if(!m_caster->isAlive())
4471 return SPELL_FAILED_CASTER_DEAD;
4473 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4474 return SPELL_FAILED_SPELL_IN_PROGRESS;
4475 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4476 return SPELL_FAILED_AFFECTING_COMBAT;
4478 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4480 //dead owner (pets still alive when owners ressed?)
4481 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4482 return SPELL_FAILED_CASTER_DEAD;
4484 if(!target && m_targets.getUnitTarget())
4485 target = m_targets.getUnitTarget();
4487 bool need = false;
4488 for(uint32 i = 0;i<3;i++)
4490 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)
4492 need = true;
4493 if(!target)
4494 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4495 break;
4498 if(need)
4499 m_targets.setUnitTarget(target);
4501 Unit* _target = m_targets.getUnitTarget();
4503 if(_target) //for target dead/target not valid
4505 if(!_target->isAlive())
4506 return SPELL_FAILED_BAD_TARGETS;
4508 if(IsPositiveSpell(m_spellInfo->Id))
4510 if(m_caster->IsHostileTo(_target))
4511 return SPELL_FAILED_BAD_TARGETS;
4513 else
4515 bool duelvsplayertar = false;
4516 for(int j=0;j<3;j++)
4518 //TARGET_DUELVSPLAYER is positive AND negative
4519 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4521 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4523 return SPELL_FAILED_BAD_TARGETS;
4527 //cooldown
4528 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4529 return SPELL_FAILED_NOT_READY;
4532 uint16 result = CanCast(true);
4533 if(result != 0)
4534 return result;
4535 else
4536 return -1; //this allows to check spell fail 0, in combat
4539 uint8 Spell::CheckCasterAuras() const
4541 // Flag drop spells totally immuned to caster auras
4542 // FIXME: find more nice check for all totally immuned spells
4543 // AttributesEx3 & 0x10000000?
4544 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4545 return 0;
4547 uint8 school_immune = 0;
4548 uint32 mechanic_immune = 0;
4549 uint32 dispel_immune = 0;
4551 //Check if the spell grants school or mechanic immunity.
4552 //We use bitmasks so the loop is done only once and not on every aura check below.
4553 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4555 for(int i = 0;i < 3; i ++)
4557 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4558 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4559 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4560 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4561 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4562 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4564 //immune movement impairment and loss of control
4565 if(m_spellInfo->Id==(uint32)42292)
4566 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4569 //Check whether the cast should be prevented by any state you might have.
4570 uint8 prevented_reason = 0;
4571 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4572 if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4573 prevented_reason = SPELL_FAILED_STUNNED;
4574 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4575 prevented_reason = SPELL_FAILED_CONFUSED;
4576 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4577 prevented_reason = SPELL_FAILED_FLEEING;
4578 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4579 prevented_reason = SPELL_FAILED_SILENCED;
4580 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4581 prevented_reason = SPELL_FAILED_PACIFIED;
4583 // Attr must make flag drop spell totally immune from all effects
4584 if(prevented_reason)
4586 if(school_immune || mechanic_immune || dispel_immune)
4588 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4589 Unit::AuraMap const& auras = m_caster->GetAuras();
4590 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4592 if(itr->second)
4594 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4595 continue;
4596 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4597 continue;
4598 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4599 continue;
4601 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4602 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4603 switch(itr->second->GetModifier()->m_auraname)
4605 case SPELL_AURA_MOD_STUN:
4606 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4607 return SPELL_FAILED_STUNNED;
4608 break;
4609 case SPELL_AURA_MOD_CONFUSE:
4610 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4611 return SPELL_FAILED_CONFUSED;
4612 break;
4613 case SPELL_AURA_MOD_FEAR:
4614 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4615 return SPELL_FAILED_FLEEING;
4616 break;
4617 case SPELL_AURA_MOD_SILENCE:
4618 case SPELL_AURA_MOD_PACIFY:
4619 case SPELL_AURA_MOD_PACIFY_SILENCE:
4620 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4621 return SPELL_FAILED_PACIFIED;
4622 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4623 return SPELL_FAILED_SILENCED;
4624 break;
4629 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4630 else
4631 return prevented_reason;
4633 return 0; // all ok
4636 bool Spell::CanAutoCast(Unit* target)
4638 uint64 targetguid = target->GetGUID();
4640 for(uint32 j = 0;j<3;j++)
4642 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4644 if( m_spellInfo->StackAmount <= 1)
4646 if( target->HasAura(m_spellInfo->Id, j) )
4647 return false;
4649 else
4651 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4652 return false;
4655 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4657 if( target->HasAura(m_spellInfo->Id, j) )
4658 return false;
4662 int16 result = PetCanCast(target);
4664 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4666 FillTargetMap();
4667 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4668 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4669 if( ihit->targetGUID == targetguid )
4670 return true;
4672 return false; //target invalid
4675 uint8 Spell::CheckRange(bool strict)
4677 float range_mod;
4679 // self cast doesn't need range checking -- also for Starshards fix
4680 if (m_spellInfo->rangeIndex == 1) return 0;
4682 if (strict) //add radius of caster
4683 range_mod = 1.25;
4684 else //add radius of caster and ~5 yds "give"
4685 range_mod = 6.25;
4687 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4688 float max_range = GetSpellMaxRange(srange) + range_mod;
4689 float min_range = GetSpellMinRange(srange);
4691 if(Player* modOwner = m_caster->GetSpellModOwner())
4692 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4694 Unit *target = m_targets.getUnitTarget();
4696 if(target && target != m_caster)
4698 // distance from target center in checks
4699 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4700 if(dist > max_range)
4701 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4702 if(dist < min_range)
4703 return SPELL_FAILED_TOO_CLOSE;
4704 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4705 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4706 return SPELL_FAILED_UNIT_NOT_INFRONT;
4709 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4711 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4712 if(dist > max_range)
4713 return SPELL_FAILED_OUT_OF_RANGE;
4714 if(dist < min_range)
4715 return SPELL_FAILED_TOO_CLOSE;
4718 return 0; // ok
4721 int32 Spell::CalculatePowerCost()
4723 // item cast not used power
4724 if(m_CastItem)
4725 return 0;
4727 // Spell drain all exist power on cast (Only paladin lay of Hands)
4728 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4730 // If power type - health drain all
4731 if (m_spellInfo->powerType == POWER_HEALTH)
4732 return m_caster->GetHealth();
4733 // Else drain all power
4734 if (m_spellInfo->powerType < MAX_POWERS)
4735 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4736 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4737 return 0;
4740 // Base powerCost
4741 int32 powerCost = m_spellInfo->manaCost;
4742 // PCT cost from total amount
4743 if (m_spellInfo->ManaCostPercentage)
4745 switch (m_spellInfo->powerType)
4747 // health as power used
4748 case POWER_HEALTH:
4749 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4750 break;
4751 case POWER_MANA:
4752 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4753 break;
4754 case POWER_RAGE:
4755 case POWER_FOCUS:
4756 case POWER_ENERGY:
4757 case POWER_HAPPINESS:
4758 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4759 break;
4760 case POWER_RUNE:
4761 case POWER_RUNIC_POWER:
4762 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4763 break;
4764 default:
4765 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4766 return 0;
4769 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4770 // Flat mod from caster auras by spell school
4771 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4772 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4773 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4774 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4775 // Apply cost mod by spell
4776 if(Player* modOwner = m_caster->GetSpellModOwner())
4777 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4779 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4780 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4782 // PCT mod from user auras by school
4783 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4784 if (powerCost < 0)
4785 powerCost = 0;
4786 return powerCost;
4789 uint8 Spell::CheckPower()
4791 // item cast not used power
4792 if(m_CastItem)
4793 return 0;
4795 // health as power used - need check health amount
4796 if(m_spellInfo->powerType == POWER_HEALTH)
4798 if(m_caster->GetHealth() <= m_powerCost)
4799 return SPELL_FAILED_CASTER_AURASTATE;
4800 return 0;
4802 // Check valid power type
4803 if( m_spellInfo->powerType >= MAX_POWERS )
4805 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4806 return SPELL_FAILED_UNKNOWN;
4809 uint8 failReason = CheckRuneCost(m_spellInfo->runeCostID);
4810 if(failReason)
4811 return failReason;
4813 // Check power amount
4814 Powers powerType = Powers(m_spellInfo->powerType);
4815 if(m_caster->GetPower(powerType) < m_powerCost)
4816 return SPELL_FAILED_NO_POWER;
4817 else
4818 return 0;
4821 uint8 Spell::CheckItems()
4823 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4824 return 0;
4826 uint32 itemid, itemcount;
4827 Player* p_caster = (Player*)m_caster;
4829 if(m_CastItem)
4831 itemid = m_CastItem->GetEntry();
4832 if( !p_caster->HasItemCount(itemid,1) )
4833 return SPELL_FAILED_ITEM_NOT_READY;
4834 else
4836 ItemPrototype const *proto = m_CastItem->GetProto();
4837 if(!proto)
4838 return SPELL_FAILED_ITEM_NOT_READY;
4840 for (int i = 0; i<5; i++)
4842 if (proto->Spells[i].SpellCharges)
4844 if(m_CastItem->GetSpellCharges(i)==0)
4845 return SPELL_FAILED_NO_CHARGES_REMAIN;
4849 uint32 ItemClass = proto->Class;
4850 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4852 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4853 uint8 failReason = 0;
4854 for (int i = 0; i < 3; i++)
4856 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4857 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4858 continue;
4860 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4862 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4864 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4865 continue;
4867 else
4869 failReason = 0;
4870 break;
4874 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4875 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4877 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4879 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4880 continue;
4883 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4884 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4886 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4887 continue;
4889 else
4891 failReason = 0;
4892 break;
4896 if (failReason)
4897 return failReason;
4902 if(m_targets.getItemTargetGUID())
4904 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4905 return SPELL_FAILED_BAD_TARGETS;
4907 if(!m_targets.getItemTarget())
4908 return SPELL_FAILED_ITEM_GONE;
4910 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4911 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4913 // if not item target then required item must be equipped
4914 else
4916 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4917 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4920 if(m_spellInfo->RequiresSpellFocus)
4922 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4923 Cell cell(p);
4924 cell.data.Part.reserved = ALL_DISTRICT;
4926 GameObject* ok = NULL;
4927 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4928 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(ok,go_check);
4930 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4931 CellLock<GridReadGuard> cell_lock(cell, p);
4932 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4934 if(!ok)
4935 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4937 focusObject = ok; // game object found in range
4940 if (!p_caster->CanNoReagentCast(m_spellInfo))
4942 for(uint32 i=0;i<8;i++)
4944 if(m_spellInfo->Reagent[i] <= 0)
4945 continue;
4947 itemid = m_spellInfo->Reagent[i];
4948 itemcount = m_spellInfo->ReagentCount[i];
4950 // if CastItem is also spell reagent
4951 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4953 ItemPrototype const *proto = m_CastItem->GetProto();
4954 if(!proto)
4955 return SPELL_FAILED_ITEM_NOT_READY;
4956 for(int s=0;s<5;s++)
4958 // CastItem will be used up and does not count as reagent
4959 int32 charges = m_CastItem->GetSpellCharges(s);
4960 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4962 ++itemcount;
4963 break;
4967 if( !p_caster->HasItemCount(itemid,itemcount) )
4968 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
4972 uint32 totems = 2;
4973 for(int i=0;i<2;++i)
4975 if(m_spellInfo->Totem[i] != 0)
4977 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4979 totems -= 1;
4980 continue;
4982 }else
4983 totems -= 1;
4985 if(totems != 0)
4986 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
4988 //Check items for TotemCategory
4989 uint32 TotemCategory = 2;
4990 for(int i=0;i<2;++i)
4992 if(m_spellInfo->TotemCategory[i] != 0)
4994 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4996 TotemCategory -= 1;
4997 continue;
5000 else
5001 TotemCategory -= 1;
5003 if(TotemCategory != 0)
5004 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
5006 for(int i = 0; i < 3; i++)
5008 switch (m_spellInfo->Effect[i])
5010 case SPELL_EFFECT_CREATE_ITEM:
5012 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
5014 ItemPosCountVec dest;
5015 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
5016 if (msg != EQUIP_ERR_OK )
5018 p_caster->SendEquipError( msg, NULL, NULL );
5019 return SPELL_FAILED_DONT_REPORT;
5022 break;
5024 case SPELL_EFFECT_ENCHANT_ITEM:
5026 Item* targetItem = m_targets.getItemTarget();
5027 if(!targetItem)
5028 return SPELL_FAILED_ITEM_NOT_FOUND;
5030 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5031 return SPELL_FAILED_LOWLEVEL;
5032 // Not allow enchant in trade slot for some enchant type
5033 if( targetItem->GetOwner() != m_caster )
5035 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5036 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5037 if(!pEnchant)
5038 return SPELL_FAILED_ERROR;
5039 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5040 return SPELL_FAILED_NOT_TRADEABLE;
5042 break;
5044 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5046 Item *item = m_targets.getItemTarget();
5047 if(!item)
5048 return SPELL_FAILED_ITEM_NOT_FOUND;
5049 // Not allow enchant in trade slot for some enchant type
5050 if( item->GetOwner() != m_caster )
5052 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5053 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5054 if(!pEnchant)
5055 return SPELL_FAILED_ERROR;
5056 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5057 return SPELL_FAILED_NOT_TRADEABLE;
5059 break;
5061 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5062 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5063 break;
5064 case SPELL_EFFECT_DISENCHANT:
5066 if(!m_targets.getItemTarget())
5067 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5069 // prevent disenchanting in trade slot
5070 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5071 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5073 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5074 if(!itemProto)
5075 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5077 uint32 item_quality = itemProto->Quality;
5078 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5079 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5080 if (item_disenchantskilllevel == uint32(-1))
5081 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5082 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5083 return SPELL_FAILED_LOW_CASTLEVEL;
5084 if(item_quality > 4 || item_quality < 2)
5085 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5086 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5087 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5088 if (!itemProto->DisenchantID)
5089 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5090 break;
5092 case SPELL_EFFECT_PROSPECTING:
5094 if(!m_targets.getItemTarget())
5095 return SPELL_FAILED_CANT_BE_PROSPECTED;
5096 //ensure item is a prospectable ore
5097 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5098 return SPELL_FAILED_CANT_BE_PROSPECTED;
5099 //prevent prospecting in trade slot
5100 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5101 return SPELL_FAILED_CANT_BE_PROSPECTED;
5102 //Check for enough skill in jewelcrafting
5103 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5104 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5105 return SPELL_FAILED_LOW_CASTLEVEL;
5106 //make sure the player has the required ores in inventory
5107 if(m_targets.getItemTarget()->GetCount() < 5)
5108 return SPELL_FAILED_NEED_MORE_ITEMS;
5110 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5111 return SPELL_FAILED_CANT_BE_PROSPECTED;
5113 break;
5115 case SPELL_EFFECT_MILLING:
5117 if(!m_targets.getItemTarget())
5118 return SPELL_FAILED_CANT_BE_MILLED;
5119 //ensure item is a millable herb
5120 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5121 return SPELL_FAILED_CANT_BE_MILLED;
5122 //prevent milling in trade slot
5123 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5124 return SPELL_FAILED_CANT_BE_MILLED;
5125 //Check for enough skill in inscription
5126 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5127 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5128 return SPELL_FAILED_LOW_CASTLEVEL;
5129 //make sure the player has the required herbs in inventory
5130 if(m_targets.getItemTarget()->GetCount() < 5)
5131 return SPELL_FAILED_NEED_MORE_ITEMS;
5133 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5134 return SPELL_FAILED_CANT_BE_MILLED;
5136 break;
5138 case SPELL_EFFECT_WEAPON_DAMAGE:
5139 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5141 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5142 if( m_attackType != RANGED_ATTACK )
5143 break;
5144 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5145 if(!pItem || pItem->IsBroken())
5146 return SPELL_FAILED_EQUIPPED_ITEM;
5148 switch(pItem->GetProto()->SubClass)
5150 case ITEM_SUBCLASS_WEAPON_THROWN:
5152 uint32 ammo = pItem->GetEntry();
5153 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5154 return SPELL_FAILED_NO_AMMO;
5155 }; break;
5156 case ITEM_SUBCLASS_WEAPON_GUN:
5157 case ITEM_SUBCLASS_WEAPON_BOW:
5158 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5160 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5161 if(!ammo)
5163 // Requires No Ammo
5164 if(m_caster->GetDummyAura(46699))
5165 break; // skip other checks
5167 return SPELL_FAILED_NO_AMMO;
5170 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5171 if(!ammoProto)
5172 return SPELL_FAILED_NO_AMMO;
5174 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5175 return SPELL_FAILED_NO_AMMO;
5177 // check ammo ws. weapon compatibility
5178 switch(pItem->GetProto()->SubClass)
5180 case ITEM_SUBCLASS_WEAPON_BOW:
5181 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5182 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5183 return SPELL_FAILED_NO_AMMO;
5184 break;
5185 case ITEM_SUBCLASS_WEAPON_GUN:
5186 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5187 return SPELL_FAILED_NO_AMMO;
5188 break;
5189 default:
5190 return SPELL_FAILED_NO_AMMO;
5193 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5194 return SPELL_FAILED_NO_AMMO;
5195 }; break;
5196 case ITEM_SUBCLASS_WEAPON_WAND:
5197 default:
5198 break;
5200 break;
5202 default:break;
5206 return uint8(0);
5209 void Spell::Delayed()
5211 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5212 return;
5214 if (m_spellState == SPELL_STATE_DELAYED)
5215 return; // spell is active and can't be time-backed
5217 // spells not loosing casting time ( slam, dynamites, bombs.. )
5218 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5219 return;
5221 //check resist chance
5222 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5223 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5224 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5225 if (roll_chance_i(resistChance))
5226 return;
5228 int32 delaytime = GetNextDelayAtDamageMsTime();
5230 if(int32(m_timer) + delaytime > m_casttime)
5232 delaytime = m_casttime - m_timer;
5233 m_timer = m_casttime;
5235 else
5236 m_timer += delaytime;
5238 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5240 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5241 data.append(m_caster->GetPackGUID());
5242 data << uint32(delaytime);
5244 m_caster->SendMessageToSet(&data,true);
5247 void Spell::DelayedChannel()
5249 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5250 return;
5252 //check resist chance
5253 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5254 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5255 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5256 if (roll_chance_i(resistChance))
5257 return;
5259 int32 delaytime = GetNextDelayAtDamageMsTime();
5261 if(int32(m_timer) < delaytime)
5263 delaytime = m_timer;
5264 m_timer = 0;
5266 else
5267 m_timer -= delaytime;
5269 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5271 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5273 if ((*ihit).missCondition == SPELL_MISS_NONE)
5275 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5276 if (unit)
5278 for (int j=0;j<3;j++)
5279 if( ihit->effectMask & (1<<j) )
5280 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5286 for(int j = 0; j < 3; j++)
5288 // partially interrupt persistent area auras
5289 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5290 if(dynObj)
5291 dynObj->Delay(delaytime);
5294 SendChannelUpdate(m_timer);
5297 void Spell::UpdatePointers()
5299 if(m_originalCasterGUID==m_caster->GetGUID())
5300 m_originalCaster = m_caster;
5301 else
5303 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5304 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5307 m_targets.Update(m_caster);
5310 bool Spell::IsAffectedByAura(Aura *aura)
5312 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5315 bool Spell::CheckTargetCreatureType(Unit* target) const
5317 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5319 // Curse of Doom : not find another way to fix spell target check :/
5320 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5322 // not allow cast at player
5323 if(target->GetTypeId()==TYPEID_PLAYER)
5324 return false;
5326 spellCreatureTargetMask = 0x7FF;
5329 // Dismiss Pet and Taming Lesson skipped
5330 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5331 spellCreatureTargetMask = 0;
5333 if (spellCreatureTargetMask)
5335 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5337 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5339 return true;
5342 CurrentSpellTypes Spell::GetCurrentContainer()
5344 if (IsNextMeleeSwingSpell())
5345 return(CURRENT_MELEE_SPELL);
5346 else if (IsAutoRepeat())
5347 return(CURRENT_AUTOREPEAT_SPELL);
5348 else if (IsChanneledSpell(m_spellInfo))
5349 return(CURRENT_CHANNELED_SPELL);
5350 else
5351 return(CURRENT_GENERIC_SPELL);
5354 bool Spell::CheckTarget( Unit* target, uint32 eff )
5356 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5357 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5359 if (!CheckTargetCreatureType(target))
5360 return false;
5363 // Check Aura spell req (need for AoE spells)
5364 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5365 return false;
5366 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5367 return false;
5369 // Check targets for not_selectable unit flag and remove
5370 // A player can cast spells on his pet (or other controlled unit) though in any state
5371 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5373 // any unattackable target skipped
5374 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5375 return false;
5377 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5378 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5379 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5380 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5381 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5382 return false;
5385 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5386 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5388 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5389 return false;
5391 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5392 return false;
5395 //Check targets for LOS visibility (except spells without range limitations )
5396 switch(m_spellInfo->Effect[eff])
5398 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5399 break;
5400 case SPELL_EFFECT_DUMMY:
5401 if(m_spellInfo->Id!=20577) // Cannibalize
5402 break;
5403 //fall through
5404 case SPELL_EFFECT_RESURRECT_NEW:
5405 // player far away, maybe his corpse near?
5406 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5408 if(!m_targets.getCorpseTargetGUID())
5409 return false;
5411 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5412 if(!corpse)
5413 return false;
5415 if(target->GetGUID()!=corpse->GetOwnerGUID())
5416 return false;
5418 if(!corpse->IsWithinLOSInMap(m_caster))
5419 return false;
5422 // all ok by some way or another, skip normal check
5423 break;
5424 default: // normal case
5425 // Get GO cast coordinates if original caster -> GO
5426 WorldObject *caster = NULL;
5427 if (m_originalCasterGUID)
5428 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
5429 if (!caster)
5430 caster = m_caster;
5431 if(target!=m_caster && !target->IsWithinLOSInMap(caster))
5432 return false;
5433 break;
5436 return true;
5439 Unit* Spell::SelectMagnetTarget()
5441 Unit* target = m_targets.getUnitTarget();
5443 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
5445 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
5446 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
5448 if(Unit* magnet = (*itr)->GetCaster())
5450 if(magnet->IsWithinLOSInMap(m_caster))
5452 target = magnet;
5453 m_targets.setUnitTarget(target);
5454 break;
5460 return target;
5463 bool Spell::IsNeedSendToClient() const
5465 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5466 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5469 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5471 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5472 if(itr->effectMask & (1<<effect))
5473 return true;
5475 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5476 if(itr->effectMask & (1<<effect))
5477 return true;
5479 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5480 if(itr->effectMask & (1<<effect))
5481 return true;
5483 return false;
5486 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5488 m_Spell = spell;
5491 SpellEvent::~SpellEvent()
5493 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5494 m_Spell->cancel();
5496 if (m_Spell->IsDeletable())
5498 delete m_Spell;
5500 else
5502 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5503 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5507 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5509 // update spell if it is not finished
5510 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5511 m_Spell->update(p_time);
5513 // check spell state to process
5514 switch (m_Spell->getState())
5516 case SPELL_STATE_FINISHED:
5518 // spell was finished, check deletable state
5519 if (m_Spell->IsDeletable())
5521 // check, if we do have unfinished triggered spells
5523 return(true); // spell is deletable, finish event
5525 // event will be re-added automatically at the end of routine)
5526 } break;
5528 case SPELL_STATE_CASTING:
5530 // this spell is in channeled state, process it on the next update
5531 // event will be re-added automatically at the end of routine)
5532 } break;
5534 case SPELL_STATE_DELAYED:
5536 // first, check, if we have just started
5537 if (m_Spell->GetDelayStart() != 0)
5539 // no, we aren't, do the typical update
5540 // check, if we have channeled spell on our hands
5541 if (IsChanneledSpell(m_Spell->m_spellInfo))
5543 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5544 // check, if we have casting anything else except this channeled spell and autorepeat
5545 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5547 // another non-melee non-delayed spell is casted now, abort
5548 m_Spell->cancel();
5550 else
5552 // do the action (pass spell to channeling state)
5553 m_Spell->handle_immediate();
5555 // event will be re-added automatically at the end of routine)
5557 else
5559 // run the spell handler and think about what we can do next
5560 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5561 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5562 if (n_offset)
5564 // re-add us to the queue
5565 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5566 return(false); // event not complete
5568 // event complete
5569 // finish update event will be re-added automatically at the end of routine)
5572 else
5574 // delaying had just started, record the moment
5575 m_Spell->SetDelayStart(e_time);
5576 // re-plan the event for the delay moment
5577 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5578 return(false); // event not complete
5580 } break;
5582 default:
5584 // all other states
5585 // event will be re-added automatically at the end of routine)
5586 } break;
5589 // spell processing not complete, plan event on the next update interval
5590 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5591 return(false); // event not complete
5594 void SpellEvent::Abort(uint64 /*e_time*/)
5596 // oops, the spell we try to do is aborted
5597 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5598 m_Spell->cancel();
5601 bool SpellEvent::IsDeletable() const
5603 return m_Spell->IsDeletable();