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

Revision 139, 195.6 kB (checked in by yumileroy, 17 years ago)

[svn] Spell target selection improvement. Remove most mangos hacks in spell target selection. (work almost done)
Merge mangos svn rev 6744.

Original author: megamage
Date: 2008-10-31 11:04:32-05:00

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