root/trunk/src/game/Spell.cpp @ 142

Revision 142, 196.4 kB (checked in by yumileroy, 17 years ago)

[svn] Fix teleport spells.
Fix cone spells.
Use interrupt_aura_flag to remove stealth/invisible/feign death auras.

Original author: megamage
Date: 2008-11-01 15:08:12-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include "Common.h"
22#include "Database/DatabaseEnv.h"
23#include "WorldPacket.h"
24#include "WorldSession.h"
25#include "GridNotifiers.h"
26#include "GridNotifiersImpl.h"
27#include "Opcodes.h"
28#include "Log.h"
29#include "UpdateMask.h"
30#include "World.h"
31#include "ObjectMgr.h"
32#include "SpellMgr.h"
33#include "Player.h"
34#include "Pet.h"
35#include "Unit.h"
36#include "Spell.h"
37#include "DynamicObject.h"
38#include "SpellAuras.h"
39#include "Group.h"
40#include "UpdateData.h"
41#include "MapManager.h"
42#include "ObjectAccessor.h"
43#include "CellImpl.h"
44#include "Policies/SingletonImp.h"
45#include "SharedDefines.h"
46#include "Tools.h"
47#include "LootMgr.h"
48#include "VMapFactory.h"
49#include "BattleGround.h"
50#include "Util.h"
51
52#define SPELL_CHANNEL_UPDATE_INTERVAL 1000
53
54extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
55
56bool IsQuestTameSpell(uint32 spellId)
57{
58    SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
59    if (!spellproto) return false;
60
61    return spellproto->Effect[0] == SPELL_EFFECT_THREAT
62        && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
63}
64
65SpellCastTargets::SpellCastTargets()
66{
67    m_unitTarget = NULL;
68    m_itemTarget = NULL;
69    m_GOTarget   = NULL;
70
71    m_unitTargetGUID   = 0;
72    m_GOTargetGUID     = 0;
73    m_CorpseTargetGUID = 0;
74    m_itemTargetGUID   = 0;
75    m_itemTargetEntry  = 0;
76
77    m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
78    m_hasDest = false;
79    m_strTarget = "";
80    m_targetMask = 0;
81}
82
83SpellCastTargets::~SpellCastTargets()
84{
85}
86
87void SpellCastTargets::setUnitTarget(Unit *target)
88{
89    if (!target)
90        return;
91
92    m_unitTarget = target;
93    m_unitTargetGUID = target->GetGUID();
94    m_targetMask |= TARGET_FLAG_UNIT;
95}
96
97void SpellCastTargets::setDestination(float x, float y, float z, bool send, uint32 mapId)
98{
99    m_destX = x;
100    m_destY = y;
101    m_destZ = z;
102    m_hasDest = true;
103    if(send)
104        m_targetMask |= TARGET_FLAG_DEST_LOCATION;
105    if(mapId)
106        m_mapId = mapId;
107}
108
109void SpellCastTargets::setDestination(Unit *target, bool send)
110{
111    if(!target)
112        return;
113
114    m_destX = target->GetPositionX();
115    m_destY = target->GetPositionY();
116    m_destZ = target->GetPositionZ();
117    m_hasDest = true;
118    if(send)
119        m_targetMask |= TARGET_FLAG_DEST_LOCATION;
120}
121
122void SpellCastTargets::setGOTarget(GameObject *target)
123{
124    m_GOTarget = target;
125    m_GOTargetGUID = target->GetGUID();
126    //    m_targetMask |= TARGET_FLAG_OBJECT;
127}
128
129void SpellCastTargets::setItemTarget(Item* item)
130{
131    if(!item)
132        return;
133
134    m_itemTarget = item;
135    m_itemTargetGUID = item->GetGUID();
136    m_itemTargetEntry = item->GetEntry();
137    m_targetMask |= TARGET_FLAG_ITEM;
138}
139
140void SpellCastTargets::setCorpseTarget(Corpse* corpse)
141{
142    m_CorpseTargetGUID = corpse->GetGUID();
143}
144
145void SpellCastTargets::Update(Unit* caster)
146{
147    m_GOTarget   = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
148    m_unitTarget = m_unitTargetGUID ?
149        ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
150    NULL;
151
152    m_itemTarget = NULL;
153    if(caster->GetTypeId()==TYPEID_PLAYER)
154    {
155        if(m_targetMask & TARGET_FLAG_ITEM)
156            m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
157        else
158        {
159            Player* pTrader = ((Player*)caster)->GetTrader();
160            if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
161                m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
162        }
163        if(m_itemTarget)
164            m_itemTargetEntry = m_itemTarget->GetEntry();
165    }
166}
167
168bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
169{
170    if(data->rpos()+4 > data->size())
171        return false;
172
173    *data >> m_targetMask;
174
175    if(m_targetMask == TARGET_FLAG_SELF)
176    {
177        //m_destX = caster->GetPositionX();
178        //m_destY = caster->GetPositionY();
179        //m_destZ = caster->GetPositionZ();
180        m_unitTarget = caster;
181        m_unitTargetGUID = caster->GetGUID();
182        return true;
183    }
184    // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
185    if( m_targetMask & (TARGET_FLAG_UNIT|TARGET_FLAG_UNK2) )
186        if(!readGUID(*data, m_unitTargetGUID))
187            return false;
188
189    if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ))
190        if(!readGUID(*data, m_GOTargetGUID))
191            return false;
192
193    if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
194        if(!readGUID(*data, m_itemTargetGUID))
195            return false;
196
197    /*if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
198    {
199        if(data->rpos()+4+4+4 > data->size())
200            return false;
201
202        *data >> m_srcX >> m_srcY >> m_srcZ;
203        if(!Trinity::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
204            return false;
205    }*/
206
207    if( m_targetMask & (TARGET_FLAG_SOURCE_LOCATION | TARGET_FLAG_DEST_LOCATION) )
208    {
209        if(data->rpos()+4+4+4 > data->size())
210            return false;
211
212        *data >> m_destX >> m_destY >> m_destZ;
213        m_hasDest = true;
214        if(!Trinity::IsValidMapCoord(m_destX, m_destY, m_destZ))
215            return false;
216    }
217
218    if( m_targetMask & TARGET_FLAG_STRING )
219    {
220        if(data->rpos()+1 > data->size())
221            return false;
222
223        *data >> m_strTarget;
224    }
225
226    if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
227        if(!readGUID(*data, m_CorpseTargetGUID))
228            return false;
229
230    // find real units/GOs
231    Update(caster);
232    return true;
233}
234
235void SpellCastTargets::write ( WorldPacket * data )
236{
237    *data << uint32(m_targetMask);
238
239    if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
240    {
241        if(m_targetMask & TARGET_FLAG_UNIT)
242        {
243            if(m_unitTarget)
244                data->append(m_unitTarget->GetPackGUID());
245            else
246                *data << uint8(0);
247        }
248        else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
249        {
250            if(m_GOTarget)
251                data->append(m_GOTarget->GetPackGUID());
252            else
253                *data << uint8(0);
254        }
255        else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
256            data->appendPackGUID(m_CorpseTargetGUID);
257        else
258            *data << uint8(0);
259    }
260
261    if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
262    {
263        if(m_itemTarget)
264            data->append(m_itemTarget->GetPackGUID());
265        else
266            *data << uint8(0);
267    }
268
269    if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
270        *data << m_srcX << m_srcY << m_srcZ;
271
272    if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
273        *data << m_destX << m_destY << m_destZ;
274
275    if( m_targetMask & TARGET_FLAG_STRING )
276        *data << m_strTarget;
277}
278
279Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
280{
281    ASSERT( Caster != NULL && info != NULL );
282    ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
283
284    m_spellInfo = info;
285    m_caster = Caster;
286    m_selfContainer = NULL;
287    m_triggeringContainer = triggeringContainer;
288    m_magnetPair.first = false;
289    m_magnetPair.second = NULL;
290    m_deletable = true;
291    m_delayAtDamageCount = 0;
292
293    m_applyMultiplierMask = 0;
294
295    // Get data for type of attack
296    switch (m_spellInfo->DmgClass)
297    {
298        case SPELL_DAMAGE_CLASS_MELEE:
299            if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
300                m_attackType = OFF_ATTACK;
301            else
302                m_attackType = BASE_ATTACK;
303            break;
304        case SPELL_DAMAGE_CLASS_RANGED:
305            m_attackType = RANGED_ATTACK;
306            break;
307        default:
308                                                            // Wands
309            if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_WAND)
310                m_attackType = RANGED_ATTACK;
311            else
312                m_attackType = BASE_ATTACK;
313            break;
314    }
315
316    m_spellSchoolMask = GetSpellSchoolMask(info);           // Can be override for some spell (wand shoot for example)
317
318    if(m_attackType == RANGED_ATTACK)
319    {
320        // wand case
321        if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
322        {
323            if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
324                m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
325        }
326    }
327
328    if(originalCasterGUID)
329        m_originalCasterGUID = originalCasterGUID;
330    else
331        m_originalCasterGUID = m_caster->GetGUID();
332
333    if(m_originalCasterGUID==m_caster->GetGUID())
334        m_originalCaster = m_caster;
335    else
336    {
337        m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
338        if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
339    }
340
341    for(int i=0; i <3; ++i)
342        m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
343
344    m_spellState = SPELL_STATE_NULL;
345
346    m_castPositionX = m_castPositionY = m_castPositionZ = 0;
347    m_TriggerSpells.clear();
348    m_IsTriggeredSpell = triggered;
349    //m_AreaAura = false;
350    m_CastItem = NULL;
351
352    unitTarget = NULL;
353    itemTarget = NULL;
354    gameObjTarget = NULL;
355    focusObject = NULL;
356    m_cast_count = 0;
357    m_triggeredByAuraSpell  = NULL;
358
359    //Auto Shot & Shoot
360    if( m_spellInfo->AttributesEx2 == 0x000020 && !triggered )
361        m_autoRepeat = true;
362    else
363        m_autoRepeat = false;
364
365    m_powerCost = 0;                                        // setup to correct value in Spell::prepare, don't must be used before.
366    m_casttime = 0;                                         // setup to correct value in Spell::prepare, don't must be used before.
367    m_timer = 0;                                            // will set to castime in preper
368
369    m_needAliveTargetMask = 0;
370
371    // determine reflection
372    m_canReflect = false;
373
374    if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
375    {
376        for(int j=0;j<3;j++)
377        {
378            if (m_spellInfo->Effect[j]==0)
379                continue;
380
381            if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
382                m_canReflect = true;
383            else
384                m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
385
386            if(m_canReflect)
387                continue;
388            else
389                break;
390        }
391    }
392
393    CleanupTargetList();
394}
395
396Spell::~Spell()
397{
398}
399
400void Spell::FillTargetMap()
401{
402    // TODO: ADD the correct target FILLS!!!!!!
403
404    for(uint32 i=0;i<3;i++)
405    {
406        // not call for empty effect.
407        // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
408        if(m_spellInfo->Effect[i]==0)
409            continue;
410
411        // TODO: find a way so this is not needed?
412        // for area auras always add caster as target (needed for totems for example)
413        if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
414            AddUnitTarget(m_caster, i);
415
416        std::list<Unit*> tmpUnitMap;
417
418        // Note: this hack with search required until GO casting not implemented
419        // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
420        // currently each enemy selected explicitly and self cast damage
421        if(m_spellInfo->EffectImplicitTargetA[i] == TARGET_ALL_AROUND_CASTER
422            && m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA
423            && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
424        {
425            tmpUnitMap.push_back(m_targets.getUnitTarget());
426        }
427        else
428        {
429            SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
430            SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
431        }
432
433        if(m_targets.HasDest())
434        {
435            switch(m_spellInfo->Effect[i])
436            {
437                case SPELL_EFFECT_SUMMON:
438                case SPELL_EFFECT_SUMMON_WILD:
439                case SPELL_EFFECT_SUMMON_GUARDIAN:
440                case SPELL_EFFECT_SUMMON_PET:
441                case SPELL_EFFECT_SUMMON_POSSESSED:
442                case SPELL_EFFECT_SUMMON_TOTEM:
443                case SPELL_EFFECT_SUMMON_OBJECT_WILD:
444                case SPELL_EFFECT_SUMMON_TOTEM_SLOT1:
445                case SPELL_EFFECT_SUMMON_TOTEM_SLOT2:
446                case SPELL_EFFECT_SUMMON_TOTEM_SLOT3:
447                case SPELL_EFFECT_SUMMON_TOTEM_SLOT4:
448                case SPELL_EFFECT_SUMMON_CRITTER:
449                case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
450                case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
451                case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
452                case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
453                case SPELL_EFFECT_SUMMON_DEAD_PET:
454                case SPELL_EFFECT_SUMMON_DEMON:
455                {
456                    tmpUnitMap.push_back(m_caster);
457                    break;
458                }
459            }
460        }
461
462        if(!m_spellInfo->EffectImplicitTargetA[i])
463        {
464            switch(m_spellInfo->Effect[i])
465            {
466                case SPELL_EFFECT_PARRY:
467                case SPELL_EFFECT_BLOCK:
468                case SPELL_EFFECT_SKILL: // always with dummy 3 as A
469                case SPELL_EFFECT_LEARN_SPELL:
470                    tmpUnitMap.push_back(m_caster);
471                    break;
472            }
473        }
474
475        if(tmpUnitMap.empty())
476        {
477            /*if( m_spellInfo->EffectImplicitTargetA[i]==TARGET_SCRIPT ||
478                m_spellInfo->EffectImplicitTargetB[i]==TARGET_SCRIPT ||
479                m_spellInfo->EffectImplicitTargetA[i]==TARGET_SCRIPT_COORDINATES ||
480                m_spellInfo->EffectImplicitTargetB[i]==TARGET_SCRIPT_COORDINATES )
481            {
482                if(!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION))
483                    continue;
484            }*/
485
486            // add here custom effects that need default target.
487            // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
488            switch(m_spellInfo->Effect[i])
489            {
490                case SPELL_EFFECT_DUMMY:
491                {
492                    switch(m_spellInfo->Id)
493                    {
494                        case 20577:                         // Cannibalize
495                        {
496                            // non-standard target selection
497                            SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
498                            float max_range = GetSpellMaxRange(srange);
499
500                            CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
501                            Cell cell(p);
502                            cell.data.Part.reserved = ALL_DISTRICT;
503                            cell.SetNoCreate();
504
505                            WorldObject* result = NULL;
506
507                            Trinity::CannibalizeObjectCheck u_check(m_caster, max_range);
508                            Trinity::WorldObjectSearcher<Trinity::CannibalizeObjectCheck > searcher(result, u_check);
509
510                            TypeContainerVisitor<Trinity::WorldObjectSearcher<Trinity::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
511                            CellLock<GridReadGuard> cell_lock(cell, p);
512                            cell_lock->Visit(cell_lock, grid_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
513
514                            if(!result)
515                            {
516                                TypeContainerVisitor<Trinity::WorldObjectSearcher<Trinity::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
517                                cell_lock->Visit(cell_lock, world_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
518                            }
519
520                            if(result)
521                            {
522                                switch(result->GetTypeId())
523                                {
524                                    case TYPEID_UNIT:
525                                    case TYPEID_PLAYER:
526                                        tmpUnitMap.push_back((Unit*)result);
527                                        break;
528                                    case TYPEID_CORPSE:
529                                        m_targets.setCorpseTarget((Corpse*)result);
530                                        if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
531                                            tmpUnitMap.push_back(owner);
532                                        break;
533                                }
534                            }
535                            else
536                            {
537                                // clear cooldown at fail
538                                if(m_caster->GetTypeId()==TYPEID_PLAYER)
539                                {
540                                    ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
541
542                                    WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
543                                    data << uint32(m_spellInfo->Id);
544                                    data << uint64(m_caster->GetGUID());
545                                    ((Player*)m_caster)->GetSession()->SendPacket(&data);
546                                }
547
548                                SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
549                                finish(false);
550                            }
551                            break;
552                        }
553                        default:
554                            if(m_targets.getUnitTarget())
555                                tmpUnitMap.push_back(m_targets.getUnitTarget());
556                            break;
557                    }
558                    break;
559                }
560                case SPELL_EFFECT_RESURRECT:
561                case SPELL_EFFECT_CREATE_ITEM:
562                case SPELL_EFFECT_TRIGGER_SPELL:
563                case SPELL_EFFECT_TRIGGER_MISSILE:
564                case SPELL_EFFECT_SKILL_STEP:
565                case SPELL_EFFECT_PROFICIENCY:
566                case SPELL_EFFECT_SELF_RESURRECT:
567                case SPELL_EFFECT_REPUTATION:
568                    if(m_targets.getUnitTarget())
569                        tmpUnitMap.push_back(m_targets.getUnitTarget());
570                    break;
571                case SPELL_EFFECT_SUMMON_PLAYER:
572                    if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
573                    {
574                        Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
575                        if(target)
576                            tmpUnitMap.push_back(target);
577                    }
578                    break;
579                case SPELL_EFFECT_RESURRECT_NEW:
580                    if(m_targets.getUnitTarget())
581                        tmpUnitMap.push_back(m_targets.getUnitTarget());
582                    if(m_targets.getCorpseTargetGUID())
583                    {
584                        Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
585                        if(corpse)
586                        {
587                            Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
588                            if(owner)
589                                tmpUnitMap.push_back(owner);
590                        }
591                    }
592                    break;
593                case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
594                case SPELL_EFFECT_TRANS_DOOR:
595                case SPELL_EFFECT_ADD_FARSIGHT:
596                case SPELL_EFFECT_STUCK:
597                case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
598                    tmpUnitMap.push_back(m_caster);
599                    break;
600                case SPELL_EFFECT_LEARN_PET_SPELL:
601                    if(Pet* pet = m_caster->GetPet())
602                        tmpUnitMap.push_back(pet);
603                    break;
604                case SPELL_EFFECT_ENCHANT_ITEM:
605                case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
606                case SPELL_EFFECT_DISENCHANT:
607                case SPELL_EFFECT_FEED_PET:
608                case SPELL_EFFECT_PROSPECTING:
609                    if(m_targets.getItemTarget())
610                        AddItemTarget(m_targets.getItemTarget(), i);
611                    break;
612                case SPELL_EFFECT_APPLY_AURA:
613                    switch(m_spellInfo->EffectApplyAuraName[i])
614                    {
615                        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)
616                        case SPELL_AURA_ADD_PCT_MODIFIER:
617                            tmpUnitMap.push_back(m_caster);
618                            break;
619                        default:                            // apply to target in other case
620                            break;
621                    }
622                    break;
623                case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
624                                                            // AreaAura
625                    if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
626                        SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
627                    break;
628                case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
629                    if(m_targets.getUnitTarget())
630                    {
631                        tmpUnitMap.push_back(m_targets.getUnitTarget());
632                    }
633                    else if (m_targets.getCorpseTargetGUID())
634                    {
635                        Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
636                        if(corpse)
637                        {
638                            Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
639                            if(owner)
640                                tmpUnitMap.push_back(owner);
641                        }
642                    }
643                    break;
644                default:
645                    break;
646            }
647        }
648        if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
649            m_needAliveTargetMask  |= (1<<i);
650
651        if(m_caster->GetTypeId() == TYPEID_PLAYER)
652        {
653            Player *me = (Player*)m_caster;
654            for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); itr++)
655            {
656                Unit *owner = (*itr)->GetOwner();
657                Unit *u = owner ? owner : (*itr);
658                if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
659                {
660                    me->UpdatePvP(true);
661                    me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
662                    break;
663                }
664            }
665        }
666
667        for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
668        {
669            if(!CheckTarget(*itr, i, false ))
670            {
671                itr = tmpUnitMap.erase(itr);
672                continue;
673            }
674            else
675                ++itr;
676        }
677
678        for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
679            AddUnitTarget((*iunit), i);
680    }
681}
682
683void Spell::CleanupTargetList()
684{
685    m_UniqueTargetInfo.clear();
686    m_UniqueGOTargetInfo.clear();
687    m_UniqueItemInfo.clear();
688    m_countOfHit = 0;
689    m_countOfMiss = 0;
690    m_delayMoment = 0;
691}
692
693void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
694{
695    if( m_spellInfo->Effect[effIndex]==0 )
696        return;
697
698    uint64 targetGUID = pVictim->GetGUID();
699
700    // Lookup target in already in list
701    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
702    {
703        if (targetGUID == ihit->targetGUID)                 // Found in list
704        {
705            ihit->effectMask |= 1<<effIndex;                // Add only effect mask
706            return;
707        }
708    }
709
710    // This is new target calculate data for him
711
712    // Get spell hit result on target
713    TargetInfo target;
714    target.targetGUID = targetGUID;                         // Store target GUID
715    target.effectMask = 1<<effIndex;                        // Store index of effect
716    target.processed  = false;                              // Effects not apply on target
717
718    // Calculate hit result
719    target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
720    if (target.missCondition == SPELL_MISS_NONE)
721        ++m_countOfHit;
722    else
723        ++m_countOfMiss;
724
725    // Spell have speed - need calculate incoming time
726    if (m_spellInfo->speed > 0.0f)
727    {
728        // calculate spell incoming interval
729        float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
730        if (dist < 5.0f) dist = 5.0f;
731        target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
732
733        // Calculate minimum incoming time
734        if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
735            m_delayMoment = target.timeDelay;
736    }
737    else
738        target.timeDelay = 0LL;
739
740    // If target reflect spell back to caster
741    if (target.missCondition==SPELL_MISS_REFLECT)
742    {
743        // Calculate reflected spell result on caster
744        target.reflectResult =  m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
745
746        if (target.reflectResult == SPELL_MISS_REFLECT)     // Impossible reflect again, so simply deflect spell
747            target.reflectResult = SPELL_MISS_PARRY;
748
749        // Increase time interval for reflected spells by 1.5
750        target.timeDelay+=target.timeDelay>>1;
751    }
752    else
753        target.reflectResult = SPELL_MISS_NONE;
754
755    // Add target to list
756    m_UniqueTargetInfo.push_back(target);
757}
758
759void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
760{
761    Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
762    if (unit)
763        AddUnitTarget(unit, effIndex);
764}
765
766void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
767{
768    if( m_spellInfo->Effect[effIndex]==0 )
769        return;
770
771    uint64 targetGUID = pVictim->GetGUID();
772
773    // Lookup target in already in list
774    for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
775    {
776        if (targetGUID == ihit->targetGUID)                 // Found in list
777        {
778            ihit->effectMask |= 1<<effIndex;                // Add only effect mask
779            return;
780        }
781    }
782
783    // This is new target calculate data for him
784
785    GOTargetInfo target;
786    target.targetGUID = targetGUID;
787    target.effectMask = 1<<effIndex;
788    target.processed  = false;                              // Effects not apply on target
789
790    // Spell have speed - need calculate incoming time
791    if (m_spellInfo->speed > 0.0f)
792    {
793        // calculate spell incoming interval
794        float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
795        if (dist < 5.0f) dist = 5.0f;
796        target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
797        if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
798            m_delayMoment = target.timeDelay;
799    }
800    else
801        target.timeDelay = 0LL;
802
803    ++m_countOfHit;
804
805    // Add target to list
806    m_UniqueGOTargetInfo.push_back(target);
807}
808
809void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
810{
811    GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
812    if (go)
813        AddGOTarget(go, effIndex);
814}
815
816void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
817{
818    if( m_spellInfo->Effect[effIndex]==0 )
819        return;
820
821    // Lookup target in already in list
822    for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
823    {
824        if (pitem == ihit->item)                            // Found in list
825        {
826            ihit->effectMask |= 1<<effIndex;                // Add only effect mask
827            return;
828        }
829    }
830
831    // This is new target add data
832
833    ItemTargetInfo target;
834    target.item       = pitem;
835    target.effectMask = 1<<effIndex;
836    m_UniqueItemInfo.push_back(target);
837}
838
839void Spell::doTriggers(SpellMissInfo missInfo, uint32 damage, SpellSchoolMask damageSchoolMask, uint32 block, uint32 absorb, bool crit)
840{
841    // Do triggers depends from hit result (triggers on hit do in effects)
842    // Set aura states depends from hit result
843    if (missInfo!=SPELL_MISS_NONE)
844    {
845        // Miss/dodge/parry/block only for melee based spells
846        // Resist only for magic based spells
847        switch (missInfo)
848        {
849            case SPELL_MISS_MISS:
850                if(m_caster->GetTypeId()== TYPEID_PLAYER)
851                    ((Player*)m_caster)->UpdateWeaponSkill(BASE_ATTACK);
852
853                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_MISS, m_spellInfo, m_IsTriggeredSpell);
854                break;
855            case SPELL_MISS_RESIST:
856                m_caster->ProcDamageAndSpell(unitTarget, PROC_FLAG_TARGET_RESISTS, PROC_FLAG_RESIST_SPELL, 0, damageSchoolMask, m_spellInfo, m_IsTriggeredSpell);
857                break;
858            case SPELL_MISS_DODGE:
859                if(unitTarget->GetTypeId() == TYPEID_PLAYER)
860                    ((Player*)unitTarget)->UpdateDefense();
861
862                // Overpower
863                if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARRIOR)
864                {
865                    ((Player*) m_caster)->AddComboPoints(unitTarget, 1);
866                    m_caster->StartReactiveTimer( REACTIVE_OVERPOWER );
867                }
868
869                // Riposte
870                if (unitTarget->getClass() != CLASS_ROGUE)
871                {
872                    unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
873                    unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
874                }
875
876                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_DODGE, m_spellInfo, m_IsTriggeredSpell);
877                break;
878            case SPELL_MISS_PARRY:
879                // Update victim defense ?
880                if(unitTarget->GetTypeId() == TYPEID_PLAYER)
881                    ((Player*)unitTarget)->UpdateDefense();
882                // Mongoose bite - set only Counterattack here
883                if (unitTarget->getClass() == CLASS_HUNTER)
884                {
885                    unitTarget->ModifyAuraState(AURA_STATE_HUNTER_PARRY,true);
886                    unitTarget->StartReactiveTimer( REACTIVE_HUNTER_PARRY );
887                }
888                else
889                {
890                    unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
891                    unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
892                }
893                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_PARRY, m_spellInfo, m_IsTriggeredSpell);
894                break;
895            case SPELL_MISS_BLOCK:
896                unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
897                unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
898
899                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_BLOCK, m_spellInfo, m_IsTriggeredSpell);
900                break;
901                // Trigger from this events not supported
902            case SPELL_MISS_EVADE:
903            case SPELL_MISS_IMMUNE:
904            case SPELL_MISS_IMMUNE2:
905            case SPELL_MISS_DEFLECT:
906            case SPELL_MISS_ABSORB:
907                // Trigger from reflects need do after get reflect result
908            case SPELL_MISS_REFLECT:
909                break;
910            default:
911                break;
912        }
913    }
914}
915
916void Spell::DoAllEffectOnTarget(TargetInfo *target)
917{
918    if (target->processed)                                  // Check target
919        return;
920    target->processed = true;                               // Target checked in apply effects procedure
921
922    // Get mask of effects for target
923    uint32 mask = target->effectMask;
924    if (mask == 0)                                          // No effects
925        return;
926
927    Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
928    if (!unit)
929        return;
930
931    SpellMissInfo missInfo = target->missCondition;
932    // Need init unitTarget by default unit (can changed in code on reflect)
933    // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
934    unitTarget = unit;
935
936    if (missInfo==SPELL_MISS_NONE)                          // In case spell hit target, do all effect on that target
937        DoSpellHitOnUnit(unit, mask);
938    else if (missInfo == SPELL_MISS_REFLECT)                // In case spell reflect from target, do all effect on caster (if hit)
939    {
940        if (target->reflectResult == SPELL_MISS_NONE)       // If reflected spell hit caster -> do all effect on him
941            DoSpellHitOnUnit(m_caster, mask);
942    }
943
944    // Do triggers only on miss/resist/parry/dodge
945    if (missInfo!=SPELL_MISS_NONE)
946        doTriggers(missInfo);
947
948    // Call scripted function for AI if this spell is casted upon a creature (except pets)
949    if(IS_CREATURE_GUID(target->targetGUID))
950    {
951        // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
952        // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
953        if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
954            ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
955    }
956
957    if( !m_caster->IsFriendlyTo(unit) && !IsPositiveSpell(m_spellInfo->Id))
958    {
959        if( !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
960        {
961            if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
962                unit->SetStandState(PLAYER_STATE_NONE);
963
964            if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
965                ((Creature*)unit)->AI()->AttackStart(m_caster);
966
967            unit->SetInCombatWith(m_caster);
968            m_caster->SetInCombatWith(unit);
969
970            if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
971                m_caster->SetContestedPvP(attackedPlayer);
972        }
973    }
974}
975
976void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
977{
978    if(!unit || !effectMask)
979        return;
980
981    // remove spell_magnet aura after first spell redirect and destroy target if its totem
982    if(m_magnetPair.first && m_magnetPair.second && m_magnetPair.second == unit)
983    {
984        if(unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->isTotem())
985            unit->DealDamage(unit,unit->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
986        return;
987    }
988
989    // Recheck immune (only for delayed spells)
990    if( m_spellInfo->speed && (
991        unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo),true) ||
992        unit->IsImmunedToSpell(m_spellInfo,true) ))
993    {
994        m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
995        return;
996    }
997
998    if( m_caster != unit )
999    {
1000        if( !m_caster->IsFriendlyTo(unit) )
1001        {
1002            // for delayed spells ignore not visible explicit target
1003            if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1004            {
1005                m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1006                return;
1007            }
1008
1009            //if(!IsPositiveSpell(m_spellInfo->Id))
1010            {
1011                //do not remove feign death
1012                unit->RemoveInterruptableAura(AURA_INTERRUPT_FLAG_STEALTH + AURA_INTERRUPT_FLAG_DAMAGE);
1013            }
1014        }
1015        else
1016        {
1017            // for delayed spells ignore negative spells (after duel end) for friendly targets
1018            // TODO: this cause soul transfer bugged
1019            if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1020            {
1021                m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1022                return;
1023            }
1024
1025            // assisting case, healing and resurrection
1026            if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1027                m_caster->SetContestedPvP();
1028            if( unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
1029            {
1030                m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1031                unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1032            }
1033        }
1034    }
1035
1036    // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1037    m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1038    m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1039    // Increase Diminishing on unit, current informations for actually casts will use values above
1040    if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1041        unit->IncrDiminishing(m_diminishGroup);
1042
1043    for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1044    {
1045        if (effectMask & (1<<effectNumber))
1046        {
1047            HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1048            if ( m_applyMultiplierMask & (1 << effectNumber) )
1049            {
1050                // Get multiplier
1051                float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1052                // Apply multiplier mods
1053                if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1054                    modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1055                m_damageMultipliers[effectNumber] *= multiplier;
1056            }
1057        }
1058    }
1059
1060    if(unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->AI())
1061        ((Creature*)unit)->AI()->SpellHit(m_caster, m_spellInfo);
1062
1063    if(m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->AI())
1064        ((Creature*)m_caster)->AI()->SpellHitTarget(unit, m_spellInfo);
1065
1066    if(int32 spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id, 1))
1067    {
1068        if(spell_triggered > 0)
1069            unit->CastSpell(unit, spell_triggered, true, 0, 0, m_caster->GetGUID());
1070        else
1071            unit->RemoveAurasDueToSpell(-spell_triggered);
1072    }
1073}
1074
1075void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1076{
1077    if (target->processed)                                  // Check target
1078        return;
1079    target->processed = true;                               // Target checked in apply effects procedure
1080
1081    uint32 effectMask = target->effectMask;
1082    if(!effectMask)
1083        return;
1084
1085    GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1086    if(!go)
1087        return;
1088
1089    for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1090        if (effectMask & (1<<effectNumber))
1091            HandleEffects(NULL,NULL,go,effectNumber);
1092
1093    // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1094    // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1095    if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1096        ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1097}
1098
1099void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1100{
1101    uint32 effectMask = target->effectMask;
1102    if(!target->item || !effectMask)
1103        return;
1104
1105    for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1106        if (effectMask & (1<<effectNumber))
1107            HandleEffects(NULL, target->item, NULL, effectNumber);
1108}
1109
1110bool Spell::IsAliveUnitPresentInTargetList()
1111{
1112    // Not need check return true
1113    if (m_needAliveTargetMask == 0)
1114        return true;
1115
1116    uint8 needAliveTargetMask = m_needAliveTargetMask;
1117
1118    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1119    {
1120        if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1121        {
1122            Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1123
1124            if (unit && unit->isAlive())
1125                needAliveTargetMask &= ~ihit->effectMask;   // remove from need alive mask effect that have alive target
1126        }
1127    }
1128
1129    // is all effects from m_needAliveTargetMask have alive targets
1130    return needAliveTargetMask==0;
1131}
1132
1133// Helper for Chain Healing
1134// Spell target first
1135// Raidmates then descending by injury suffered (MaxHealth - Health)
1136// Other players/mobs then descending by injury suffered (MaxHealth - Health)
1137struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1138{
1139    const Unit* MainTarget;
1140    ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1141    // functor for operator ">"
1142    bool operator()(Unit const* _Left, Unit const* _Right) const
1143    {
1144        return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1145    }
1146    int32 ChainHealingHash(Unit const* Target) const
1147    {
1148        if (Target == MainTarget)
1149            return 0;
1150        else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1151            ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1152        {
1153            if (Target->GetHealth() == Target->GetMaxHealth())
1154                return 40000;
1155            else
1156                return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1157        }
1158        else
1159            return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1160    }
1161};
1162
1163class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1164{
1165    public:
1166        const Unit* MainTarget;
1167        ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1168
1169        bool operator()(const Unit* Target)
1170        {
1171            return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1172        }
1173};
1174
1175// Helper for targets nearest to the spell target
1176// The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1177struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1178{
1179    const Unit* MainTarget;
1180    TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1181    // functor for operator ">"
1182    bool operator()(const Unit* _Left, const Unit* _Right) const
1183    {
1184        return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1185    }
1186};
1187
1188void Spell::SearchChainTarget(std::list<Unit*> &TagUnitMap, Unit* pUnitTarget, float max_range, uint32 unMaxTargets)
1189{
1190    if(!pUnitTarget)
1191        return;
1192
1193    //FIXME: This very like horrible hack and wrong for most spells
1194    if(m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE)
1195        max_range += unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1196
1197    CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1198    Cell cell(p);
1199    cell.data.Part.reserved = ALL_DISTRICT;
1200    cell.SetNoCreate();
1201
1202    std::list<Unit *> tempUnitMap;
1203
1204    {
1205        Trinity::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, m_caster, max_range);
1206        Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1207
1208        TypeContainerVisitor<Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1209        TypeContainerVisitor<Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1210
1211        CellLock<GridReadGuard> cell_lock(cell, p);
1212        cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1213        cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1214    }
1215
1216    tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1217
1218    if(tempUnitMap.empty())
1219        return;
1220
1221    uint32 t = unMaxTargets;
1222    if(pUnitTarget != m_caster)
1223    {
1224        if(*tempUnitMap.begin() == pUnitTarget)
1225            tempUnitMap.erase(tempUnitMap.begin());
1226        TagUnitMap.push_back(pUnitTarget);
1227        --t;
1228    }
1229    Unit *prev = pUnitTarget;
1230
1231    std::list<Unit*>::iterator next = tempUnitMap.begin();
1232
1233    while(t && next != tempUnitMap.end())
1234    {
1235        if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1236            break;
1237
1238        if(!prev->IsWithinLOSInMap(*next)
1239            || m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE && !m_caster->isInFront(*next, max_range))
1240        {
1241            ++next;
1242            continue;
1243        }
1244
1245        prev = *next;
1246        TagUnitMap.push_back(prev);
1247        tempUnitMap.erase(next);
1248        tempUnitMap.sort(TargetDistanceOrder(prev));
1249        next = tempUnitMap.begin();
1250        --t;
1251    }
1252}
1253
1254void Spell::SearchAreaTarget(std::list<Unit*> &TagUnitMap, float radius, const uint32 &type, SpellTargets TargetType, uint32 entry)
1255{
1256    float x, y;
1257    if(type == PUSH_DEST_CENTER)
1258    {
1259        if(!m_targets.HasDest())
1260        {
1261            sLog.outError( "SPELL: cannot find destination for spell ID %u\n", m_spellInfo->Id );
1262            return;
1263        }
1264        x = m_targets.m_destX;
1265        y = m_targets.m_destY;
1266    }
1267    else
1268    {
1269        x = m_caster->GetPositionX();
1270        y = m_caster->GetPositionY();
1271    }
1272
1273    CellPair p(Trinity::ComputeCellPair(x, y));
1274    Cell cell(p);
1275    cell.data.Part.reserved = ALL_DISTRICT;
1276    cell.SetNoCreate();
1277    CellLock<GridReadGuard> cell_lock(cell, p);
1278
1279    Trinity::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, type, TargetType, entry);
1280   
1281    if(TargetType != SPELL_TARGETS_ENTRY)
1282    {
1283        TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1284        cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1285    }
1286    if(!spellmgr.GetSpellExtraAttr(m_spellInfo->Id, SPELL_EXTRA_ATTR_MAX_TARGETS))
1287    {
1288        TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, GridTypeMapContainer >  grid_object_notifier(notifier);
1289        cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1290    }
1291}
1292
1293Unit* Spell::SearchNearbyTarget(float radius, SpellTargets TargetType, uint32 entry)
1294{
1295    CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1296    Cell cell(p);
1297    cell.data.Part.reserved = ALL_DISTRICT;
1298    cell.SetNoCreate();
1299    CellLock<GridReadGuard> cell_lock(cell, p);
1300
1301    Unit* target = NULL;
1302    switch(TargetType)
1303    {
1304        case SPELL_TARGETS_ENTRY:
1305        {
1306            Creature* target = NULL;
1307            Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster, entry, true, radius);
1308            Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(target, u_check);
1309            TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1310            cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1311            return target;
1312        }break;
1313        default:
1314        case SPELL_TARGETS_AOE_DAMAGE:
1315        {
1316            Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, radius);
1317            Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(target, u_check);
1318            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1319            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1320            cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1321            cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1322        }break;
1323        case SPELL_TARGETS_FRIENDLY:
1324        {
1325            Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, radius);
1326            Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(target, u_check);
1327            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1328            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1329            cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1330            cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1331        }break;
1332    }
1333    return target;
1334}
1335
1336void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1337{
1338    float radius;
1339    if (m_spellInfo->EffectRadiusIndex[i])
1340        radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1341    else
1342        radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1343
1344    uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1345    uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1346    if(!unMaxTargets)
1347        unMaxTargets = spellmgr.GetSpellExtraAttr(m_spellInfo->Id, SPELL_EXTRA_ATTR_MAX_TARGETS);
1348    if(m_originalCaster)
1349    {
1350        if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1351        {
1352            modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1353            modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1354        }
1355    }
1356
1357    switch(cur)
1358    {
1359        // specific unit
1360        case TARGET_SELF:
1361        case TARGET_SELF_FISHING:
1362        {
1363            TagUnitMap.push_back(m_caster);
1364        }break;
1365        case TARGET_MASTER:
1366        {
1367            if(Unit* owner = m_caster->GetCharmerOrOwner())
1368                TagUnitMap.push_back(owner);
1369        }break;
1370        case TARGET_PET:
1371        {
1372            if(Pet* tmpUnit = m_caster->GetPet())
1373                TagUnitMap.push_back(tmpUnit);
1374        }break;
1375        case TARGET_NONCOMBAT_PET:
1376        {
1377            if(Unit* target = m_targets.getUnitTarget())
1378                if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1379                    TagUnitMap.push_back(target);
1380        }break;
1381        case TARGET_SINGLE_FRIEND: // ally
1382        case TARGET_SINGLE_FRIEND_2: // raid member
1383        case TARGET_DUELVSPLAYER: // all (SelectMagnetTarget()?)
1384        case TARGET_UNIT_SINGLE_UNKNOWN:
1385        {
1386            if(m_targets.getUnitTarget())
1387                TagUnitMap.push_back(m_targets.getUnitTarget());
1388        }break;
1389        case TARGET_CHAIN_DAMAGE:
1390        {
1391            if(Unit* pUnitTarget = SelectMagnetTarget())
1392            {
1393                if(EffectChainTarget <= 1)
1394                    TagUnitMap.push_back(pUnitTarget);
1395                else //TODO: chain target should also use magnet target
1396                    SearchChainTarget(TagUnitMap, pUnitTarget, radius, EffectChainTarget);
1397            }
1398        }break;
1399        case TARGET_GAMEOBJECT:
1400        {
1401            if(m_targets.getGOTarget())
1402                AddGOTarget(m_targets.getGOTarget(), i);
1403        }break;
1404        case TARGET_GAMEOBJECT_ITEM:
1405        {
1406            if(m_targets.getGOTargetGUID())
1407                AddGOTarget(m_targets.getGOTarget(), i);
1408            else if(m_targets.getItemTarget())
1409                AddItemTarget(m_targets.getItemTarget(), i);
1410        }break;
1411
1412        // channel
1413        case TARGET_SINGLE_ENEMY:
1414            if(m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
1415            {
1416                if(Unit* target = m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->m_targets.getUnitTarget())
1417                    TagUnitMap.push_back(target);
1418                else
1419                    sLog.outError( "SPELL: cannot find channel spell target for spell ID %u\n", m_spellInfo->Id );
1420            }
1421            else
1422                sLog.outError( "SPELL: no current channeled spell for spell ID %u\n", m_spellInfo->Id );
1423            break;
1424        case TARGET_DEST_CHANNEL:
1425            if(m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
1426            {
1427                if(m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->m_targets.HasDest())
1428                    m_targets = m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->m_targets;
1429                else
1430                    sLog.outError( "SPELL: cannot find channel spell destination for spell ID %u\n", m_spellInfo->Id );
1431            }
1432            else
1433                sLog.outError( "SPELL: no current channeled spell for spell ID %u\n", m_spellInfo->Id );
1434            break;
1435
1436        // reference dest
1437        case TARGET_EFFECT_SELECT:
1438            m_targets.setDestination(m_caster, true);
1439            break;
1440        case TARGET_ALL_AROUND_CASTER:
1441            m_targets.setDestination(m_caster, false);
1442            break;
1443        case TARGET_CURRENT_ENEMY_COORDINATES:
1444            m_targets.setDestination(m_targets.getUnitTarget(), true);
1445            break;
1446        case TARGET_DUELVSPLAYER_COORDINATES: // no ground?
1447            m_targets.setDestination(m_targets.getUnitTarget(), false);
1448            break;
1449        case TARGET_DEST_TABLE_UNKNOWN2:
1450        case TARGET_TABLE_X_Y_Z_COORDINATES:
1451            if(SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id))
1452            {
1453                //TODO: fix this check
1454                if(m_spellInfo->Effect[0] == SPELL_EFFECT_TELEPORT_UNITS
1455                    || m_spellInfo->Effect[1] == SPELL_EFFECT_TELEPORT_UNITS
1456                    || m_spellInfo->Effect[2] == SPELL_EFFECT_TELEPORT_UNITS)
1457                    m_targets.setDestination(st->target_X, st->target_Y, st->target_Z, true, st->target_mapId);
1458                else if(st->target_mapId == m_caster->GetMapId())
1459                    m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1460            }
1461            else
1462                sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1463            break;
1464        case TARGET_INNKEEPER_COORDINATES:
1465            if(m_caster->GetTypeId() == TYPEID_PLAYER)
1466                m_targets.setDestination(((Player*)m_caster)->m_homebindX,((Player*)m_caster)->m_homebindY,((Player*)m_caster)->m_homebindZ, true, ((Player*)m_caster)->m_homebindMapId);
1467            break;
1468
1469        // area targets
1470        case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1471            if(m_spellInfo->Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
1472                break;
1473            m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
1474        case TARGET_ALL_ENEMY_IN_AREA:
1475            SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1476            break;
1477        case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1478            m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
1479        case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1480            SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_FRIENDLY);
1481            break;
1482        case TARGET_AREAEFFECT_CUSTOM:
1483            m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
1484        case TARGET_UNIT_AREA_ENTRY:
1485        {
1486            SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
1487            SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
1488            if(lower==upper)
1489            {
1490                SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1491                //sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = TARGET_SCRIPT, but does not have record in `spell_script_target`",m_spellInfo->Id);
1492                break;
1493            }
1494            // let it be done in one check?
1495            for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
1496            {
1497                if(i_spellST->second.type != SPELL_TARGET_TYPE_CREATURE)
1498                {
1499                    sLog.outError( "SPELL: spell ID %u requires non-creature target\n", m_spellInfo->Id );
1500                    continue;
1501                }
1502                SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_ENTRY, i_spellST->second.targetEntry);
1503            }
1504        }break;
1505        case TARGET_IN_FRONT_OF_CASTER:
1506        case TARGET_UNIT_CONE_ENEMY_UNKNOWN:
1507            switch(spellmgr.GetSpellExtraAttr(m_spellInfo->Id, SPELL_EXTRA_ATTR_CONE_TYPE))
1508            {
1509                default:
1510                case 0:
1511                    SearchAreaTarget(TagUnitMap, radius, PUSH_IN_FRONT, SPELL_TARGETS_AOE_DAMAGE);
1512                    break;
1513                case 1:
1514                    SearchAreaTarget(TagUnitMap, radius, PUSH_IN_BACK, SPELL_TARGETS_AOE_DAMAGE);
1515                    break;
1516                case 2:
1517                    SearchAreaTarget(TagUnitMap, radius, PUSH_IN_LINE, SPELL_TARGETS_AOE_DAMAGE);
1518                    break;
1519            }break;
1520        case TARGET_UNIT_CONE_ALLY:
1521            SearchAreaTarget(TagUnitMap, radius, PUSH_IN_FRONT, SPELL_TARGETS_FRIENDLY);
1522            break;
1523
1524        // nearby target
1525        case TARGET_UNIT_NEARBY_ALLY:
1526        {
1527            if(Unit* pUnitTarget = SearchNearbyTarget(radius, SPELL_TARGETS_FRIENDLY))
1528                TagUnitMap.push_back(pUnitTarget);
1529        }break;
1530        case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1531        {
1532            if(EffectChainTarget <= 1)
1533            {
1534                if(Unit* pUnitTarget = SearchNearbyTarget(radius, SPELL_TARGETS_AOE_DAMAGE))
1535                    TagUnitMap.push_back(pUnitTarget);
1536            }
1537            else
1538                SearchChainTarget(TagUnitMap, m_caster, radius, EffectChainTarget);
1539        }break;
1540        case TARGET_SCRIPT:
1541        case TARGET_SCRIPT_COORDINATES:
1542        {
1543            SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
1544            SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
1545            if(lower==upper)
1546                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);
1547
1548            SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
1549            float range = GetSpellMaxRange(srange);
1550
1551            Creature* creatureScriptTarget = NULL;
1552            GameObject* goScriptTarget = NULL;
1553
1554            for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
1555            {
1556                switch(i_spellST->second.type)
1557                {
1558                case SPELL_TARGET_TYPE_GAMEOBJECT:
1559                    {
1560                        GameObject* p_GameObject = NULL;
1561
1562                        if(i_spellST->second.targetEntry)
1563                        {
1564                            CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1565                            Cell cell(p);
1566                            cell.data.Part.reserved = ALL_DISTRICT;
1567
1568                            Trinity::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
1569                            Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
1570
1571                            TypeContainerVisitor<Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
1572                            CellLock<GridReadGuard> cell_lock(cell, p);
1573                            cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1574
1575                            if(p_GameObject)
1576                            {
1577                                // remember found target and range, next attempt will find more near target with another entry
1578                                creatureScriptTarget = NULL;
1579                                goScriptTarget = p_GameObject;
1580                                range = go_check.GetLastRange();
1581                            }
1582                        }
1583                        else if( focusObject )          //Focus Object
1584                        {
1585                            float frange = m_caster->GetDistance(focusObject);
1586                            if(range >= frange)
1587                            {
1588                                creatureScriptTarget = NULL;
1589                                goScriptTarget = focusObject;
1590                                range = frange;
1591                            }
1592                        }
1593                        break;
1594                    }
1595                case SPELL_TARGET_TYPE_CREATURE:
1596                case SPELL_TARGET_TYPE_DEAD:
1597                default:
1598                    {
1599                        Creature *p_Creature = NULL;
1600
1601                        CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1602                        Cell cell(p);
1603                        cell.data.Part.reserved = ALL_DISTRICT;
1604                        cell.SetNoCreate();             // Really don't know what is that???
1605
1606                        Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
1607                        Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
1608
1609                        TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1610
1611                        CellLock<GridReadGuard> cell_lock(cell, p);
1612                        cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1613
1614                        if(p_Creature )
1615                        {
1616                            creatureScriptTarget = p_Creature;
1617                            goScriptTarget = NULL;
1618                            range = u_check.GetLastRange();
1619                        }
1620                        break;
1621                    }
1622                }
1623            }
1624
1625            if(cur == TARGET_SCRIPT_COORDINATES)
1626            {
1627                if(creatureScriptTarget)
1628                    m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
1629                else if(goScriptTarget)
1630                    m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
1631            }
1632            else
1633            {
1634                if(creatureScriptTarget)
1635                    TagUnitMap.push_back(creatureScriptTarget);
1636                else if(goScriptTarget)
1637                    AddGOTarget(goScriptTarget, i);
1638            }
1639        }break;
1640
1641        // dummy
1642        case TARGET_AREAEFFECT_CUSTOM_2:
1643        {
1644            TagUnitMap.push_back(m_caster);
1645            break;
1646        }
1647
1648        case TARGET_ALL_PARTY_AROUND_CASTER:
1649        case TARGET_ALL_PARTY_AROUND_CASTER_2:
1650        case TARGET_ALL_PARTY:
1651        {
1652            Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1653            Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1654
1655            if(pGroup)
1656            {
1657                uint8 subgroup = pTarget->GetSubGroup();
1658
1659                for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1660                {
1661                    Player* Target = itr->getSource();
1662
1663                    // IsHostileTo check duel and controlled by enemy
1664                    if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1665                    {
1666                        if( m_caster->IsWithinDistInMap(Target, radius) )
1667                            TagUnitMap.push_back(Target);
1668
1669                        if(Pet* pet = Target->GetPet())
1670                            if( m_caster->IsWithinDistInMap(pet, radius) )
1671                                TagUnitMap.push_back(pet);
1672                    }
1673                }
1674            }
1675            else
1676            {
1677                Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1678                if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1679                    TagUnitMap.push_back(ownerOrSelf);
1680                if(Pet* pet = ownerOrSelf->GetPet())
1681                    if( m_caster->IsWithinDistInMap(pet, radius) )
1682                        TagUnitMap.push_back(pet);
1683            }
1684        }break;
1685        case TARGET_RANDOM_RAID_MEMBER:
1686        {
1687            if (m_caster->GetTypeId() == TYPEID_PLAYER)
1688                if(Player* target = ((Player*)m_caster)->GetNextRandomRaidMember(radius))
1689                    TagUnitMap.push_back(target);
1690        }break;
1691        // TARGET_SINGLE_PARTY means that the spells can only be casted on a party member and not on the caster (some sceals, fire shield from imp, etc..)
1692        case TARGET_SINGLE_PARTY:
1693        {
1694            Unit *target = m_targets.getUnitTarget();
1695            // Thoses spells apparently can't be casted on the caster.
1696            if( target && target != m_caster)
1697            {
1698                // Can only be casted on group's members or its pets
1699                Group  *pGroup = NULL;
1700
1701                Unit* owner = m_caster->GetCharmerOrOwner();
1702                Unit *targetOwner = target->GetCharmerOrOwner();
1703                if(owner)
1704                {
1705                    if(owner->GetTypeId() == TYPEID_PLAYER)
1706                    {
1707                        if( target == owner )
1708                        {
1709                            TagUnitMap.push_back(target);
1710                            break;
1711                        }
1712                        pGroup = ((Player*)owner)->GetGroup();
1713                    }
1714                }
1715                else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1716                {
1717                    if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1718                    {
1719                        TagUnitMap.push_back(target);
1720                        break;
1721                    }
1722                    pGroup = ((Player*)m_caster)->GetGroup();
1723                }
1724
1725                if(pGroup)
1726                {
1727                    // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1728                    if(targetOwner)
1729                    {
1730                        if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1731                            target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1732                            target->GetOwnerGUID()==targetOwner->GetGUID() &&
1733                            pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1734                        {
1735                            TagUnitMap.push_back(target);
1736                        }
1737                    }
1738                    // 1Our target can be a player who is on our group
1739                    else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1740                    {
1741                        TagUnitMap.push_back(target);
1742                    }
1743                }
1744            }
1745        }break;
1746        case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1747        {
1748            // targets the ground, not the units in the area
1749            if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1750            {
1751                CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1752                Cell cell(p);
1753                cell.data.Part.reserved = ALL_DISTRICT;
1754                cell.SetNoCreate();
1755
1756                Trinity::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1757
1758                TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1759                TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, GridTypeMapContainer >  grid_object_notifier(notifier);
1760
1761                CellLock<GridReadGuard> cell_lock(cell, p);
1762                cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1763                cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1764            }
1765        }break;
1766        case TARGET_AREAEFFECT_PARTY:
1767        {
1768            Unit* owner = m_caster->GetCharmerOrOwner();
1769            Player *pTarget = NULL;
1770
1771            if(owner)
1772            {
1773                TagUnitMap.push_back(m_caster);
1774                if(owner->GetTypeId() == TYPEID_PLAYER)
1775                    pTarget = (Player*)owner;
1776            }
1777            else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1778            {
1779                if(Unit* target = m_targets.getUnitTarget())
1780                {
1781                    if( target->GetTypeId() != TYPEID_PLAYER)
1782                    {
1783                        if(((Creature*)target)->isPet())
1784                        {
1785                            Unit *targetOwner = target->GetOwner();
1786                            if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1787                                pTarget = (Player*)targetOwner;
1788                        }
1789                    }
1790                    else
1791                        pTarget = (Player*)target;
1792                }
1793            }
1794
1795            Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1796
1797            if(pGroup)
1798            {
1799                uint8 subgroup = pTarget->GetSubGroup();
1800
1801                for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1802                {
1803                    Player* Target = itr->getSource();
1804
1805                    // IsHostileTo check duel and controlled by enemy
1806                    if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1807                    {
1808                        if( pTarget->IsWithinDistInMap(Target, radius) )
1809                            TagUnitMap.push_back(Target);
1810
1811                        if(Pet* pet = Target->GetPet())
1812                            if( pTarget->IsWithinDistInMap(pet, radius) )
1813                                TagUnitMap.push_back(pet);
1814                    }
1815                }
1816            }
1817            else if (owner)
1818            {
1819                if(m_caster->IsWithinDistInMap(owner, radius))
1820                    TagUnitMap.push_back(owner);
1821            }
1822            else if(pTarget)
1823            {
1824                TagUnitMap.push_back(pTarget);
1825
1826                if(Pet* pet = pTarget->GetPet())
1827                    if( m_caster->IsWithinDistInMap(pet, radius) )
1828                        TagUnitMap.push_back(pet);
1829            }
1830
1831        }break;
1832        case TARGET_CHAIN_HEAL:
1833        {
1834            Unit* pUnitTarget = m_targets.getUnitTarget();
1835            if(!pUnitTarget)
1836                break;
1837
1838            if (EffectChainTarget <= 1)
1839                TagUnitMap.push_back(pUnitTarget);
1840            else
1841            {
1842                unMaxTargets = EffectChainTarget;
1843                float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1844
1845                std::list<Unit *> tempUnitMap;
1846
1847                {
1848                    CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1849                    Cell cell(p);
1850                    cell.data.Part.reserved = ALL_DISTRICT;
1851                    cell.SetNoCreate();
1852
1853                    Trinity::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1854
1855                    TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1856                    TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, GridTypeMapContainer >  grid_object_notifier(notifier);
1857
1858                    CellLock<GridReadGuard> cell_lock(cell, p);
1859                    cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1860                    cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1861
1862                }
1863
1864                if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1865                    tempUnitMap.push_front(m_caster);
1866
1867                tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1868
1869                if(tempUnitMap.empty())
1870                    break;
1871
1872                if(*tempUnitMap.begin() == pUnitTarget)
1873                    tempUnitMap.erase(tempUnitMap.begin());
1874
1875                TagUnitMap.push_back(pUnitTarget);
1876                uint32 t = unMaxTargets - 1;
1877                Unit *prev = pUnitTarget;
1878                std::list<Unit*>::iterator next = tempUnitMap.begin();
1879
1880                while(t && next != tempUnitMap.end() )
1881                {
1882                    if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1883                        break;
1884
1885                    if(!prev->IsWithinLOSInMap(*next))
1886                    {
1887                        ++next;
1888                        continue;
1889                    }
1890
1891                    if((*next)->GetHealth() == (*next)->GetMaxHealth())
1892                    {
1893                        next = tempUnitMap.erase(next);
1894                        continue;
1895                    }
1896
1897                    prev = *next;
1898                    TagUnitMap.push_back(prev);
1899                    tempUnitMap.erase(next);
1900                    tempUnitMap.sort(TargetDistanceOrder(prev));
1901                    next = tempUnitMap.begin();
1902
1903                    --t;
1904                }
1905            }
1906        }break;
1907        case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1908        {
1909            Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1910                ? (Player*)m_targets.getUnitTarget() : NULL;
1911
1912            Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1913            if(pGroup)
1914            {
1915                for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1916                {
1917                    Player* Target = itr->getSource();
1918
1919                    // IsHostileTo check duel and controlled by enemy
1920                    if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1921                        targetPlayer->getClass() == Target->getClass() &&
1922                        !m_caster->IsHostileTo(Target) )
1923                    {
1924                        TagUnitMap.push_back(Target);
1925                    }
1926                }
1927            }
1928            else if(m_targets.getUnitTarget())
1929                TagUnitMap.push_back(m_targets.getUnitTarget());
1930            break;
1931        }
1932
1933        // destination around caster
1934        case TARGET_DEST_CASTER_FRONT_LEFT:
1935        case TARGET_DEST_CASTER_BACK_LEFT:
1936        case TARGET_DEST_CASTER_BACK_RIGHT:
1937        case TARGET_DEST_CASTER_FRONT_RIGHT:
1938        case TARGET_DEST_CASTER_FRONT:
1939        case TARGET_MINION:
1940        case TARGET_DEST_CASTER_FRONT_LEAP:
1941        case TARGET_DEST_CASTER_FRONT_UNKNOWN:
1942        case TARGET_DEST_CASTER_BACK:
1943        case TARGET_DEST_CASTER_RIGHT:
1944        case TARGET_DEST_CASTER_LEFT:
1945        case TARGET_DEST_CASTER_RANDOM:
1946        case TARGET_DEST_CASTER_RADIUS:
1947        {
1948            float x, y, z, angle, dist;
1949
1950            if (m_spellInfo->EffectRadiusIndex[i])
1951                dist = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1952            else
1953                dist = 3.0f;//do we need this?
1954            if (cur == TARGET_DEST_CASTER_RANDOM)
1955                dist *= rand_norm(); // This case we need to consider caster size
1956            else
1957                dist -= m_caster->GetObjectSize(); // Size is calculated in GetNearPoint(), but we do not need it
1958            //need a new function to remove this repeated work
1959
1960            switch(cur)
1961            {
1962                case TARGET_DEST_CASTER_FRONT_LEFT: angle = -M_PI/4;    break;
1963                case TARGET_DEST_CASTER_BACK_LEFT:  angle = -3*M_PI/4;  break;
1964                case TARGET_DEST_CASTER_BACK_RIGHT: angle = 3*M_PI/4;   break;
1965                case TARGET_DEST_CASTER_FRONT_RIGHT:angle = M_PI/4;     break;
1966                case TARGET_MINION:
1967                case TARGET_DEST_CASTER_FRONT_LEAP:
1968                case TARGET_DEST_CASTER_FRONT_UNKNOWN:
1969                case TARGET_DEST_CASTER_FRONT:      angle = 0.0f;       break;
1970                case TARGET_DEST_CASTER_BACK:       angle = M_PI;       break;
1971                case TARGET_DEST_CASTER_RIGHT:      angle = M_PI/2;     break;
1972                case TARGET_DEST_CASTER_LEFT:       angle = -M_PI/2;    break;
1973                default:                            angle = rand_norm()*2*M_PI; break;
1974            }
1975
1976            m_caster->GetClosePoint(x, y, z, 0, dist, angle);
1977            m_targets.setDestination(x, y, z); // do not know if has ground visual
1978        }break;
1979
1980        // destination around target
1981        case TARGET_DEST_TARGET_FRONT:
1982        case TARGET_DEST_TARGET_BACK:
1983        case TARGET_DEST_TARGET_RIGHT:
1984        case TARGET_DEST_TARGET_LEFT:
1985        case TARGET_DEST_TARGET_RANDOM:
1986        case TARGET_DEST_TARGET_RADIUS:
1987        {
1988            Unit *target = m_targets.getUnitTarget();
1989            if(!target)
1990            {
1991                sLog.outError("SPELL: no unit target for spell ID %u\n", m_spellInfo->Id);
1992                break;
1993            }
1994
1995            float x, y, z, angle, dist;
1996
1997            if (m_spellInfo->EffectRadiusIndex[i])
1998                dist = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1999            else
2000                dist = 3.0f;//do we need this?
2001            if (cur == TARGET_DEST_TARGET_RANDOM)
2002                dist *= rand_norm(); // This case we need to consider caster size
2003            else
2004                dist -= target->GetObjectSize(); // Size is calculated in GetNearPoint(), but we do not need it
2005            //need a new function to remove this repeated work
2006
2007            switch(cur)
2008            {
2009                case TARGET_DEST_TARGET_FRONT:      angle = 0.0f;       break;
2010                case TARGET_DEST_TARGET_BACK:       angle = M_PI;       break;
2011                case TARGET_DEST_TARGET_RIGHT:      angle = M_PI/2;     break;
2012                case TARGET_DEST_TARGET_LEFT:       angle = -M_PI/2;    break;
2013                default:                            angle = rand_norm()*2*M_PI; break;
2014            }
2015
2016            target->GetClosePoint(x, y, z, 0, dist, angle);
2017            m_targets.setDestination(x, y, z); // do not know if has ground visual
2018        }break;
2019
2020        // destination around destination
2021        case TARGET_DEST_DEST_RANDOM:
2022        {
2023            if(!m_targets.HasDest())
2024            {
2025                sLog.outError("SPELL: no destination for spell ID %u\n", m_spellInfo->Id);
2026                break;
2027            }
2028            float x, y, z, dist, px, py, pz;
2029            dist = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
2030            x = m_targets.m_destX;
2031            y = m_targets.m_destY;
2032            z = m_targets.m_destZ;
2033            m_caster->GetRandomPoint(x, y, z, dist, px, py, pz);
2034            m_targets.setDestination(px, py, pz);
2035        }break;
2036        case TARGET_SELF2:
2037            if(!m_targets.HasDest())
2038            {
2039                sLog.outError("SPELL: no destination for spell ID %u\n", m_spellInfo->Id);
2040                break;
2041            }
2042            break;
2043        default:
2044            break;
2045    }
2046
2047    if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2048    {
2049        // make sure one unit is always removed per iteration
2050        uint32 removed_utarget = 0;
2051        for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2052        {
2053            next = itr;
2054            ++next;
2055            if (!*itr) continue;
2056            if ((*itr) == m_targets.getUnitTarget())
2057            {
2058                TagUnitMap.erase(itr);
2059                removed_utarget = 1;
2060                //        break;
2061            }
2062        }
2063        // remove random units from the map
2064        while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2065        {
2066            uint32 poz = urand(0, TagUnitMap.size()-1);
2067            for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2068            {
2069                if (!*itr) continue;
2070                if (!poz)
2071                {
2072                    TagUnitMap.erase(itr);
2073                    break;
2074                }
2075            }
2076        }
2077        // the player's target will always be added to the map
2078        if (removed_utarget && m_targets.getUnitTarget())
2079            TagUnitMap.push_back(m_targets.getUnitTarget());
2080    }
2081}
2082
2083void Spell::prepare(SpellCastTargets * targets, Aura* triggeredByAura)
2084{
2085    m_targets = *targets;
2086
2087    m_spellState = SPELL_STATE_PREPARING;
2088
2089    m_caster->GetPosition(m_castPositionX, m_castPositionY, m_castPositionZ);
2090    m_castOrientation = m_caster->GetOrientation();
2091
2092    if(triggeredByAura)
2093        m_triggeredByAuraSpell  = triggeredByAura->GetSpellProto();
2094
2095    // create and add update event for this spell
2096    SpellEvent* Event = new SpellEvent(this);
2097    m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2098
2099    //Prevent casting at cast another spell (ServerSide check)
2100    if(m_caster->IsNonMeleeSpellCasted(false, true) && m_cast_count)
2101    {
2102        SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2103        finish(false);
2104        return;
2105    }
2106
2107    if(m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet()))
2108    {
2109        if(objmgr.IsPlayerSpellDisabled(m_spellInfo->Id))
2110        {
2111            SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
2112            finish(false);
2113            return;
2114        }
2115    }
2116    else
2117    {
2118        if(objmgr.IsCreatureSpellDisabled(m_spellInfo->Id))
2119        {
2120            finish(false);
2121            return;
2122        }
2123    }
2124
2125    // Fill cost data
2126    m_powerCost = CalculatePowerCost();
2127
2128    uint8 result = CanCast(true);
2129    if(result != 0 && !IsAutoRepeat())                      //always cast autorepeat dummy for triggering
2130    {
2131        if(triggeredByAura)
2132        {
2133            SendChannelUpdate(0);
2134            triggeredByAura->SetAuraDuration(0);
2135        }
2136        SendCastResult(result);
2137        finish(false);
2138        return;
2139    }
2140
2141    // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2142    m_casttime = GetSpellCastTime(m_spellInfo, this);
2143
2144    // set timer base at cast time
2145    ReSetTimer();
2146
2147    // stealth must be removed at cast starting (at show channel bar)
2148    // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2149    if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2150    {
2151        m_caster->RemoveInterruptableAura(AURA_INTERRUPT_FLAG_STEALTH);
2152    }
2153
2154    if(m_IsTriggeredSpell)
2155        cast(true);
2156    else
2157    {
2158        m_caster->SetCurrentCastedSpell( this );
2159        m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2160        SendSpellStart();
2161    }
2162}
2163
2164void Spell::cancel()
2165{
2166    if(m_spellState == SPELL_STATE_FINISHED)
2167        return;
2168
2169    m_autoRepeat = false;
2170    switch (m_spellState)
2171    {
2172        case SPELL_STATE_PREPARING:
2173        case SPELL_STATE_DELAYED:
2174        {
2175            SendInterrupted(0);
2176            SendCastResult(SPELL_FAILED_INTERRUPTED);
2177        } break;
2178
2179        case SPELL_STATE_CASTING:
2180        {
2181            for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2182            {
2183                if( ihit->missCondition == SPELL_MISS_NONE )
2184                {
2185                    Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2186                    if( unit && unit->isAlive() )
2187                        unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2188                }
2189            }
2190
2191            m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2192            SendChannelUpdate(0);
2193            SendInterrupted(0);
2194            SendCastResult(SPELL_FAILED_INTERRUPTED);
2195        } break;
2196
2197        default:
2198        {
2199        } break;
2200    }
2201
2202    finish(false);
2203    m_caster->RemoveDynObject(m_spellInfo->Id);
2204    m_caster->RemoveGameObject(m_spellInfo->Id,true);
2205}
2206
2207void Spell::cast(bool skipCheck)
2208{
2209    uint8 castResult = 0;
2210
2211    // update pointers base at GUIDs to prevent access to non-existed already object
2212    UpdatePointers();
2213
2214    // cancel at lost main target unit
2215    if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2216    {
2217        cancel();
2218        return;
2219    }
2220
2221    if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2222        m_caster->SetInFront(m_targets.getUnitTarget());
2223
2224    castResult = CheckPower();
2225    if(castResult != 0)
2226    {
2227        SendCastResult(castResult);
2228        finish(false);
2229        return;
2230    }
2231
2232    // triggered cast called from Spell::prepare where it was already checked
2233    if(!skipCheck)
2234    {
2235        castResult = CanCast(false);
2236        if(castResult != 0)
2237        {
2238            SendCastResult(castResult);
2239            finish(false);
2240            return;
2241        }
2242    }
2243
2244    FillTargetMap();
2245
2246    // who did this hack?
2247    // Conflagrate - consumes immolate
2248    if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2249    {
2250        // for caster applied auras only
2251        Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2252        for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2253        {
2254            if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2255                (*i)->GetCasterGUID()==m_caster->GetGUID() )
2256            {
2257                m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2258                break;
2259            }
2260        }
2261    }
2262
2263    if(int32 spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id, 0))
2264    {
2265        if(spell_triggered > 0)
2266            m_caster->CastSpell(m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster, spell_triggered, true);
2267        else
2268            m_caster->RemoveAurasDueToSpell(-spell_triggered);
2269    }
2270
2271    // traded items have trade slot instead of guid in m_itemTargetGUID
2272    // set to real guid to be sent later to the client
2273    m_targets.updateTradeSlotItem();
2274
2275    // CAST SPELL
2276    SendSpellCooldown();
2277
2278    TakePower();
2279    TakeReagents();                                         // we must remove reagents before HandleEffects to allow place crafted item in same slot
2280
2281    if(m_spellState == SPELL_STATE_FINISHED)                // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2282        return;
2283
2284    SendCastResult(castResult);
2285    SendSpellGo();                                          // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2286
2287    // Pass cast spell event to handler (not send triggered by aura spells)
2288    if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE && m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_RANGED && !m_triggeredByAuraSpell)
2289    {
2290        m_caster->ProcDamageAndSpell(m_targets.getUnitTarget(), PROC_FLAG_CAST_SPELL, PROC_FLAG_NONE, 0, SPELL_SCHOOL_MASK_NONE, m_spellInfo, m_IsTriggeredSpell);
2291
2292        // update pointers base at GUIDs to prevent access to non-existed already object
2293        UpdatePointers();                                   // pointers can be invalidate at triggered spell casting
2294    }
2295
2296    // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2297    if (m_spellInfo->speed > 0.0f)
2298    {
2299
2300        // Remove used for cast item if need (it can be already NULL after TakeReagents call
2301        // in case delayed spell remove item at cast delay start
2302        TakeCastItem();
2303
2304        // Okay, maps created, now prepare flags
2305        m_immediateHandled = false;
2306        m_spellState = SPELL_STATE_DELAYED;
2307        SetDelayStart(0);
2308    }
2309    else
2310    {
2311        // Immediate spell, no big deal
2312        handle_immediate();
2313    }
2314}
2315
2316void Spell::handle_immediate()
2317{
2318    // start channeling if applicable
2319    if(IsChanneledSpell(m_spellInfo))
2320    {
2321        m_spellState = SPELL_STATE_CASTING;
2322        SendChannelStart(GetSpellDuration(m_spellInfo));
2323    }
2324
2325    // process immediate effects (items, ground, etc.) also initialize some variables
2326    _handle_immediate_phase();
2327
2328    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2329        DoAllEffectOnTarget(&(*ihit));
2330
2331    for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2332        DoAllEffectOnTarget(&(*ihit));
2333
2334    // spell is finished, perform some last features of the spell here
2335    _handle_finish_phase();
2336
2337    // Remove used for cast item if need (it can be already NULL after TakeReagents call
2338    TakeCastItem();
2339
2340    if(m_spellState != SPELL_STATE_CASTING)
2341        finish(true);                                       // successfully finish spell cast (not last in case autorepeat or channel spell)
2342}
2343
2344uint64 Spell::handle_delayed(uint64 t_offset)
2345{
2346    uint64 next_time = 0;
2347
2348    if (!m_immediateHandled)
2349    {
2350        _handle_immediate_phase();
2351        m_immediateHandled = true;
2352    }
2353
2354    // 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)
2355    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2356    {
2357        if (ihit->processed == false)
2358        {
2359            if ( ihit->timeDelay <= t_offset )
2360                DoAllEffectOnTarget(&(*ihit));
2361            else if( next_time == 0 || ihit->timeDelay < next_time )
2362                next_time = ihit->timeDelay;
2363        }
2364    }
2365
2366    // now recheck gameobject targeting correctness
2367    for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2368    {
2369        if (ighit->processed == false)
2370        {
2371            if ( ighit->timeDelay <= t_offset )
2372                DoAllEffectOnTarget(&(*ighit));
2373            else if( next_time == 0 || ighit->timeDelay < next_time )
2374                next_time = ighit->timeDelay;
2375        }
2376    }
2377    // All targets passed - need finish phase
2378    if (next_time == 0)
2379    {
2380        // spell is finished, perform some last features of the spell here
2381        _handle_finish_phase();
2382
2383        finish(true);                                       // successfully finish spell cast
2384
2385        // return zero, spell is finished now
2386        return 0;
2387    }
2388    else
2389    {
2390        // spell is unfinished, return next execution time
2391        return next_time;
2392    }
2393}
2394
2395void Spell::_handle_immediate_phase()
2396{
2397    // handle some immediate features of the spell here
2398    HandleThreatSpells(m_spellInfo->Id);
2399
2400    m_needSpellLog = IsNeedSendToClient();
2401    for(uint32 j = 0;j<3;j++)
2402    {
2403        if(m_spellInfo->Effect[j]==0)
2404            continue;
2405
2406        // apply Send Event effect to ground in case empty target lists
2407        if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2408        {
2409            HandleEffects(NULL,NULL,NULL, j);
2410            continue;
2411        }
2412
2413        // Don't do spell log, if is school damage spell
2414        if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2415            m_needSpellLog = false;
2416
2417        uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2418        if(m_originalCaster)
2419            if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2420                modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2421
2422        // initialize multipliers
2423        m_damageMultipliers[j] = 1.0f;
2424        if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2425            (EffectChainTarget > 1) )
2426            m_applyMultiplierMask |= 1 << j;
2427    }
2428
2429    // initialize Diminishing Returns Data
2430    m_diminishLevel = DIMINISHING_LEVEL_1;
2431    m_diminishGroup = DIMINISHING_NONE;
2432
2433    // process items
2434    for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2435        DoAllEffectOnTarget(&(*ihit));
2436
2437    // process ground
2438    for(uint32 j = 0;j<3;j++)
2439    {
2440        // persistent area auras target only the ground
2441        if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2442            HandleEffects(NULL,NULL,NULL, j);
2443    }
2444}
2445
2446void Spell::_handle_finish_phase()
2447{
2448    // spell log
2449    if(m_needSpellLog)
2450        SendLogExecute();
2451}
2452
2453void Spell::SendSpellCooldown()
2454{
2455    if(m_caster->GetTypeId() != TYPEID_PLAYER)
2456        return;
2457
2458    Player* _player = (Player*)m_caster;
2459    // Add cooldown for max (disable spell)
2460    // Cooldown started on SendCooldownEvent call
2461    if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2462    {
2463        _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2464        return;
2465    }
2466
2467    // init cooldown values
2468    uint32 cat   = 0;
2469    int32 rec    = -1;
2470    int32 catrec = -1;
2471
2472    // some special item spells without correct cooldown in SpellInfo
2473    // cooldown information stored in item prototype
2474    // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2475
2476    if(m_CastItem)
2477    {
2478        ItemPrototype const* proto = m_CastItem->GetProto();
2479        if(proto)
2480        {
2481            for(int idx = 0; idx < 5; ++idx)
2482            {
2483                if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2484                {
2485                    cat    = proto->Spells[idx].SpellCategory;
2486                    rec    = proto->Spells[idx].SpellCooldown;
2487                    catrec = proto->Spells[idx].SpellCategoryCooldown;
2488                    break;
2489                }
2490            }
2491        }
2492    }
2493
2494    // if no cooldown found above then base at DBC data
2495    if(rec < 0 && catrec < 0)
2496    {
2497        cat = m_spellInfo->Category;
2498        rec = m_spellInfo->RecoveryTime;
2499        catrec = m_spellInfo->CategoryRecoveryTime;
2500    }
2501
2502    // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2503    // prevent 0 cooldowns set by another way
2504    if (rec <= 0 && catrec <= 0 && (cat == 76 || cat == 351))
2505        rec = _player->GetAttackTime(RANGED_ATTACK);
2506
2507    // Now we have cooldown data (if found any), time to apply mods
2508    if(rec > 0)
2509        _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2510
2511    if(catrec > 0)
2512        _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2513
2514    // replace negative cooldowns by 0
2515    if (rec < 0) rec = 0;
2516    if (catrec < 0) catrec = 0;
2517
2518    // no cooldown after applying spell mods
2519    if( rec == 0 && catrec == 0)
2520        return;
2521
2522    time_t curTime = time(NULL);
2523
2524    time_t catrecTime = catrec ? curTime+catrec/1000 : 0;   // in secs
2525    time_t recTime    = rec ? curTime+rec/1000 : catrecTime;// in secs
2526
2527    // self spell cooldown
2528    if(recTime > 0)
2529        _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2530
2531    // category spells
2532    if (catrec > 0)
2533    {
2534        SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2535        if(i_scstore != sSpellCategoryStore.end())
2536        {
2537            for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2538            {
2539                if(*i_scset == m_spellInfo->Id)             // skip main spell, already handled above
2540                    continue;
2541
2542                _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2543            }
2544        }
2545    }
2546}
2547
2548void Spell::update(uint32 difftime)
2549{
2550    // update pointers based at it's GUIDs
2551    UpdatePointers();
2552
2553    if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2554    {
2555        cancel();
2556        return;
2557    }
2558
2559    // check if the player caster has moved before the spell finished
2560    if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2561        (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2562        (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2563    {
2564        // always cancel for channeled spells
2565        if( m_spellState == SPELL_STATE_CASTING )
2566            cancel();
2567        // don't cancel for melee, autorepeat, triggered and instant spells
2568        else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2569            cancel();
2570    }
2571
2572    switch(m_spellState)
2573    {
2574        case SPELL_STATE_PREPARING:
2575        {
2576            if(m_timer)
2577            {
2578                if(difftime >= m_timer)
2579                    m_timer = 0;
2580                else
2581                    m_timer -= difftime;
2582            }
2583
2584            if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2585                cast();
2586        } break;
2587        case SPELL_STATE_CASTING:
2588        {
2589            if(m_timer > 0)
2590            {
2591                if( m_caster->GetTypeId() == TYPEID_PLAYER )
2592                {
2593                    // check if player has jumped before the channeling finished
2594                    if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2595                        cancel();
2596
2597                    // check for incapacitating player states
2598                    if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2599                        cancel();
2600
2601                    // check if player has turned if flag is set
2602                    if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2603                        cancel();
2604                }
2605
2606                // check if there are alive targets left
2607                if (!IsAliveUnitPresentInTargetList())
2608                {
2609                    SendChannelUpdate(0);
2610                    finish();
2611                }
2612
2613                if(difftime >= m_timer)
2614                    m_timer = 0;
2615                else
2616                    m_timer -= difftime;
2617            }
2618
2619            if(m_timer == 0)
2620            {
2621                SendChannelUpdate(0);
2622
2623                // channeled spell processed independently for quest targeting
2624                // cast at creature (or GO) quest objectives update at successful cast channel finished
2625                // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2626                if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2627                {
2628                    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2629                    {
2630                        TargetInfo* target = &*ihit;
2631                        if(!IS_CREATURE_GUID(target->targetGUID))
2632                            continue;
2633
2634                        Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2635                        if (unit==NULL)
2636                            continue;
2637
2638                        ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2639                    }
2640
2641                    for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2642                    {
2643                        GOTargetInfo* target = &*ihit;
2644
2645                        GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2646                        if(!go)
2647                            continue;
2648
2649                        ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2650                    }
2651                }
2652
2653                finish();
2654            }
2655        } break;
2656        default:
2657        {
2658        }break;
2659    }
2660}
2661
2662void Spell::finish(bool ok)
2663{
2664    if(!m_caster)
2665        return;
2666
2667    if(m_spellState == SPELL_STATE_FINISHED)
2668        return;
2669
2670    m_spellState = SPELL_STATE_FINISHED;
2671
2672    //remove spell mods
2673    if (m_caster->GetTypeId() == TYPEID_PLAYER)
2674        ((Player*)m_caster)->RemoveSpellMods(this);
2675
2676    // other code related only to successfully finished spells
2677    if(!ok)
2678        return;
2679
2680    //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2681    Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2682    for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2683    {
2684        SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2685        uint32 auraSpellIdx = (*i)->GetEffIndex();
2686        if (IsAffectedBy(auraSpellInfo, auraSpellIdx))
2687        {
2688            for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2689                if( ihit->effectMask & (1<<auraSpellIdx) )
2690            {
2691                // check m_caster->GetGUID() let load auras at login and speedup most often case
2692                Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2693                if (unit && unit->isAlive())
2694                {
2695                    // Calculate chance at that moment (can be depend for example from combo points)
2696                    int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2697
2698                    if(roll_chance_i(chance))
2699                        m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2700                }
2701            }
2702        }
2703    }
2704
2705    if (IsMeleeAttackResetSpell())
2706    {
2707        m_caster->resetAttackTimer(BASE_ATTACK);
2708        if(m_caster->haveOffhandWeapon())
2709            m_caster->resetAttackTimer(OFF_ATTACK);
2710    }
2711
2712    /*if (IsRangedAttackResetSpell())
2713        m_caster->resetAttackTimer(RANGED_ATTACK);*/
2714
2715    // Clear combo at finish state
2716    if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2717        ((Player*)m_caster)->ClearComboPoints();
2718
2719    // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2720    if(!m_TriggerSpells.empty())
2721        TriggerSpell();
2722
2723    // Stop Attack for some spells
2724    if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2725        m_caster->AttackStop();
2726}
2727
2728void Spell::SendCastResult(uint8 result)
2729{
2730    if (m_caster->GetTypeId() != TYPEID_PLAYER)
2731        return;
2732
2733    if(((Player*)m_caster)->GetSession()->PlayerLoading())  // don't send cast results at loading time
2734        return;
2735
2736    if(result != 0)
2737    {
2738        WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2739        data << uint32(m_spellInfo->Id);
2740        data << uint8(result);                              // problem
2741        data << uint8(m_cast_count);                        // single cast or multi 2.3 (0/1)
2742        switch (result)
2743        {
2744            case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2745                data << uint32(m_spellInfo->RequiresSpellFocus);
2746                break;
2747            case SPELL_FAILED_REQUIRES_AREA:
2748                // hardcode areas limitation case
2749                if( m_spellInfo->Id==41618 || m_spellInfo->Id==41620 )
2750                    data << uint32(3842);
2751                else if( m_spellInfo->Id==41617 || m_spellInfo->Id==41619 )
2752                    data << uint32(3905);
2753                // normal case
2754                else
2755                    data << uint32(m_spellInfo->AreaId);
2756                break;
2757            case SPELL_FAILED_TOTEMS:
2758                if(m_spellInfo->Totem[0])
2759                    data << uint32(m_spellInfo->Totem[0]);
2760                if(m_spellInfo->Totem[1])
2761                    data << uint32(m_spellInfo->Totem[1]);
2762                break;
2763            case SPELL_FAILED_TOTEM_CATEGORY:
2764                if(m_spellInfo->TotemCategory[0])
2765                    data << uint32(m_spellInfo->TotemCategory[0]);
2766                if(m_spellInfo->TotemCategory[1])
2767                    data << uint32(m_spellInfo->TotemCategory[1]);
2768                break;
2769            case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2770                data << uint32(m_spellInfo->EquippedItemClass);
2771                data << uint32(m_spellInfo->EquippedItemSubClassMask);
2772                data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2773                break;
2774        }
2775        ((Player*)m_caster)->GetSession()->SendPacket(&data);
2776    }
2777    else
2778    {
2779        WorldPacket data(SMSG_CLEAR_EXTRA_AURA_INFO, (8+4));
2780        data.append(m_caster->GetPackGUID());
2781        data << uint32(m_spellInfo->Id);
2782        ((Player*)m_caster)->GetSession()->SendPacket(&data);
2783    }
2784}
2785
2786void Spell::SendSpellStart()
2787{
2788    if(!IsNeedSendToClient())
2789        return;
2790
2791    sLog.outDebug("Sending SMSG_SPELL_START id=%u",m_spellInfo->Id);
2792
2793    uint16 castFlags = CAST_FLAG_UNKNOWN1;
2794    if(IsRangedSpell())
2795        castFlags |= CAST_FLAG_AMMO;
2796
2797    Unit * target;
2798    if(!m_targets.getUnitTarget())
2799        target = m_caster;
2800    else
2801        target = m_targets.getUnitTarget();
2802
2803    WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2804    if(m_CastItem)
2805        data.append(m_CastItem->GetPackGUID());
2806    else
2807        data.append(m_caster->GetPackGUID());
2808
2809    data.append(m_caster->GetPackGUID());
2810    data << uint32(m_spellInfo->Id);
2811    data << uint8(m_cast_count);                            // single cast or multi 2.3 (0/1)
2812    data << uint16(castFlags);
2813    data << uint32(m_timer);
2814
2815    m_targets.write(&data);
2816
2817    if( castFlags & CAST_FLAG_AMMO )
2818        WriteAmmoToPacket(&data);
2819
2820    m_caster->SendMessageToSet(&data, true);
2821}
2822
2823void Spell::SendSpellGo()
2824{
2825    // not send invisible spell casting
2826    if(!IsNeedSendToClient())
2827        return;
2828
2829    sLog.outDebug("Sending SMSG_SPELL_GO id=%u",m_spellInfo->Id);
2830
2831    Unit * target;
2832    if(!m_targets.getUnitTarget())
2833        target = m_caster;
2834    else
2835        target = m_targets.getUnitTarget();
2836
2837    uint16 castFlags = CAST_FLAG_UNKNOWN3;
2838    if(IsRangedSpell())
2839        castFlags |= CAST_FLAG_AMMO;
2840
2841    WorldPacket data(SMSG_SPELL_GO, 50);                    // guess size
2842    if(m_CastItem)
2843        data.append(m_CastItem->GetPackGUID());
2844    else
2845        data.append(m_caster->GetPackGUID());
2846
2847    data.append(m_caster->GetPackGUID());
2848    data << uint32(m_spellInfo->Id);
2849    data << uint16(castFlags);
2850    data << uint32(getMSTime());                            // timestamp
2851
2852    WriteSpellGoTargets(&data);
2853
2854    m_targets.write(&data);
2855
2856    if( castFlags & CAST_FLAG_AMMO )
2857        WriteAmmoToPacket(&data);
2858
2859    m_caster->SendMessageToSet(&data, true);
2860}
2861
2862void Spell::WriteAmmoToPacket( WorldPacket * data )
2863{
2864    uint32 ammoInventoryType = 0;
2865    uint32 ammoDisplayID = 0;
2866
2867    if (m_caster->GetTypeId() == TYPEID_PLAYER)
2868    {
2869        Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2870        if(pItem)
2871        {
2872            ammoInventoryType = pItem->GetProto()->InventoryType;
2873            if( ammoInventoryType == INVTYPE_THROWN )
2874                ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2875            else
2876            {
2877                uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2878                if(ammoID)
2879                {
2880                    ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2881                    if(pProto)
2882                    {
2883                        ammoDisplayID = pProto->DisplayInfoID;
2884                        ammoInventoryType = pProto->InventoryType;
2885                    }
2886                }
2887                else if(m_caster->GetDummyAura(46699))      // Requires No Ammo
2888                {
2889                    ammoDisplayID = 5996;                   // normal arrow
2890                    ammoInventoryType = INVTYPE_AMMO;
2891                }
2892            }
2893        }
2894    }
2895    // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2896
2897    *data << uint32(ammoDisplayID);
2898    *data << uint32(ammoInventoryType);
2899}
2900
2901void Spell::WriteSpellGoTargets( WorldPacket * data )
2902{
2903    *data << (uint8)m_countOfHit;
2904    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2905        if ((*ihit).missCondition == SPELL_MISS_NONE)       // Add only hits
2906            *data << uint64(ihit->targetGUID);
2907
2908    for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
2909        *data << uint64(ighit->targetGUID);                 // Always hits
2910
2911    *data << (uint8)m_countOfMiss;
2912    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2913    {
2914        if( ihit->missCondition != SPELL_MISS_NONE )        // Add only miss
2915        {
2916            *data << uint64(ihit->targetGUID);
2917            *data << uint8(ihit->missCondition);
2918            if( ihit->missCondition == SPELL_MISS_REFLECT )
2919                *data << uint8(ihit->reflectResult);
2920        }
2921    }
2922}
2923
2924void Spell::SendLogExecute()
2925{
2926    Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2927
2928    WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
2929
2930    if(m_caster->GetTypeId() == TYPEID_PLAYER)
2931        data.append(m_caster->GetPackGUID());
2932    else
2933        data.append(target->GetPackGUID());
2934
2935    data << uint32(m_spellInfo->Id);
2936    uint32 count1 = 1;
2937    data << uint32(count1);                                 // count1 (effect count?)
2938    for(uint32 i = 0; i < count1; ++i)
2939    {
2940        data << uint32(m_spellInfo->Effect[0]);             // spell effect?
2941        uint32 count2 = 1;
2942        data << uint32(count2);                             // count2 (target count?)
2943        for(uint32 j = 0; j < count2; ++j)
2944        {
2945            switch(m_spellInfo->Effect[0])
2946            {
2947                case SPELL_EFFECT_POWER_DRAIN:
2948                    if(Unit *unit = m_targets.getUnitTarget())
2949                        data.append(unit->GetPackGUID());
2950                    else
2951                        data << uint8(0);
2952                    data << uint32(0);
2953                    data << uint32(0);
2954                    data << float(0);
2955                    break;
2956                case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
2957                    if(Unit *unit = m_targets.getUnitTarget())
2958                        data.append(unit->GetPackGUID());
2959                    else
2960                        data << uint8(0);
2961                    data << uint32(0);                      // count?
2962                    break;
2963                case SPELL_EFFECT_INTERRUPT_CAST:
2964                    if(Unit *unit = m_targets.getUnitTarget())
2965                        data.append(unit->GetPackGUID());
2966                    else
2967                        data << uint8(0);
2968                    data << uint32(0);                      // spellid
2969                    break;
2970                case SPELL_EFFECT_DURABILITY_DAMAGE:
2971                    if(Unit *unit = m_targets.getUnitTarget())
2972                        data.append(unit->GetPackGUID());
2973                    else
2974                        data << uint8(0);
2975                    data << uint32(0);
2976                    data << uint32(0);
2977                    break;
2978                case SPELL_EFFECT_OPEN_LOCK:
2979                case SPELL_EFFECT_OPEN_LOCK_ITEM:
2980                    if(Item *item = m_targets.getItemTarget())
2981                        data.append(item->GetPackGUID());
2982                    else
2983                        data << uint8(0);
2984                    break;
2985                case SPELL_EFFECT_CREATE_ITEM:
2986                    data << uint32(m_spellInfo->EffectItemType[0]);
2987                    break;
2988                case SPELL_EFFECT_SUMMON:
2989                case SPELL_EFFECT_SUMMON_WILD:
2990                case SPELL_EFFECT_SUMMON_GUARDIAN:
2991                case SPELL_EFFECT_TRANS_DOOR:
2992                case SPELL_EFFECT_SUMMON_PET:
2993                case SPELL_EFFECT_SUMMON_POSSESSED:
2994                case SPELL_EFFECT_SUMMON_TOTEM:
2995                case SPELL_EFFECT_SUMMON_OBJECT_WILD:
2996                case SPELL_EFFECT_CREATE_HOUSE:
2997                case SPELL_EFFECT_DUEL:
2998                case SPELL_EFFECT_SUMMON_TOTEM_SLOT1:
2999                case SPELL_EFFECT_SUMMON_TOTEM_SLOT2:
3000                case SPELL_EFFECT_SUMMON_TOTEM_SLOT3:
3001                case SPELL_EFFECT_SUMMON_TOTEM_SLOT4:
3002                case SPELL_EFFECT_SUMMON_PHANTASM:
3003                case SPELL_EFFECT_SUMMON_CRITTER:
3004                case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3005                case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3006                case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3007                case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3008                case SPELL_EFFECT_SUMMON_DEMON:
3009                case SPELL_EFFECT_150:
3010                    if(Unit *unit = m_targets.getUnitTarget())
3011                        data.append(unit->GetPackGUID());
3012                    else if(m_targets.getItemTargetGUID())
3013                        data.appendPackGUID(m_targets.getItemTargetGUID());
3014                    else if(GameObject *go = m_targets.getGOTarget())
3015                        data.append(go->GetPackGUID());
3016                    else
3017                        data << uint8(0);                   // guid
3018                    break;
3019                case SPELL_EFFECT_FEED_PET:
3020                    data << uint32(m_targets.getItemTargetEntry());
3021                    break;
3022                case SPELL_EFFECT_DISMISS_PET:
3023                    if(Unit *unit = m_targets.getUnitTarget())
3024                        data.append(unit->GetPackGUID());
3025                    else
3026                        data << uint8(0);
3027                    break;
3028                default:
3029                    return;
3030            }
3031        }
3032    }
3033
3034    m_caster->SendMessageToSet(&data, true);
3035}
3036
3037void Spell::SendInterrupted(uint8 result)
3038{
3039    WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3040    data.append(m_caster->GetPackGUID());
3041    data << m_spellInfo->Id;
3042    data << result;
3043    m_caster->SendMessageToSet(&data, true);
3044
3045    data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3046    data.append(m_caster->GetPackGUID());
3047    data << m_spellInfo->Id;
3048    m_caster->SendMessageToSet(&data, true);
3049}
3050
3051void Spell::SendChannelUpdate(uint32 time)
3052{
3053    if(time == 0)
3054    {
3055        m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3056        m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3057    }
3058
3059    if (m_caster->GetTypeId() != TYPEID_PLAYER)
3060        return;
3061
3062    WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3063    data.append(m_caster->GetPackGUID());
3064    data << time;
3065
3066    ((Player*)m_caster)->GetSession()->SendPacket( &data );
3067}
3068
3069void Spell::SendChannelStart(uint32 duration)
3070{
3071    WorldObject* target = NULL;
3072
3073    // select first not rsusted target from target list for _0_ effect
3074    if(!m_UniqueTargetInfo.empty())
3075    {
3076        for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3077        {
3078            if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3079            {
3080                target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3081                break;
3082            }
3083        }
3084    }
3085    else if(!m_UniqueGOTargetInfo.empty())
3086    {
3087        for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3088        {
3089            if(itr->effectMask & (1<<0) )
3090            {
3091                target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3092                break;
3093            }
3094        }
3095    }
3096
3097    if (m_caster->GetTypeId() == TYPEID_PLAYER)
3098    {
3099        WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3100        data.append(m_caster->GetPackGUID());
3101        data << m_spellInfo->Id;
3102        data << duration;
3103
3104        ((Player*)m_caster)->GetSession()->SendPacket( &data );
3105    }
3106
3107    m_timer = duration;
3108    if(target)
3109        m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3110    m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3111}
3112
3113void Spell::SendResurrectRequest(Player* target)
3114{
3115    WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+2+4));
3116    data << m_caster->GetGUID();
3117    data << uint32(1) << uint16(0) << uint32(1);
3118
3119    target->GetSession()->SendPacket(&data);
3120}
3121
3122void Spell::SendPlaySpellVisual(uint32 SpellID)
3123{
3124    if (m_caster->GetTypeId() != TYPEID_PLAYER)
3125        return;
3126
3127    WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3128    data << m_caster->GetGUID();
3129    data << SpellID;
3130    ((Player*)m_caster)->GetSession()->SendPacket(&data);
3131}
3132
3133void Spell::TakeCastItem()
3134{
3135    if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3136        return;
3137
3138    // not remove cast item at triggered spell (equipping, weapon damage, etc)
3139    if(m_IsTriggeredSpell)
3140        return;
3141
3142    ItemPrototype const *proto = m_CastItem->GetProto();
3143
3144    if(!proto)
3145    {
3146        // This code is to avoid a crash
3147        // I'm not sure, if this is really an error, but I guess every item needs a prototype
3148        sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3149        return;
3150    }
3151
3152    bool expendable = false;
3153    bool withoutCharges = false;
3154
3155    for (int i = 0; i<5; i++)
3156    {
3157        if (proto->Spells[i].SpellId)
3158        {
3159            // item has limited charges
3160            if (proto->Spells[i].SpellCharges)
3161            {
3162                if (proto->Spells[i].SpellCharges < 0)
3163                    expendable = true;
3164
3165                int32 charges = m_CastItem->GetSpellCharges(i);
3166
3167                // item has charges left
3168                if (charges)
3169                {
3170                    (charges > 0) ? --charges : ++charges;  // abs(charges) less at 1 after use
3171                    if (proto->Stackable < 2)
3172                        m_CastItem->SetSpellCharges(i, charges);
3173                    m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3174                }
3175
3176                // all charges used
3177                withoutCharges = (charges == 0);
3178            }
3179        }
3180    }
3181
3182    if (expendable && withoutCharges)
3183    {
3184        uint32 count = 1;
3185        ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3186
3187        // prevent crash at access to deleted m_targets.getItemTarget
3188        if(m_CastItem==m_targets.getItemTarget())
3189            m_targets.setItemTarget(NULL);
3190
3191        m_CastItem = NULL;
3192    }
3193}
3194
3195void Spell::TakePower()
3196{
3197    if(m_CastItem || m_triggeredByAuraSpell)
3198        return;
3199
3200    // health as power used
3201    if(m_spellInfo->powerType == POWER_HEALTH)
3202    {
3203        m_caster->ModifyHealth( -(int32)m_powerCost );
3204        return;
3205    }
3206
3207    if(m_spellInfo->powerType >= MAX_POWERS)
3208    {
3209        sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3210        return;
3211    }
3212
3213    Powers powerType = Powers(m_spellInfo->powerType);
3214
3215    m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3216
3217    // Set the five second timer
3218    if (powerType == POWER_MANA && m_powerCost > 0)
3219        m_caster->SetLastManaUse(getMSTime());
3220}
3221
3222void Spell::TakeReagents()
3223{
3224    if(m_IsTriggeredSpell)                                  // reagents used in triggered spell removed by original spell or don't must be removed.
3225        return;
3226
3227    if (m_caster->GetTypeId() != TYPEID_PLAYER)
3228        return;
3229
3230    if (m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
3231        m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
3232        return;
3233
3234    Player* p_caster = (Player*)m_caster;
3235
3236    for(uint32 x=0;x<8;x++)
3237    {
3238        if(m_spellInfo->Reagent[x] <= 0)
3239            continue;
3240
3241        uint32 itemid = m_spellInfo->Reagent[x];
3242        uint32 itemcount = m_spellInfo->ReagentCount[x];
3243
3244        // if CastItem is also spell reagent
3245        if (m_CastItem)
3246        {
3247            ItemPrototype const *proto = m_CastItem->GetProto();
3248            if( proto && proto->ItemId == itemid )
3249            {
3250                for(int s=0;s<5;s++)
3251                {
3252                    // CastItem will be used up and does not count as reagent
3253                    int32 charges = m_CastItem->GetSpellCharges(s);
3254                    if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3255                    {
3256                        ++itemcount;
3257                        break;
3258                    }
3259                }
3260
3261                m_CastItem = NULL;
3262            }
3263        }
3264
3265        // if getItemTarget is also spell reagent
3266        if (m_targets.getItemTargetEntry()==itemid)
3267            m_targets.setItemTarget(NULL);
3268
3269        p_caster->DestroyItemCount(itemid, itemcount, true);
3270    }
3271}
3272
3273void Spell::HandleThreatSpells(uint32 spellId)
3274{
3275    if(!m_targets.getUnitTarget() || !spellId)
3276        return;
3277
3278    if(!m_targets.getUnitTarget()->CanHaveThreatList())
3279        return;
3280
3281    SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3282    if(!threatSpell)
3283        return;
3284
3285    m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3286
3287    DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3288}
3289
3290void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3291{
3292    unitTarget = pUnitTarget;
3293    itemTarget = pItemTarget;
3294    gameObjTarget = pGOTarget;
3295
3296    uint8 eff = m_spellInfo->Effect[i];
3297    uint32 mechanic = m_spellInfo->EffectMechanic[i];
3298
3299    damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3300
3301    sLog.outDebug( "Spell: Effect : %u", eff);
3302
3303    //Simply return. Do not display "immune" in red text on client
3304    if(unitTarget && unitTarget->IsImmunedToSpellEffect(eff, mechanic))
3305        return;
3306
3307    if(eff<TOTAL_SPELL_EFFECTS)
3308    {
3309        //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3310        (*this.*SpellEffects[eff])(i);
3311    }
3312    /*
3313    else
3314    {
3315        sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3316        if (m_CastItem)
3317            EffectEnchantItemTmp(i);
3318        else
3319        {
3320            sLog.outError("SPELL: unknown effect %u spell id %u\n",
3321                eff, m_spellInfo->Id);
3322        }
3323    }
3324    */
3325}
3326
3327void Spell::TriggerSpell()
3328{
3329    for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3330    {
3331        Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, this->m_selfContainer);
3332        spell->prepare(&m_targets);                         // use original spell original targets
3333    }
3334}
3335
3336uint8 Spell::CanCast(bool strict)
3337{
3338    // check cooldowns to prevent cheating
3339    if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3340    {
3341        if(m_triggeredByAuraSpell)
3342            return SPELL_FAILED_DONT_REPORT;
3343        else
3344            return SPELL_FAILED_NOT_READY;
3345    }
3346
3347    // only allow triggered spells if at an ended battleground
3348    if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3349        if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3350            if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3351                return SPELL_FAILED_DONT_REPORT;
3352
3353    // only check at first call, Stealth auras are already removed at second call
3354    // for now, ignore triggered spells
3355    if( strict && !m_IsTriggeredSpell)
3356    {
3357        // Cannot be used in this stance/form
3358        if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3359            return shapeError;
3360
3361        if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3362            return SPELL_FAILED_ONLY_STEALTHED;
3363    }
3364
3365    // caster state requirements
3366    if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3367        return SPELL_FAILED_CASTER_AURASTATE;
3368    if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3369        return SPELL_FAILED_CASTER_AURASTATE;
3370
3371    // cancel autorepeat spells if cast start when moving
3372    // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3373    if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3374    {
3375        // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3376        if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3377            (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3378            return SPELL_FAILED_MOVING;
3379    }
3380
3381    Unit *target = m_targets.getUnitTarget();
3382
3383    if(target)
3384    {
3385        // target state requirements (not allowed state), apply to self also
3386        if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3387            return SPELL_FAILED_TARGET_AURASTATE;
3388
3389
3390        if(target != m_caster)
3391        {
3392            // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3393            if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3394                return SPELL_FAILED_TARGET_AURASTATE;
3395
3396            // Not allow casting on flying player
3397            if (target->isInFlight())
3398                return SPELL_FAILED_BAD_TARGETS;
3399
3400            if(VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3401                return SPELL_FAILED_LINE_OF_SIGHT;
3402
3403            // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3404            // this case can be triggered if rank not found (too low-level target for first rank)
3405            if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3406            {
3407                for(int i=0;i<3;i++)
3408                {
3409                    if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3410                        if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3411                            return SPELL_FAILED_LOWLEVEL;
3412                }
3413            }
3414        }
3415
3416        // check pet presents
3417        for(int j=0;j<3;j++)
3418        {
3419            if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3420            {
3421                target = m_caster->GetPet();
3422                if(!target)
3423                {
3424                    if(m_triggeredByAuraSpell)              // not report pet not existence for triggered spells
3425                        return SPELL_FAILED_DONT_REPORT;
3426                    else
3427                        return SPELL_FAILED_NO_PET;
3428                }
3429                break;
3430            }
3431        }
3432
3433        //check creature type
3434        //ignore self casts (including area casts when caster selected as target)
3435        if(target != m_caster)
3436        {
3437            if(!CheckTargetCreatureType(target))
3438            {
3439                if(target->GetTypeId()==TYPEID_PLAYER)
3440                    return SPELL_FAILED_TARGET_IS_PLAYER;
3441                else
3442                    return SPELL_FAILED_BAD_TARGETS;
3443            }
3444        }
3445
3446        // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3447        // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3448        if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3449        {
3450            // check correctness positive/negative cast target (pet cast real check and cheating check)
3451            if(IsPositiveSpell(m_spellInfo->Id))
3452            {
3453                if(m_caster->IsHostileTo(target))
3454                    return SPELL_FAILED_BAD_TARGETS;
3455            }
3456            else
3457            {
3458                if(m_caster->IsFriendlyTo(target))
3459                    return SPELL_FAILED_BAD_TARGETS;
3460            }
3461        }
3462
3463        if(IsPositiveSpell(m_spellInfo->Id))
3464        {
3465            if(target->IsImmunedToSpell(m_spellInfo,false))
3466                return SPELL_FAILED_TARGET_AURASTATE;
3467        }
3468
3469        //Must be behind the target.
3470        if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3471        {
3472            SendInterrupted(2);
3473            return SPELL_FAILED_NOT_BEHIND;
3474        }
3475
3476        //Target must be facing you.
3477        if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3478        {
3479            SendInterrupted(2);
3480            return SPELL_FAILED_NOT_INFRONT;
3481        }
3482
3483        // check if target is in combat
3484        if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3485        {
3486            return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3487        }
3488    }
3489    // Spell casted only on battleground
3490    if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) &&  m_caster->GetTypeId()==TYPEID_PLAYER)
3491        if(!((Player*)m_caster)->InBattleGround())
3492            return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3493
3494    // do not allow spells to be cast in arenas
3495    // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3496    // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3497    if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3498        GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3499        if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3500            if(mapEntry->IsBattleArena())
3501                return SPELL_FAILED_NOT_IN_ARENA;
3502
3503    // zone check
3504    if(!IsSpellAllowedInLocation(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3505        return SPELL_FAILED_REQUIRES_AREA;
3506
3507    // not let players cast spells at mount (and let do it to creatures)
3508    if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3509        !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3510    {
3511        if(m_caster->isInFlight())
3512            return SPELL_FAILED_NOT_FLYING;
3513        else
3514            return SPELL_FAILED_NOT_MOUNTED;
3515    }
3516
3517    // always (except passive spells) check items (focus object can be required for any type casts)
3518    if(!IsPassiveSpell(m_spellInfo->Id))
3519        if(uint8 castResult = CheckItems())
3520            return castResult;
3521
3522    if(uint8 castResult = CheckRange(strict))
3523        return castResult;
3524
3525    {
3526        if(uint8 castResult = CheckPower())
3527            return castResult;
3528    }
3529
3530    if(!m_triggeredByAuraSpell)                             // triggered spell not affected by stun/etc
3531        if(uint8 castResult = CheckCasterAuras())
3532            return castResult;
3533
3534    for (int i = 0; i < 3; i++)
3535    {
3536        // for effects of spells that have only one target
3537        switch(m_spellInfo->Effect[i])
3538        {
3539            case SPELL_EFFECT_DUMMY:
3540            {
3541                if(m_spellInfo->SpellIconID == 1648)        // Execute
3542                {
3543                    if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3544                        return SPELL_FAILED_BAD_TARGETS;
3545                }
3546                else if (m_spellInfo->Id == 51582)          // Rocket Boots Engaged
3547                {
3548                    if(m_caster->IsInWater())
3549                        return SPELL_FAILED_ONLY_ABOVEWATER;
3550                }
3551                else if(m_spellInfo->SpellIconID==156)      // Holy Shock
3552                {
3553                    // spell different for friends and enemies
3554                    // hart version required facing
3555                    if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3556                        return SPELL_FAILED_UNIT_NOT_INFRONT;
3557                }
3558                break;
3559            }
3560            case SPELL_EFFECT_SCHOOL_DAMAGE:
3561            {
3562                // Hammer of Wrath
3563                if(m_spellInfo->SpellVisual == 7250)
3564                {
3565                    if (!m_targets.getUnitTarget())
3566                        return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3567
3568                    if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3569                        return SPELL_FAILED_BAD_TARGETS;
3570                }
3571                break;
3572            }
3573            case SPELL_EFFECT_TAMECREATURE:
3574            {
3575                if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3576                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3577
3578                if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3579                    return SPELL_FAILED_HIGHLEVEL;
3580
3581                CreatureInfo const *cinfo = ((Creature*)m_targets.getUnitTarget())->GetCreatureInfo();
3582                if( cinfo->type != CREATURE_TYPE_BEAST )
3583                    return SPELL_FAILED_BAD_TARGETS;
3584
3585                // use SMSG_PET_TAME_FAILURE?
3586                if( !(cinfo->flag1 & 1) || !(cinfo->family) )
3587                    return SPELL_FAILED_BAD_TARGETS;
3588
3589                if(m_caster->GetPetGUID())
3590                    return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3591
3592                if(m_caster->GetCharmGUID())
3593                    return SPELL_FAILED_ALREADY_HAVE_CHARM;
3594
3595                break;
3596            }
3597            case SPELL_EFFECT_LEARN_SPELL:
3598            {
3599                if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
3600                    break;
3601
3602                Pet* pet = m_caster->GetPet();
3603
3604                if(!pet)
3605                    return SPELL_FAILED_NO_PET;
3606
3607                SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3608
3609                if(!learn_spellproto)
3610                    return SPELL_FAILED_NOT_KNOWN;
3611
3612                if(!pet->CanTakeMoreActiveSpells(learn_spellproto->Id))
3613                    return SPELL_FAILED_TOO_MANY_SKILLS;
3614
3615                if(m_spellInfo->spellLevel > pet->getLevel())
3616                    return SPELL_FAILED_LOWLEVEL;
3617
3618                if(!pet->HasTPForSpell(learn_spellproto->Id))
3619                    return SPELL_FAILED_TRAINING_POINTS;
3620
3621                break;
3622            }
3623            case SPELL_EFFECT_LEARN_PET_SPELL:
3624            {
3625                Pet* pet = m_caster->GetPet();
3626
3627                if(!pet)
3628                    return SPELL_FAILED_NO_PET;
3629
3630                SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3631
3632                if(!learn_spellproto)
3633                    return SPELL_FAILED_NOT_KNOWN;
3634
3635                if(!pet->CanTakeMoreActiveSpells(learn_spellproto->Id))
3636                    return SPELL_FAILED_TOO_MANY_SKILLS;
3637
3638                if(m_spellInfo->spellLevel > pet->getLevel())
3639                    return SPELL_FAILED_LOWLEVEL;
3640
3641                if(!pet->HasTPForSpell(learn_spellproto->Id))
3642                    return SPELL_FAILED_TRAINING_POINTS;
3643
3644                break;
3645            }
3646            case SPELL_EFFECT_FEED_PET:
3647            {
3648                if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getItemTarget() )
3649                    return SPELL_FAILED_BAD_TARGETS;
3650
3651                Pet* pet = m_caster->GetPet();
3652
3653                if(!pet)
3654                    return SPELL_FAILED_NO_PET;
3655
3656                if(!pet->HaveInDiet(m_targets.getItemTarget()->GetProto()))
3657                    return SPELL_FAILED_WRONG_PET_FOOD;
3658
3659                if(!pet->GetCurrentFoodBenefitLevel(m_targets.getItemTarget()->GetProto()->ItemLevel))
3660                    return SPELL_FAILED_FOOD_LOWLEVEL;
3661
3662                if(m_caster->isInCombat() || pet->isInCombat())
3663                    return SPELL_FAILED_AFFECTING_COMBAT;
3664
3665                break;
3666            }
3667            case SPELL_EFFECT_POWER_BURN:
3668            case SPELL_EFFECT_POWER_DRAIN:
3669            {
3670                // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
3671                if(m_caster->GetTypeId() == TYPEID_PLAYER)
3672                    if(Unit* target = m_targets.getUnitTarget())
3673                        if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
3674                            return SPELL_FAILED_BAD_TARGETS;
3675                break;
3676            }
3677            case SPELL_EFFECT_CHARGE:
3678            {
3679                if (m_caster->hasUnitState(UNIT_STAT_ROOT))
3680                    return SPELL_FAILED_ROOTED;
3681
3682                break;
3683            }
3684            case SPELL_EFFECT_SKINNING:
3685            {
3686                if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
3687                    return SPELL_FAILED_BAD_TARGETS;
3688
3689                if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
3690                    return SPELL_FAILED_TARGET_UNSKINNABLE;
3691
3692                Creature* creature = (Creature*)m_targets.getUnitTarget();
3693                if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
3694                {
3695                    return SPELL_FAILED_TARGET_NOT_LOOTED;
3696                }
3697
3698                uint32 skill;
3699                if(creature->GetCreatureInfo()->flag1 & 256)
3700                    skill = SKILL_HERBALISM;                // special case
3701                else if(creature->GetCreatureInfo()->flag1 & 512)
3702                    skill = SKILL_MINING;                   // special case
3703                else
3704                    skill = SKILL_SKINNING;                 // normal case
3705
3706                int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
3707                int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
3708                int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
3709                if (ReqValue > skillValue)
3710                    return SPELL_FAILED_LOW_CASTLEVEL;
3711
3712                // chance for fail at orange skinning attempt
3713                if( (m_selfContainer && (*m_selfContainer) == this) &&
3714                    skillValue < sWorld.GetConfigMaxSkillValue() &&
3715                    (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
3716                    return SPELL_FAILED_TRY_AGAIN;
3717
3718                break;
3719            }
3720            case SPELL_EFFECT_OPEN_LOCK_ITEM:
3721            case SPELL_EFFECT_OPEN_LOCK:
3722            {
3723                if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
3724                    m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
3725                    break;
3726
3727                if( m_caster->GetTypeId() != TYPEID_PLAYER  // only players can open locks, gather etc.
3728                    // we need a go target in case of TARGET_GAMEOBJECT
3729                    || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
3730                    // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
3731                    || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
3732                    (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
3733                    return SPELL_FAILED_BAD_TARGETS;
3734
3735                // In BattleGround players can use only flags and banners
3736                if( ((Player*)m_caster)->InBattleGround() &&
3737                    !((Player*)m_caster)->isAllowUseBattleGroundObject() )
3738                    return SPELL_FAILED_TRY_AGAIN;
3739
3740                // get the lock entry
3741                LockEntry const *lockInfo = NULL;
3742                if (GameObject* go=m_targets.getGOTarget())
3743                    lockInfo = sLockStore.LookupEntry(go->GetLockId());
3744                else if(Item* itm=m_targets.getItemTarget())
3745                    lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
3746
3747                // check lock compatibility
3748                if (lockInfo)
3749                {
3750                    // check for lock - key pair (checked by client also, just prevent cheating
3751                    bool ok_key = false;
3752                    for(int it = 0; it < 5; ++it)
3753                    {
3754                        switch(lockInfo->keytype[it])
3755                        {
3756                            case LOCK_KEY_NONE:
3757                                break;
3758                            case LOCK_KEY_ITEM:
3759                            {
3760                                if(lockInfo->key[it])
3761                                {
3762                                    if(m_CastItem && m_CastItem->GetEntry()==lockInfo->key[it])
3763                                        ok_key =true;
3764                                    break;
3765                                }
3766                            }
3767                            case LOCK_KEY_SKILL:
3768                            {
3769                                if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->key[it])
3770                                    break;
3771
3772                                switch(lockInfo->key[it])
3773                                {
3774                                    case LOCKTYPE_HERBALISM:
3775                                        if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
3776                                            ok_key =true;
3777                                        break;
3778                                    case LOCKTYPE_MINING:
3779                                        if(((Player*)m_caster)->HasSkill(SKILL_MINING))
3780                                            ok_key =true;
3781                                        break;
3782                                    default:
3783                                        ok_key =true;
3784                                        break;
3785                                }
3786                            }
3787                        }
3788                        if(ok_key)
3789                            break;
3790                    }
3791
3792                    if(!ok_key)
3793                        return SPELL_FAILED_BAD_TARGETS;
3794                }
3795
3796                // chance for fail at orange mining/herb/LockPicking gathering attempt
3797                if (!m_selfContainer || ((*m_selfContainer) != this))
3798                    break;
3799
3800                // get the skill value of the player
3801                int32 SkillValue = 0;
3802                bool canFailAtMax = true;
3803                if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
3804                {
3805                    SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
3806                    canFailAtMax = false;
3807                }
3808                else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
3809                {
3810                    SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
3811                    canFailAtMax = false;
3812                }
3813                else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3814                    SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
3815
3816                // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
3817                if(m_CastItem)
3818                    SkillValue = 0;
3819
3820                // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
3821                SkillValue += m_currentBasePoints[i]+1;
3822
3823                // get the required lock value
3824                int32 ReqValue=0;
3825                if (lockInfo)
3826                {
3827                    // check for lock - key pair
3828                    bool ok = false;
3829                    for(int it = 0; it < 5; ++it)
3830                    {
3831                        if(lockInfo->keytype[it]==LOCK_KEY_ITEM && lockInfo->key[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->key[it])
3832                        {
3833                            // if so, we're good to go
3834                            ok = true;
3835                            break;
3836                        }
3837                    }
3838                    if(ok)
3839                        break;
3840
3841                    if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3842                        ReqValue = lockInfo->requiredlockskill;
3843                    else
3844                        ReqValue = lockInfo->requiredminingskill;
3845                }
3846
3847                // skill doesn't meet the required value
3848                if (ReqValue > SkillValue)
3849                    return SPELL_FAILED_LOW_CASTLEVEL;
3850
3851                // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
3852                if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
3853                    return SPELL_FAILED_TRY_AGAIN;
3854
3855                break;
3856            }
3857            case SPELL_EFFECT_SUMMON_DEAD_PET:
3858            {
3859                Creature *pet = m_caster->GetPet();
3860                if(!pet)
3861                    return SPELL_FAILED_NO_PET;
3862
3863                if(pet->isAlive())
3864                    return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3865
3866                break;
3867            }
3868            // This is generic summon effect now and don't make this check for summon types similar
3869            // SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3870            // These won't show up in m_caster->GetPetGUID()
3871            case SPELL_EFFECT_SUMMON:
3872            {
3873                switch(m_spellInfo->EffectMiscValueB[i])
3874                {
3875                    case SUMMON_TYPE_POSESSED:
3876                    case SUMMON_TYPE_POSESSED2:
3877                    case SUMMON_TYPE_DEMON:
3878                    case SUMMON_TYPE_SUMMON:
3879                    {
3880                        if(m_caster->GetPetGUID())
3881                            return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3882
3883                        if(m_caster->GetCharmGUID())
3884                            return SPELL_FAILED_ALREADY_HAVE_CHARM;
3885                        break;
3886                    }
3887                }
3888                break;
3889            }
3890            // Don't make this check for SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3891            // These won't show up in m_caster->GetPetGUID()
3892            case SPELL_EFFECT_SUMMON_POSSESSED:
3893            case SPELL_EFFECT_SUMMON_PHANTASM:
3894            case SPELL_EFFECT_SUMMON_DEMON:
3895            {
3896                if(m_caster->GetPetGUID())
3897                    return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3898
3899                if(m_caster->GetCharmGUID())
3900                    return SPELL_FAILED_ALREADY_HAVE_CHARM;
3901
3902                break;
3903            }
3904            case SPELL_EFFECT_SUMMON_PET:
3905            {
3906                if(m_caster->GetPetGUID())                  //let warlock do a replacement summon
3907                {
3908
3909                    Pet* pet = ((Player*)m_caster)->GetPet();
3910
3911                    if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
3912                    {
3913                        if (strict)                         //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
3914                            pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
3915                    }
3916                    else
3917                        return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3918                }
3919
3920                if(m_caster->GetCharmGUID())
3921                    return SPELL_FAILED_ALREADY_HAVE_CHARM;
3922
3923                break;
3924            }
3925            case SPELL_EFFECT_SUMMON_PLAYER:
3926            {
3927                if(m_caster->GetTypeId()!=TYPEID_PLAYER)
3928                    return SPELL_FAILED_BAD_TARGETS;
3929                if(!((Player*)m_caster)->GetSelection())
3930                    return SPELL_FAILED_BAD_TARGETS;
3931
3932                Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
3933                if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
3934                    return SPELL_FAILED_BAD_TARGETS;
3935
3936                // check if our map is dungeon
3937                if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
3938                {
3939                    InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
3940                    if(!instance)
3941                        return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
3942                    if ( instance->levelMin > target->getLevel() )
3943                        return SPELL_FAILED_LOWLEVEL;
3944                    if ( instance->levelMax && instance->levelMax < target->getLevel() )
3945                        return SPELL_FAILED_HIGHLEVEL;
3946                }
3947                break;
3948            }
3949            case SPELL_EFFECT_LEAP:
3950            case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
3951            {
3952                float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
3953                float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
3954                float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
3955                // teleport a bit above terrain level to avoid falling below it
3956                float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
3957                if(fz <= INVALID_HEIGHT)                    // note: this also will prevent use effect in instances without vmaps height enabled
3958                    return SPELL_FAILED_TRY_AGAIN;
3959
3960                float caster_pos_z = m_caster->GetPositionZ();
3961                // Control the caster to not climb or drop when +-fz > 8
3962                if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
3963                    return SPELL_FAILED_TRY_AGAIN;
3964
3965                // not allow use this effect at battleground until battleground start
3966                if(m_caster->GetTypeId()==TYPEID_PLAYER)
3967                    if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
3968                        if(bg->GetStatus() != STATUS_IN_PROGRESS)
3969                            return SPELL_FAILED_TRY_AGAIN;
3970                break;
3971            }
3972            case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
3973            {
3974                if (m_targets.getUnitTarget()==m_caster)
3975                    return SPELL_FAILED_BAD_TARGETS;
3976                break;
3977            }
3978            default:break;
3979        }
3980    }
3981
3982    for (int i = 0; i < 3; i++)
3983    {
3984        switch(m_spellInfo->EffectApplyAuraName[i])
3985        {
3986            case SPELL_AURA_MOD_POSSESS:
3987            case SPELL_AURA_MOD_CHARM:
3988            {
3989                if(m_caster->GetPetGUID())
3990                    return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3991
3992                if(m_caster->GetCharmGUID())
3993                    return SPELL_FAILED_ALREADY_HAVE_CHARM;
3994
3995                if(m_caster->GetCharmerGUID())
3996                    return SPELL_FAILED_CHARMED;
3997
3998                if(!m_targets.getUnitTarget())
3999                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4000
4001                if(m_targets.getUnitTarget()->GetCharmerGUID())
4002                    return SPELL_FAILED_CHARMED;
4003
4004                if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4005                    return SPELL_FAILED_HIGHLEVEL;
4006            };break;
4007            case SPELL_AURA_MOUNTED:
4008            {
4009                if (m_caster->IsInWater())
4010                    return SPELL_FAILED_ONLY_ABOVEWATER;
4011
4012                if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4013                    return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4014
4015                // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4016                if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaId)
4017                    return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4018
4019                if (m_caster->GetAreaId()==35)
4020                    return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4021
4022                ShapeshiftForm form = m_caster->m_form;
4023                if( form == FORM_CAT          || form == FORM_TREE      || form == FORM_TRAVEL   ||
4024                    form == FORM_AQUA         || form == FORM_BEAR      || form == FORM_DIREBEAR ||
4025                    form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT   ||
4026                    form == FORM_FLIGHT_EPIC  || form == FORM_MOONKIN )
4027                    return SPELL_FAILED_NOT_SHAPESHIFT;
4028
4029                break;
4030            }
4031            case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4032            {
4033                if(!m_targets.getUnitTarget())
4034                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4035
4036                // can be casted at non-friendly unit or own pet/charm
4037                if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4038                    return SPELL_FAILED_TARGET_FRIENDLY;
4039            };break;
4040            case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4041            case SPELL_AURA_FLY:
4042            {
4043                // not allow cast fly spells at old maps by players (all spells is self target)
4044                if(m_caster->GetTypeId()==TYPEID_PLAYER)
4045                {
4046                    if( !((Player*)m_caster)->isGameMaster() &&
4047                        GetVirtualMapForMapAndZone(m_caster->GetMapId(),m_caster->GetZoneId()) != 530)
4048                        return SPELL_FAILED_NOT_HERE;
4049                }
4050            };break;
4051            case SPELL_AURA_PERIODIC_MANA_LEECH:
4052            {
4053                if (!m_targets.getUnitTarget())
4054                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4055
4056                if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4057                    break;
4058
4059                if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4060                    return SPELL_FAILED_BAD_TARGETS;
4061                break;
4062            }
4063            default:break;
4064        }
4065    }
4066
4067    // all ok
4068    return 0;
4069}
4070
4071int16 Spell::PetCanCast(Unit* target)
4072{
4073    if(!m_caster->isAlive())
4074        return SPELL_FAILED_CASTER_DEAD;
4075
4076    if(m_caster->IsNonMeleeSpellCasted(false))              //prevent spellcast interuption by another spellcast
4077        return SPELL_FAILED_SPELL_IN_PROGRESS;
4078    if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4079        return SPELL_FAILED_AFFECTING_COMBAT;
4080
4081    if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4082    {
4083                                                            //dead owner (pets still alive when owners ressed?)
4084        if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4085            return SPELL_FAILED_CASTER_DEAD;
4086
4087        if(!target && m_targets.getUnitTarget())
4088            target = m_targets.getUnitTarget();
4089
4090        bool need = false;
4091        for(uint32 i = 0;i<3;i++)
4092        {
4093            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)
4094            {
4095                need = true;
4096                if(!target)
4097                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4098                break;
4099            }
4100        }
4101        if(need)
4102            m_targets.setUnitTarget(target);
4103
4104        Unit* _target = m_targets.getUnitTarget();
4105
4106        if(_target)                                         //for target dead/target not valid
4107        {
4108            if(!_target->isAlive())
4109                return SPELL_FAILED_BAD_TARGETS;
4110
4111            if(IsPositiveSpell(m_spellInfo->Id))
4112            {
4113                if(m_caster->IsHostileTo(_target))
4114                    return SPELL_FAILED_BAD_TARGETS;
4115            }
4116            else
4117            {
4118                bool duelvsplayertar = false;
4119                for(int j=0;j<3;j++)
4120                {
4121                                                            //TARGET_DUELVSPLAYER is positive AND negative
4122                    duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4123                }
4124                if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4125                {
4126                    return SPELL_FAILED_BAD_TARGETS;
4127                }
4128            }
4129        }
4130                                                            //cooldown
4131        if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4132            return SPELL_FAILED_NOT_READY;
4133    }
4134
4135    uint16 result = CanCast(true);
4136    if(result != 0)
4137        return result;
4138    else
4139        return -1;                                          //this allows to check spell fail 0, in combat
4140}
4141
4142uint8 Spell::CheckCasterAuras() const
4143{
4144    // Flag drop spells totally immuned to caster auras
4145    // FIXME: find more nice check for all totally immuned spells
4146    // AttributesEx3 & 0x10000000?
4147    if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4148        return 0;
4149
4150    uint8 school_immune = 0;
4151    uint32 mechanic_immune = 0;
4152    uint32 dispel_immune = 0;
4153
4154    //Check if the spell grants school or mechanic immunity.
4155    //We use bitmasks so the loop is done only once and not on every aura check below.
4156    if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4157    {
4158        for(int i = 0;i < 3; i ++)
4159        {
4160            if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4161                school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4162            else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4163                mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4164            else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4165                dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4166        }
4167        //immune movement impairement and loss of control
4168        if(m_spellInfo->Id==(uint32)42292)
4169            mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4170    }
4171
4172    //Check whether the cast should be prevented by any state you might have.
4173    uint8 prevented_reason = 0;
4174    // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4175    if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4176        prevented_reason = SPELL_FAILED_STUNNED;
4177    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4178        prevented_reason = SPELL_FAILED_CONFUSED;
4179    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4180        prevented_reason = SPELL_FAILED_FLEEING;
4181    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4182        prevented_reason = SPELL_FAILED_SILENCED;
4183    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4184        prevented_reason = SPELL_FAILED_PACIFIED;
4185
4186    // Attr must make flag drop spell totally immuned from all effects
4187    if(prevented_reason)
4188    {
4189        if(school_immune || mechanic_immune || dispel_immune)
4190        {
4191            //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4192            Unit::AuraMap const& auras = m_caster->GetAuras();
4193            for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); itr++)
4194            {
4195                if(itr->second)
4196                {
4197                    if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4198                        continue;
4199                    if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4200                        continue;
4201                    if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4202                        continue;
4203
4204                    //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4205                    //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4206                    switch(itr->second->GetModifier()->m_auraname)
4207                    {
4208                        case SPELL_AURA_MOD_STUN:
4209                            if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4210                                return SPELL_FAILED_STUNNED;
4211                            break;
4212                        case SPELL_AURA_MOD_CONFUSE:
4213                            if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4214                                return SPELL_FAILED_CONFUSED;
4215                            break;
4216                        case SPELL_AURA_MOD_FEAR:
4217                            if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4218                                return SPELL_FAILED_FLEEING;
4219                            break;
4220                        case SPELL_AURA_MOD_SILENCE:
4221                        case SPELL_AURA_MOD_PACIFY:
4222                        case SPELL_AURA_MOD_PACIFY_SILENCE:
4223                            if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4224                                return SPELL_FAILED_PACIFIED;
4225                            else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4226                                return SPELL_FAILED_SILENCED;
4227                            break;
4228                    }
4229                }
4230            }
4231        }
4232        //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4233        else
4234            return prevented_reason;
4235    }
4236    return 0;                                               // all ok
4237}
4238
4239bool Spell::CanAutoCast(Unit* target)
4240{
4241    uint64 targetguid = target->GetGUID();
4242
4243    for(uint32 j = 0;j<3;j++)
4244    {
4245        if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4246        {
4247            if( m_spellInfo->StackAmount <= 1)
4248            {
4249                if( target->HasAura(m_spellInfo->Id, j) )
4250                    return false;
4251            }
4252            else
4253            {
4254                if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4255                    return false;
4256            }
4257        }
4258        else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4259        {
4260                if( target->HasAura(m_spellInfo->Id, j) )
4261                    return false;
4262        }
4263    }
4264
4265    int16 result = PetCanCast(target);
4266
4267    if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4268    {
4269        FillTargetMap();
4270        //check if among target units, our WANTED target is as well (->only self cast spells return false)
4271        for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4272            if( ihit->targetGUID == targetguid )
4273                return true;
4274    }
4275    return false;                                           //target invalid
4276}
4277
4278uint8 Spell::CheckRange(bool strict)
4279{
4280    float range_mod;
4281
4282    // self cast doesn't need range checking -- also for Starshards fix
4283    if (m_spellInfo->rangeIndex == 1) return 0;
4284
4285    if (strict)                                             //add radius of caster
4286        range_mod = 1.25;
4287    else                                                    //add radius of caster and ~5 yds "give"
4288        range_mod = 6.25;
4289
4290    SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4291    float max_range = GetSpellMaxRange(srange) + range_mod;
4292    float min_range = GetSpellMinRange(srange);
4293
4294    if(Player* modOwner = m_caster->GetSpellModOwner())
4295        modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4296
4297    Unit *target = m_targets.getUnitTarget();
4298
4299    if(target && target != m_caster)
4300    {
4301        // distance from target center in checks
4302        if(!m_caster->IsWithinCombatDist(target, max_range))
4303            return SPELL_FAILED_OUT_OF_RANGE;               //0x5A;
4304        if(min_range && m_caster->IsWithinCombatDist(target, min_range)) // skip this check if min_range = 0
4305            return SPELL_FAILED_TOO_CLOSE;
4306        if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4307            (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4308            return SPELL_FAILED_UNIT_NOT_INFRONT;
4309    }
4310
4311    if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4312    {
4313        float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4314        if(dist > max_range)
4315            return SPELL_FAILED_OUT_OF_RANGE;
4316        if(dist < min_range)
4317            return SPELL_FAILED_TOO_CLOSE;
4318    }
4319
4320    return 0;                                               // ok
4321}
4322
4323int32 Spell::CalculatePowerCost()
4324{
4325    // item cast not used power
4326    if(m_CastItem)
4327        return 0;
4328
4329    // Spell drain all exist power on cast (Only paladin lay of Hands)
4330    if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4331    {
4332        // If power type - health drain all
4333        if (m_spellInfo->powerType == POWER_HEALTH)
4334            return m_caster->GetHealth();
4335        // Else drain all power
4336        if (m_spellInfo->powerType < MAX_POWERS)
4337            return m_caster->GetPower(Powers(m_spellInfo->powerType));
4338        sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4339        return 0;
4340    }
4341
4342    // Base powerCost
4343    int32 powerCost = m_spellInfo->manaCost;
4344    // PCT cost from total amount
4345    if (m_spellInfo->ManaCostPercentage)
4346    {
4347        switch (m_spellInfo->powerType)
4348        {
4349            // health as power used
4350            case POWER_HEALTH:
4351                powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4352                break;
4353            case POWER_MANA:
4354                powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4355                break;
4356            case POWER_RAGE:
4357            case POWER_FOCUS:
4358            case POWER_ENERGY:
4359            case POWER_HAPPINESS:
4360                //            case POWER_RUNES:
4361                powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4362                break;
4363            default:
4364                sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4365                return 0;
4366        }
4367    }
4368    SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4369    // Flat mod from caster auras by spell school
4370    powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4371    // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4372    if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4373        powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4374    // Apply cost mod by spell
4375    if(Player* modOwner = m_caster->GetSpellModOwner())
4376        modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4377
4378    if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4379        powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4380
4381    // PCT mod from user auras by school
4382    powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4383    if (powerCost < 0)
4384        powerCost = 0;
4385    return powerCost;
4386}
4387
4388uint8 Spell::CheckPower()
4389{
4390    // item cast not used power
4391    if(m_CastItem)
4392        return 0;
4393
4394    // health as power used - need check health amount
4395    if(m_spellInfo->powerType == POWER_HEALTH)
4396    {
4397        if(m_caster->GetHealth() <= m_powerCost)
4398            return SPELL_FAILED_CASTER_AURASTATE;
4399        return 0;
4400    }
4401    // Check valid power type
4402    if( m_spellInfo->powerType >= MAX_POWERS )
4403    {
4404        sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4405        return SPELL_FAILED_UNKNOWN;
4406    }
4407    // Check power amount
4408    Powers powerType = Powers(m_spellInfo->powerType);
4409    if(m_caster->GetPower(powerType) < m_powerCost)
4410        return SPELL_FAILED_NO_POWER;
4411    else
4412        return 0;
4413}
4414
4415uint8 Spell::CheckItems()
4416{
4417    if (m_caster->GetTypeId() != TYPEID_PLAYER)
4418        return 0;
4419
4420    uint32 itemid, itemcount;
4421    Player* p_caster = (Player*)m_caster;
4422
4423    if(m_CastItem)
4424    {
4425        itemid = m_CastItem->GetEntry();
4426        if( !p_caster->HasItemCount(itemid,1) )
4427            return SPELL_FAILED_ITEM_NOT_READY;
4428        else
4429        {
4430            ItemPrototype const *proto = m_CastItem->GetProto();
4431            if(!proto)
4432                return SPELL_FAILED_ITEM_NOT_READY;
4433
4434            for (int i = 0; i<5; i++)
4435            {
4436                if (proto->Spells[i].SpellCharges)
4437                {
4438                    if(m_CastItem->GetSpellCharges(i)==0)
4439                        return SPELL_FAILED_NO_CHARGES_REMAIN;
4440                }
4441            }
4442
4443            uint32 ItemClass = proto->Class;
4444            if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4445            {
4446                for (int i = 0; i < 3; i++)
4447                {
4448                    // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4449                    if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4450                        continue;
4451
4452                    if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4453                        if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4454                            return (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4455
4456                    // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4457                    if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4458                    {
4459                        if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4460                            return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4461
4462                        Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4463
4464                        if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4465                            return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4466                    }
4467                }
4468            }
4469        }
4470    }
4471
4472    if(m_targets.getItemTargetGUID())
4473    {
4474        if(m_caster->GetTypeId() != TYPEID_PLAYER)
4475            return SPELL_FAILED_BAD_TARGETS;
4476
4477        if(!m_targets.getItemTarget())
4478            return SPELL_FAILED_ITEM_GONE;
4479
4480        if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4481            return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4482    }
4483    // if not item target then required item must be equipped
4484    else
4485    {
4486        if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4487            return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4488    }
4489
4490    if(m_spellInfo->RequiresSpellFocus)
4491    {
4492        CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4493        Cell cell(p);
4494        cell.data.Part.reserved = ALL_DISTRICT;
4495
4496        GameObject* ok = NULL;
4497        Trinity::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4498        Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> checker(ok,go_check);
4499
4500        TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4501        CellLock<GridReadGuard> cell_lock(cell, p);
4502        cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
4503
4504        if(!ok)
4505            return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4506
4507        focusObject = ok;                                   // game object found in range
4508    }
4509
4510    if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
4511        m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION)))
4512    {
4513        for(uint32 i=0;i<8;i++)
4514        {
4515            if(m_spellInfo->Reagent[i] <= 0)
4516                continue;
4517
4518            itemid    = m_spellInfo->Reagent[i];
4519            itemcount = m_spellInfo->ReagentCount[i];
4520
4521            // if CastItem is also spell reagent
4522            if( m_CastItem && m_CastItem->GetEntry() == itemid )
4523            {
4524                ItemPrototype const *proto = m_CastItem->GetProto();
4525                if(!proto)
4526                    return SPELL_FAILED_ITEM_NOT_READY;
4527                for(int s=0;s<5;s++)
4528                {
4529                    // CastItem will be used up and does not count as reagent
4530                    int32 charges = m_CastItem->GetSpellCharges(s);
4531                    if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4532                    {
4533                        ++itemcount;
4534                        break;
4535                    }
4536                }
4537            }
4538            if( !p_caster->HasItemCount(itemid,itemcount) )
4539                return (uint8)SPELL_FAILED_ITEM_NOT_READY;      //0x54
4540        }
4541    }
4542
4543    uint32 totems = 2;
4544    for(int i=0;i<2;++i)
4545    {
4546        if(m_spellInfo->Totem[i] != 0)
4547        {
4548            if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4549            {
4550                totems -= 1;
4551                continue;
4552            }
4553        }else
4554        totems -= 1;
4555    }
4556    if(totems != 0)
4557        return (uint8)SPELL_FAILED_TOTEMS;                  //0x7C
4558
4559    //Check items for TotemCategory
4560    uint32 TotemCategory = 2;
4561    for(int i=0;i<2;++i)
4562    {
4563        if(m_spellInfo->TotemCategory[i] != 0)
4564        {
4565            if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4566            {
4567                TotemCategory -= 1;
4568                continue;
4569            }
4570        }
4571        else
4572            TotemCategory -= 1;
4573    }
4574    if(TotemCategory != 0)
4575        return (uint8)SPELL_FAILED_TOTEM_CATEGORY;          //0x7B
4576
4577    for(int i = 0; i < 3; i++)
4578    {
4579        switch (m_spellInfo->Effect[i])
4580        {
4581            case SPELL_EFFECT_CREATE_ITEM:
4582            {
4583                if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4584                {
4585                    ItemPosCountVec dest;
4586                    uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
4587                    if (msg != EQUIP_ERR_OK )
4588                    {
4589                        p_caster->SendEquipError( msg, NULL, NULL );
4590                        return SPELL_FAILED_DONT_REPORT;
4591                    }
4592                }
4593                break;
4594            }
4595            case SPELL_EFFECT_ENCHANT_ITEM:
4596            {
4597                Item* targetItem = m_targets.getItemTarget();
4598                if(!targetItem)
4599                    return SPELL_FAILED_ITEM_NOT_FOUND;
4600
4601                if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
4602                    return SPELL_FAILED_LOWLEVEL;
4603                // Not allow enchant in trade slot for some enchant type
4604                if( targetItem->GetOwner() != m_caster )
4605                {
4606                    uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4607                    SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4608                    if(!pEnchant)
4609                        return SPELL_FAILED_ERROR;
4610                    if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4611                        return SPELL_FAILED_NOT_TRADEABLE;
4612                }
4613                break;
4614            }
4615            case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
4616            {
4617                Item *item = m_targets.getItemTarget();
4618                if(!item)
4619                    return SPELL_FAILED_ITEM_NOT_FOUND;
4620                // Not allow enchant in trade slot for some enchant type
4621                if( item->GetOwner() != m_caster )
4622                {
4623                    uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4624                    SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4625                    if(!pEnchant)
4626                        return SPELL_FAILED_ERROR;
4627                    if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4628                        return SPELL_FAILED_NOT_TRADEABLE;
4629                }
4630                break;
4631            }
4632            case SPELL_EFFECT_ENCHANT_HELD_ITEM:
4633                // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
4634                break;
4635            case SPELL_EFFECT_DISENCHANT:
4636            {
4637                if(!m_targets.getItemTarget())
4638                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4639
4640                // prevent disenchanting in trade slot
4641                if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4642                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4643
4644                ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
4645                if(!itemProto)
4646                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4647
4648                uint32 item_quality = itemProto->Quality;
4649                // 2.0.x addon: Check player enchanting level agains the item desenchanting requirements
4650                uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
4651                if (item_disenchantskilllevel == uint32(-1))
4652                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4653                if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
4654                    return SPELL_FAILED_LOW_CASTLEVEL;
4655                if(item_quality > 4 || item_quality < 2)
4656                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4657                if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
4658                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4659                if (!itemProto->DisenchantID)
4660                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4661                break;
4662            }
4663            case SPELL_EFFECT_PROSPECTING:
4664            {
4665                if(!m_targets.getItemTarget())
4666                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4667                //ensure item is a prospectable ore
4668                if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
4669                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4670                //prevent prospecting in trade slot
4671                if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4672                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4673                //Check for enough skill in jewelcrafting
4674                uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
4675                if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
4676                    return SPELL_FAILED_LOW_CASTLEVEL;
4677                //make sure the player has the required ores in inventory
4678                if(m_targets.getItemTarget()->GetCount() < 5)
4679                    return SPELL_FAILED_PROSPECT_NEED_MORE;
4680
4681                if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
4682                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4683
4684                break;
4685            }
4686            case SPELL_EFFECT_WEAPON_DAMAGE:
4687            case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
4688            {
4689                if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
4690                if( m_attackType != RANGED_ATTACK )
4691                    break;
4692                Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
4693                if(!pItem || pItem->IsBroken())
4694                    return SPELL_FAILED_EQUIPPED_ITEM;
4695
4696                switch(pItem->GetProto()->SubClass)
4697                {
4698                    case ITEM_SUBCLASS_WEAPON_THROWN:
4699                    {
4700                        uint32 ammo = pItem->GetEntry();
4701                        if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4702                            return SPELL_FAILED_NO_AMMO;
4703                    };  break;
4704                    case ITEM_SUBCLASS_WEAPON_GUN:
4705                    case ITEM_SUBCLASS_WEAPON_BOW:
4706                    case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4707                    {
4708                        uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
4709                        if(!ammo)
4710                        {
4711                            // Requires No Ammo
4712                            if(m_caster->GetDummyAura(46699))
4713                                break;                      // skip other checks
4714
4715                            return SPELL_FAILED_NO_AMMO;
4716                        }
4717
4718                        ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
4719                        if(!ammoProto)
4720                            return SPELL_FAILED_NO_AMMO;
4721
4722                        if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
4723                            return SPELL_FAILED_NO_AMMO;
4724
4725                        // check ammo ws. weapon compatibility
4726                        switch(pItem->GetProto()->SubClass)
4727                        {
4728                            case ITEM_SUBCLASS_WEAPON_BOW:
4729                            case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4730                                if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
4731                                    return SPELL_FAILED_NO_AMMO;
4732                                break;
4733                            case ITEM_SUBCLASS_WEAPON_GUN:
4734                                if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
4735                                    return SPELL_FAILED_NO_AMMO;
4736                                break;
4737                            default:
4738                                return SPELL_FAILED_NO_AMMO;
4739                        }
4740
4741                        if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4742                            return SPELL_FAILED_NO_AMMO;
4743                    };  break;
4744                    case ITEM_SUBCLASS_WEAPON_WAND:
4745                    default:
4746                        break;
4747                }
4748                break;
4749            }
4750            default:break;
4751        }
4752    }
4753
4754    return uint8(0);
4755}
4756
4757void Spell::Delayed()
4758{
4759    if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
4760        return;
4761
4762    if (m_spellState == SPELL_STATE_DELAYED)
4763        return;                                             // spell is active and can't be time-backed
4764
4765    // spells not loosing casting time ( slam, dynamites, bombs.. )
4766    if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
4767        return;
4768
4769    //check resist chance
4770    int32 resistChance = 100;                               //must be initialized to 100 for percent modifiers
4771    ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4772    resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4773    if (roll_chance_i(resistChance))
4774        return;
4775
4776    int32 delaytime = GetNextDelayAtDamageMsTime();
4777
4778    if(int32(m_timer) + delaytime > m_casttime)
4779    {
4780        delaytime = m_casttime - m_timer;
4781        m_timer = m_casttime;
4782    }
4783    else
4784        m_timer += delaytime;
4785
4786    sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
4787
4788    WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
4789    data.append(m_caster->GetPackGUID());
4790    data << uint32(delaytime);
4791
4792    m_caster->SendMessageToSet(&data,true);
4793}
4794
4795void Spell::DelayedChannel()
4796{
4797    if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
4798        return;
4799
4800    //check resist chance
4801    int32 resistChance = 100;                               //must be initialized to 100 for percent modifiers
4802    ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4803    resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4804    if (roll_chance_i(resistChance))
4805        return;
4806
4807    int32 delaytime = GetNextDelayAtDamageMsTime();
4808
4809    if(int32(m_timer) < delaytime)
4810    {
4811        delaytime = m_timer;
4812        m_timer = 0;
4813    }
4814    else
4815        m_timer -= delaytime;
4816
4817    sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
4818
4819    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4820    {
4821        if ((*ihit).missCondition == SPELL_MISS_NONE)
4822        {
4823            Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
4824            if (unit)
4825            {
4826                for (int j=0;j<3;j++)
4827                    if( ihit->effectMask & (1<<j) )
4828                        unit->DelayAura(m_spellInfo->Id, j, delaytime);
4829            }
4830
4831        }
4832    }
4833
4834    for(int j = 0; j < 3; j++)
4835    {
4836        // partially interrupt persistent area auras
4837        DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
4838        if(dynObj)
4839            dynObj->Delay(delaytime);
4840    }
4841
4842    SendChannelUpdate(m_timer);
4843}
4844
4845void Spell::UpdatePointers()
4846{
4847    if(m_originalCasterGUID==m_caster->GetGUID())
4848        m_originalCaster = m_caster;
4849    else
4850    {
4851        m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
4852        if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
4853    }
4854
4855    m_targets.Update(m_caster);
4856}
4857
4858bool Spell::IsAffectedBy(SpellEntry const *spellInfo, uint32 effectId)
4859{
4860    return spellmgr.IsAffectedBySpell(m_spellInfo,spellInfo->Id,effectId,spellInfo->EffectItemType[effectId]);
4861}
4862
4863bool Spell::CheckTargetCreatureType(Unit* target) const
4864{
4865    uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
4866
4867    // Curse of Doom : not find another way to fix spell target check :/
4868    if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
4869    {
4870        // not allow cast at player
4871        if(target->GetTypeId()==TYPEID_PLAYER)
4872            return false;
4873
4874        spellCreatureTargetMask = 0x7FF;
4875    }
4876
4877    // Dismiss Pet and Taming Lesson skipped
4878    if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
4879        spellCreatureTargetMask =  0;
4880
4881    if (spellCreatureTargetMask)
4882    {
4883        uint32 TargetCreatureType = target->GetCreatureTypeMask();
4884
4885        return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
4886    }
4887    return true;
4888}
4889
4890CurrentSpellTypes Spell::GetCurrentContainer()
4891{
4892    if (IsNextMeleeSwingSpell())
4893        return(CURRENT_MELEE_SPELL);
4894    else if (IsAutoRepeat())
4895        return(CURRENT_AUTOREPEAT_SPELL);
4896    else if (IsChanneledSpell(m_spellInfo))
4897        return(CURRENT_CHANNELED_SPELL);
4898    else
4899        return(CURRENT_GENERIC_SPELL);
4900}
4901
4902bool Spell::CheckTarget( Unit* target, uint32 eff, bool hitPhase )
4903{
4904    // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
4905    if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF && !m_magnetPair.first)
4906    {
4907        if (!CheckTargetCreatureType(target))
4908            return false;
4909    }
4910
4911    // Check targets for not_selectable unit flag and remove
4912    // A player can cast spells on his pet (or other controlled unit) though in any state
4913    if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
4914    {
4915        // any unattackable target skipped
4916        if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
4917            return false;
4918
4919        // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
4920        // in case TARGET_SCRIPT target selected by server always and can't be cheated
4921        if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
4922            m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
4923            m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
4924            return false;
4925    }
4926
4927    //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
4928    if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
4929    {
4930        if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
4931            return false;
4932
4933        if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
4934            return false;
4935    }
4936
4937    //Check targets for LOS visibility (except spells without range limitations )
4938    switch(m_spellInfo->Effect[eff])
4939    {
4940        case SPELL_EFFECT_SUMMON_PLAYER:                    // from anywhere
4941            break;
4942        case SPELL_EFFECT_DUMMY:
4943            if(m_spellInfo->Id!=20577)                      // Cannibalize
4944                break;
4945            //fall through
4946        case SPELL_EFFECT_RESURRECT_NEW:
4947            // player far away, maybe his corpse near?
4948            if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4949            {
4950                if(!m_targets.getCorpseTargetGUID())
4951                    return false;
4952
4953                Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
4954                if(!corpse)
4955                    return false;
4956
4957                if(target->GetGUID()!=corpse->GetOwnerGUID())
4958                    return false;
4959
4960                if(!corpse->IsWithinLOSInMap(m_caster))
4961                    return false;
4962            }
4963
4964            // all ok by some way or another, skip normal check
4965            break;
4966        default:                                            // normal case
4967            if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4968                return false;
4969            break;
4970    }
4971
4972    return true;
4973}
4974
4975Unit* Spell::SelectMagnetTarget()
4976{
4977    Unit* target = m_targets.getUnitTarget();
4978
4979    if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
4980    {
4981        Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
4982        for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
4983        {
4984            if(Unit* magnet = (*itr)->GetCaster())
4985            {
4986                if((*itr)->m_procCharges>0 && magnet->IsWithinLOSInMap(m_caster))
4987                {
4988                    (*itr)->SetAuraProcCharges((*itr)->m_procCharges-1);
4989                    m_magnetPair.first = true;
4990                    m_magnetPair.second = magnet;
4991
4992                    target = magnet;
4993                    m_targets.setUnitTarget(target);
4994                    break;
4995                }
4996            }
4997        }
4998    }
4999
5000    return target;
5001}
5002
5003bool Spell::IsNeedSendToClient() const
5004{
5005    return m_spellInfo->SpellVisual!=0 || IsChanneledSpell(m_spellInfo) ||
5006        m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5007}
5008
5009bool Spell::HaveTargetsForEffect( uint8 effect ) const
5010{
5011    for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5012        if(itr->effectMask & (1<<effect))
5013            return true;
5014
5015    for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5016        if(itr->effectMask & (1<<effect))
5017            return true;
5018
5019    for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5020        if(itr->effectMask & (1<<effect))
5021            return true;
5022
5023    return false;
5024}
5025
5026SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5027{
5028    m_Spell = spell;
5029}
5030
5031SpellEvent::~SpellEvent()
5032{
5033    if (m_Spell->getState() != SPELL_STATE_FINISHED)
5034        m_Spell->cancel();
5035
5036    if (m_Spell->IsDeletable())
5037    {
5038        delete m_Spell;
5039    }
5040    else
5041    {
5042        sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5043            (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5044    }
5045}
5046
5047bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5048{
5049    // update spell if it is not finished
5050    if (m_Spell->getState() != SPELL_STATE_FINISHED)
5051        m_Spell->update(p_time);
5052
5053    // check spell state to process
5054    switch (m_Spell->getState())
5055    {
5056        case SPELL_STATE_FINISHED:
5057        {
5058            // spell was finished, check deletable state
5059            if (m_Spell->IsDeletable())
5060            {
5061                // check, if we do have unfinished triggered spells
5062
5063                return(true);                               // spell is deletable, finish event
5064            }
5065            // event will be re-added automatically at the end of routine)
5066        } break;
5067
5068        case SPELL_STATE_CASTING:
5069        {
5070            // this spell is in channeled state, process it on the next update
5071            // event will be re-added automatically at the end of routine)
5072        } break;
5073
5074        case SPELL_STATE_DELAYED:
5075        {
5076            // first, check, if we have just started
5077            if (m_Spell->GetDelayStart() != 0)
5078            {
5079                // no, we aren't, do the typical update
5080                // check, if we have channeled spell on our hands
5081                if (IsChanneledSpell(m_Spell->m_spellInfo))
5082                {
5083                    // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5084                    // check, if we have casting anything else except this channeled spell and autorepeat
5085                    if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5086                    {
5087                        // another non-melee non-delayed spell is casted now, abort
5088                        m_Spell->cancel();
5089                    }
5090                    else
5091                    {
5092                        // do the action (pass spell to channeling state)
5093                        m_Spell->handle_immediate();
5094                    }
5095                    // event will be re-added automatically at the end of routine)
5096                }
5097                else
5098                {
5099                    // run the spell handler and think about what we can do next
5100                    uint64 t_offset = e_time - m_Spell->GetDelayStart();
5101                    uint64 n_offset = m_Spell->handle_delayed(t_offset);
5102                    if (n_offset)
5103                    {
5104                        // re-add us to the queue
5105                        m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5106                        return(false);                      // event not complete
5107                    }
5108                    // event complete
5109                    // finish update event will be re-added automatically at the end of routine)
5110                }
5111            }
5112            else
5113            {
5114                // delaying had just started, record the moment
5115                m_Spell->SetDelayStart(e_time);
5116                // re-plan the event for the delay moment
5117                m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5118                return(false);                              // event not complete
5119            }
5120        } break;
5121
5122        default:
5123        {
5124            // all other states
5125            // event will be re-added automatically at the end of routine)
5126        } break;
5127    }
5128
5129    // spell processing not complete, plan event on the next update interval
5130    m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5131    return(false);                                          // event not complete
5132}
5133
5134void SpellEvent::Abort(uint64 /*e_time*/)
5135{
5136    // oops, the spell we try to do is aborted
5137    if (m_Spell->getState() != SPELL_STATE_FINISHED)
5138        m_Spell->cancel();
5139}
Note: See TracBrowser for help on using the browser.