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

Revision 157, 196.3 kB (checked in by yumileroy, 17 years ago)

[svn] Fix hunter's frozen trap, half duration when pvp.
Use vector to store linked spell information to support multiple effects.

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