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

Revision 220, 196.9 kB (checked in by yumileroy, 17 years ago)

[svn] Cast on caster for SPELL_EFFECT_TRADE_SKILL.

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