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

Revision 248, 197.1 kB (checked in by yumileroy, 17 years ago)

*Do not let CC spells interrupt themselves.

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