Phase system development continue.
[getmangos.git] / src / game / Spell.cpp
blob54825b2665bb5910f816be78d20a3e7feaa0af6e
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "SpellAuras.h"
37 #include "Group.h"
38 #include "UpdateData.h"
39 #include "MapManager.h"
40 #include "ObjectAccessor.h"
41 #include "CellImpl.h"
42 #include "Policies/SingletonImp.h"
43 #include "SharedDefines.h"
44 #include "LootMgr.h"
45 #include "VMapFactory.h"
46 #include "BattleGround.h"
47 #include "Util.h"
49 #define SPELL_CHANNEL_UPDATE_INTERVAL 1000
51 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
53 bool IsQuestTameSpell(uint32 spellId)
55 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
56 if (!spellproto) return false;
58 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
59 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
62 SpellCastTargets::SpellCastTargets()
64 m_unitTarget = NULL;
65 m_itemTarget = NULL;
66 m_GOTarget = NULL;
68 m_unitTargetGUID = 0;
69 m_GOTargetGUID = 0;
70 m_CorpseTargetGUID = 0;
71 m_itemTargetGUID = 0;
72 m_itemTargetEntry = 0;
74 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
75 m_strTarget = "";
76 m_targetMask = 0;
79 SpellCastTargets::~SpellCastTargets()
83 void SpellCastTargets::setUnitTarget(Unit *target)
85 if (!target)
86 return;
88 m_destX = target->GetPositionX();
89 m_destY = target->GetPositionY();
90 m_destZ = target->GetPositionZ();
91 m_unitTarget = target;
92 m_unitTargetGUID = target->GetGUID();
93 m_targetMask |= TARGET_FLAG_UNIT;
96 void SpellCastTargets::setDestination(float x, float y, float z)
98 m_destX = x;
99 m_destY = y;
100 m_destZ = z;
101 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
104 void SpellCastTargets::setSource(float x, float y, float z)
106 m_srcX = x;
107 m_srcY = y;
108 m_srcZ = z;
109 m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
112 void SpellCastTargets::setGOTarget(GameObject *target)
114 m_GOTarget = target;
115 m_GOTargetGUID = target->GetGUID();
116 // m_targetMask |= TARGET_FLAG_OBJECT;
119 void SpellCastTargets::setItemTarget(Item* item)
121 if(!item)
122 return;
124 m_itemTarget = item;
125 m_itemTargetGUID = item->GetGUID();
126 m_itemTargetEntry = item->GetEntry();
127 m_targetMask |= TARGET_FLAG_ITEM;
130 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
132 m_CorpseTargetGUID = corpse->GetGUID();
135 void SpellCastTargets::Update(Unit* caster)
137 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
138 m_unitTarget = m_unitTargetGUID ?
139 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
140 NULL;
142 m_itemTarget = NULL;
143 if(caster->GetTypeId()==TYPEID_PLAYER)
145 if(m_targetMask & TARGET_FLAG_ITEM)
146 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
147 else
149 Player* pTrader = ((Player*)caster)->GetTrader();
150 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
151 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
153 if(m_itemTarget)
154 m_itemTargetEntry = m_itemTarget->GetEntry();
158 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
160 if(data->rpos()+4 > data->size())
161 return false;
163 *data >> m_targetMask;
165 if(m_targetMask == TARGET_FLAG_SELF)
167 m_destX = caster->GetPositionX();
168 m_destY = caster->GetPositionY();
169 m_destZ = caster->GetPositionZ();
170 m_unitTarget = caster;
171 m_unitTargetGUID = caster->GetGUID();
172 return true;
175 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
176 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
177 if(!data->readPackGUID(m_unitTargetGUID))
178 return false;
180 if( m_targetMask & ( TARGET_FLAG_OBJECT ))
181 if(!data->readPackGUID(m_GOTargetGUID))
182 return false;
184 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
185 if(!data->readPackGUID(m_itemTargetGUID))
186 return false;
188 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
189 if(!data->readPackGUID(m_CorpseTargetGUID))
190 return false;
192 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
194 if(data->rpos()+4+4+4 > data->size())
195 return false;
197 *data >> m_srcX >> m_srcY >> m_srcZ;
198 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
199 return false;
202 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
204 if(data->rpos()+1+4+4+4 > data->size())
205 return false;
207 if(!data->readPackGUID(m_unitTargetGUID))
208 return false;
210 *data >> m_destX >> m_destY >> m_destZ;
211 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
212 return false;
215 if( m_targetMask & TARGET_FLAG_STRING )
217 if(data->rpos()+1 > data->size())
218 return false;
220 *data >> m_strTarget;
223 // find real units/GOs
224 Update(caster);
225 return true;
228 void SpellCastTargets::write ( WorldPacket * data )
230 *data << uint32(m_targetMask);
232 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
234 if(m_targetMask & TARGET_FLAG_UNIT)
236 if(m_unitTarget)
237 data->append(m_unitTarget->GetPackGUID());
238 else
239 *data << uint8(0);
241 else if( m_targetMask & TARGET_FLAG_OBJECT )
243 if(m_GOTarget)
244 data->append(m_GOTarget->GetPackGUID());
245 else
246 *data << uint8(0);
248 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
249 data->appendPackGUID(m_CorpseTargetGUID);
250 else
251 *data << uint8(0);
254 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
256 if(m_itemTarget)
257 data->append(m_itemTarget->GetPackGUID());
258 else
259 *data << uint8(0);
262 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
263 *data << m_srcX << m_srcY << m_srcZ;
265 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
267 if(m_unitTarget)
268 data->append(m_unitTarget->GetPackGUID());
269 else
270 *data << uint8(0);
272 *data << m_destX << m_destY << m_destZ;
275 if( m_targetMask & TARGET_FLAG_STRING )
276 *data << m_strTarget;
279 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
281 ASSERT( Caster != NULL && info != NULL );
282 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
284 m_spellInfo = info;
285 m_caster = Caster;
286 m_selfContainer = NULL;
287 m_triggeringContainer = triggeringContainer;
288 m_referencedFromCurrentSpell = false;
289 m_executedCurrently = false;
290 m_delayStart = 0;
291 m_delayAtDamageCount = 0;
293 m_applyMultiplierMask = 0;
295 // Get data for type of attack
296 switch (m_spellInfo->DmgClass)
298 case SPELL_DAMAGE_CLASS_MELEE:
299 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
300 m_attackType = OFF_ATTACK;
301 else
302 m_attackType = BASE_ATTACK;
303 break;
304 case SPELL_DAMAGE_CLASS_RANGED:
305 m_attackType = RANGED_ATTACK;
306 break;
307 default:
308 // Wands
309 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
310 m_attackType = RANGED_ATTACK;
311 else
312 m_attackType = BASE_ATTACK;
313 break;
316 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
318 if(m_attackType == RANGED_ATTACK)
320 // wand case
321 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
323 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
324 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
327 // Set health leech amount to zero
328 m_healthLeech = 0;
330 if(originalCasterGUID)
331 m_originalCasterGUID = originalCasterGUID;
332 else
333 m_originalCasterGUID = m_caster->GetGUID();
335 if(m_originalCasterGUID==m_caster->GetGUID())
336 m_originalCaster = m_caster;
337 else
339 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
340 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
343 for(int i=0; i <3; ++i)
344 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
346 m_spellState = SPELL_STATE_NULL;
348 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
349 m_TriggerSpells.clear();
350 m_IsTriggeredSpell = triggered;
351 //m_AreaAura = false;
352 m_CastItem = NULL;
354 unitTarget = NULL;
355 itemTarget = NULL;
356 gameObjTarget = NULL;
357 focusObject = NULL;
358 m_cast_count = 0;
359 m_glyphIndex = 0;
360 m_preCastSpell = 0;
361 m_triggeredByAuraSpell = NULL;
363 //Auto Shot & Shoot (wand)
364 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
366 m_runesState = 0;
367 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
368 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
369 m_timer = 0; // will set to castime in prepare
371 m_needAliveTargetMask = 0;
373 // determine reflection
374 m_canReflect = false;
376 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED))
378 for(int j=0;j<3;j++)
380 if (m_spellInfo->Effect[j]==0)
381 continue;
383 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
384 m_canReflect = true;
385 else
386 m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NEGATIVE) ? true : false;
388 if(m_canReflect)
389 continue;
390 else
391 break;
395 CleanupTargetList();
398 Spell::~Spell()
402 void Spell::FillTargetMap()
404 // TODO: ADD the correct target FILLS!!!!!!
406 for(uint32 i=0;i<3;i++)
408 // not call for empty effect.
409 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
410 if(m_spellInfo->Effect[i]==0)
411 continue;
413 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
414 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
415 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
416 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
417 continue;
419 // TODO: find a way so this is not needed?
420 // for area auras always add caster as target (needed for totems for example)
421 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
422 AddUnitTarget(m_caster, i);
424 std::list<Unit*> tmpUnitMap;
426 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
427 // but need it support in some know cases
428 switch(m_spellInfo->EffectImplicitTargetA[i])
430 case TARGET_CASTER_COORDINATES:
431 // Note: this hack with search required until GO casting not implemented
432 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
433 // currently each enemy selected explicitly and self cast damage
434 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
436 if(m_targets.getUnitTarget())
437 tmpUnitMap.push_back(m_targets.getUnitTarget());
439 else
441 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
442 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
444 break;
445 case TARGET_TABLE_X_Y_Z_COORDINATES:
446 // Only if target A, for target B (used in teleports) dest select in effect
447 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
448 break;
449 default:
450 switch(m_spellInfo->EffectImplicitTargetB[i])
452 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
453 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
454 break;
455 default:
456 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
457 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
458 break;
460 break;
463 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
464 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
466 // add here custom effects that need default target.
467 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
468 switch(m_spellInfo->Effect[i])
470 case SPELL_EFFECT_DUMMY:
472 switch(m_spellInfo->Id)
474 case 20577: // Cannibalize
476 // non-standard target selection
477 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
478 float max_range = GetSpellMaxRange(srange);
480 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
481 Cell cell(p);
482 cell.data.Part.reserved = ALL_DISTRICT;
483 cell.SetNoCreate();
485 WorldObject* result = NULL;
487 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
488 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(m_caster, result, u_check);
490 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
491 CellLock<GridReadGuard> cell_lock(cell, p);
492 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
494 if(!result)
496 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
497 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
500 if(result)
502 switch(result->GetTypeId())
504 case TYPEID_UNIT:
505 case TYPEID_PLAYER:
506 tmpUnitMap.push_back((Unit*)result);
507 break;
508 case TYPEID_CORPSE:
509 m_targets.setCorpseTarget((Corpse*)result);
510 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
511 tmpUnitMap.push_back(owner);
512 break;
515 else
517 // clear cooldown at fail
518 if(m_caster->GetTypeId()==TYPEID_PLAYER)
520 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
522 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
523 data << uint32(m_spellInfo->Id);
524 data << uint64(m_caster->GetGUID());
525 ((Player*)m_caster)->GetSession()->SendPacket(&data);
528 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
529 finish(false);
531 break;
533 default:
534 if(m_targets.getUnitTarget())
535 tmpUnitMap.push_back(m_targets.getUnitTarget());
536 break;
538 break;
540 case SPELL_EFFECT_RESURRECT:
541 case SPELL_EFFECT_PARRY:
542 case SPELL_EFFECT_BLOCK:
543 case SPELL_EFFECT_CREATE_ITEM:
544 case SPELL_EFFECT_TRIGGER_SPELL:
545 case SPELL_EFFECT_TRIGGER_MISSILE:
546 case SPELL_EFFECT_LEARN_SPELL:
547 case SPELL_EFFECT_SKILL_STEP:
548 case SPELL_EFFECT_PROFICIENCY:
549 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
550 case SPELL_EFFECT_SELF_RESURRECT:
551 case SPELL_EFFECT_REPUTATION:
552 if(m_targets.getUnitTarget())
553 tmpUnitMap.push_back(m_targets.getUnitTarget());
554 break;
555 case SPELL_EFFECT_SUMMON_PLAYER:
556 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
558 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
559 if(target)
560 tmpUnitMap.push_back(target);
562 break;
563 case SPELL_EFFECT_RESURRECT_NEW:
564 if(m_targets.getUnitTarget())
565 tmpUnitMap.push_back(m_targets.getUnitTarget());
566 if(m_targets.getCorpseTargetGUID())
568 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
569 if(corpse)
571 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
572 if(owner)
573 tmpUnitMap.push_back(owner);
576 break;
577 case SPELL_EFFECT_SUMMON:
578 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
580 if(m_targets.getUnitTarget())
581 tmpUnitMap.push_back(m_targets.getUnitTarget());
583 else
584 tmpUnitMap.push_back(m_caster);
585 break;
586 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
587 case SPELL_EFFECT_TRANS_DOOR:
588 case SPELL_EFFECT_ADD_FARSIGHT:
589 case SPELL_EFFECT_APPLY_GLYPH:
590 case SPELL_EFFECT_STUCK:
591 case SPELL_EFFECT_FEED_PET:
592 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
593 case SPELL_EFFECT_SKILL:
594 tmpUnitMap.push_back(m_caster);
595 break;
596 case SPELL_EFFECT_LEARN_PET_SPELL:
597 if(Pet* pet = m_caster->GetPet())
598 tmpUnitMap.push_back(pet);
599 break;
600 case SPELL_EFFECT_ENCHANT_ITEM:
601 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
602 case SPELL_EFFECT_DISENCHANT:
603 case SPELL_EFFECT_PROSPECTING:
604 case SPELL_EFFECT_MILLING:
605 if(m_targets.getItemTarget())
606 AddItemTarget(m_targets.getItemTarget(), i);
607 break;
608 case SPELL_EFFECT_APPLY_AURA:
609 switch(m_spellInfo->EffectApplyAuraName[i])
611 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)
612 case SPELL_AURA_ADD_PCT_MODIFIER:
613 tmpUnitMap.push_back(m_caster);
614 break;
615 default: // apply to target in other case
616 if(m_targets.getUnitTarget())
617 tmpUnitMap.push_back(m_targets.getUnitTarget());
618 break;
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())
629 tmpUnitMap.push_back(m_targets.getUnitTarget());
631 else if (m_targets.getCorpseTargetGUID())
633 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
634 if(corpse)
636 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
637 if(owner)
638 tmpUnitMap.push_back(owner);
641 break;
642 default:
643 break;
647 if(m_caster->GetTypeId() == TYPEID_PLAYER)
649 Player *me = (Player*)m_caster;
650 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
652 Unit *owner = (*itr)->GetOwner();
653 Unit *u = owner ? owner : (*itr);
654 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
656 me->UpdatePvP(true);
657 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
658 break;
663 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
665 if (!CheckTarget (*itr, i))
667 itr = tmpUnitMap.erase(itr);
668 continue;
670 else
671 ++itr;
674 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
675 AddUnitTarget((*iunit), i);
679 void Spell::prepareDataForTriggerSystem()
681 //==========================================================================================
682 // Now fill data for trigger system, need know:
683 // Ñan spell trigger another or not ( m_canTrigger )
684 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
685 //==========================================================================================
686 // Fill flag can spell trigger or not
687 // TODO: possible exist spell attribute for this
688 m_canTrigger = false;
690 if (m_CastItem)
691 m_canTrigger = false; // Do not trigger from item cast spell
692 else if (!m_IsTriggeredSpell)
693 m_canTrigger = true; // Normal cast - can trigger
694 else if (!m_triggeredByAuraSpell)
695 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
697 if (!m_canTrigger) // Exceptions (some periodic triggers)
699 switch (m_spellInfo->SpellFamilyName)
701 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
702 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
703 break;
704 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
705 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
706 break;
707 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
708 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
709 break;
710 case SPELLFAMILY_ROGUE: // For poisons need do it
711 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
712 break;
713 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot
714 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000214LL ||
715 m_spellInfo->SpellFamilyFlags2 & 0x200) m_canTrigger = true;
716 break;
717 case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it
718 if (m_spellInfo->SpellFamilyFlags & 0x0001000900B80400LL) m_canTrigger = true;
719 break;
723 // Get data for type of attack and fill base info for trigger
724 switch (m_spellInfo->DmgClass)
726 case SPELL_DAMAGE_CLASS_MELEE:
727 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
728 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
729 break;
730 case SPELL_DAMAGE_CLASS_RANGED:
731 // Auto attack
732 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
734 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
735 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
737 else // Ranged spell attack
739 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
740 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
742 break;
743 default:
744 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
746 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
747 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
749 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
751 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
752 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
754 else // Negative spell
756 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
757 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
759 break;
761 // Hunter traps spells (for Entrapment trigger)
762 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
763 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x000020000000001CLL)
764 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
767 void Spell::CleanupTargetList()
769 m_UniqueTargetInfo.clear();
770 m_UniqueGOTargetInfo.clear();
771 m_UniqueItemInfo.clear();
772 m_delayMoment = 0;
775 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
777 if( m_spellInfo->Effect[effIndex]==0 )
778 return;
780 // Check for effect immune skip if immuned
781 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
783 uint64 targetGUID = pVictim->GetGUID();
785 // Lookup target in already in list
786 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
788 if (targetGUID == ihit->targetGUID) // Found in list
790 if (!immuned)
791 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
792 return;
796 // This is new target calculate data for him
798 // Get spell hit result on target
799 TargetInfo target;
800 target.targetGUID = targetGUID; // Store target GUID
801 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
802 target.processed = false; // Effects not apply on target
804 // Calculate hit result
805 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
807 // Spell have speed - need calculate incoming time
808 if (m_spellInfo->speed > 0.0f)
810 // calculate spell incoming interval
811 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
812 if (dist < 5.0f) dist = 5.0f;
813 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
815 // Calculate minimum incoming time
816 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
817 m_delayMoment = target.timeDelay;
819 else
820 target.timeDelay = 0LL;
822 // If target reflect spell back to caster
823 if (target.missCondition==SPELL_MISS_REFLECT)
825 // Calculate reflected spell result on caster
826 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
828 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
829 target.reflectResult = SPELL_MISS_PARRY;
831 // Increase time interval for reflected spells by 1.5
832 target.timeDelay+=target.timeDelay>>1;
834 else
835 target.reflectResult = SPELL_MISS_NONE;
837 // Add target to list
838 m_UniqueTargetInfo.push_back(target);
841 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
843 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
844 if (unit)
845 AddUnitTarget(unit, effIndex);
848 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
850 if( m_spellInfo->Effect[effIndex]==0 )
851 return;
853 uint64 targetGUID = pVictim->GetGUID();
855 // Lookup target in already in list
856 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
858 if (targetGUID == ihit->targetGUID) // Found in list
860 ihit->effectMask |= 1<<effIndex; // Add only effect mask
861 return;
865 // This is new target calculate data for him
867 GOTargetInfo target;
868 target.targetGUID = targetGUID;
869 target.effectMask = 1<<effIndex;
870 target.processed = false; // Effects not apply on target
872 // Spell have speed - need calculate incoming time
873 if (m_spellInfo->speed > 0.0f)
875 // calculate spell incoming interval
876 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
877 if (dist < 5.0f) dist = 5.0f;
878 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
879 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
880 m_delayMoment = target.timeDelay;
882 else
883 target.timeDelay = 0LL;
885 // Add target to list
886 m_UniqueGOTargetInfo.push_back(target);
889 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
891 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
892 if (go)
893 AddGOTarget(go, effIndex);
896 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
898 if( m_spellInfo->Effect[effIndex]==0 )
899 return;
901 // Lookup target in already in list
902 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
904 if (pitem == ihit->item) // Found in list
906 ihit->effectMask |= 1<<effIndex; // Add only effect mask
907 return;
911 // This is new target add data
913 ItemTargetInfo target;
914 target.item = pitem;
915 target.effectMask = 1<<effIndex;
916 m_UniqueItemInfo.push_back(target);
919 void Spell::DoAllEffectOnTarget(TargetInfo *target)
921 if (target->processed) // Check target
922 return;
923 target->processed = true; // Target checked in apply effects procedure
925 // Get mask of effects for target
926 uint32 mask = target->effectMask;
928 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
929 if (!unit)
930 return;
932 // Get original caster (if exist) and calculate damage/healing from him data
933 Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
935 // Skip if m_originalCaster not avaiable
936 if (!caster)
937 return;
939 SpellMissInfo missInfo = target->missCondition;
940 // Need init unitTarget by default unit (can changed in code on reflect)
941 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
942 unitTarget = unit;
944 // Reset damage/healing counter
945 m_damage = 0;
946 m_healing = 0;
948 // Fill base trigger info
949 uint32 procAttacker = m_procAttacker;
950 uint32 procVictim = m_procVictim;
951 uint32 procEx = PROC_EX_NONE;
953 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
954 DoSpellHitOnUnit(unit, mask);
955 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
957 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
958 DoSpellHitOnUnit(m_caster, mask);
961 // All calculated do it!
962 // Do healing and triggers
963 if (m_healing)
965 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
966 uint32 addhealth = m_healing;
967 if (crit)
969 procEx |= PROC_EX_CRITICAL_HIT;
970 addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
972 else
973 procEx |= PROC_EX_NORMAL_HIT;
975 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
977 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
978 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
979 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
981 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
983 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
984 if(caster->GetTypeId()==TYPEID_PLAYER)
985 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
986 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
988 // Do damage and triggers
989 else if (m_damage)
991 // Fill base damage struct (unitTarget - is real spell target)
992 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
994 // Add bonuses and fill damageInfo struct
995 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
997 // Send log damage message to client
998 caster->SendSpellNonMeleeDamageLog(&damageInfo);
1000 procEx = createProcExtendMask(&damageInfo, missInfo);
1001 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1003 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1004 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1005 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
1007 caster->DealSpellDamage(&damageInfo, true);
1009 // Judgement of Blood
1010 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1012 int32 damagePoint = damageInfo.damage * 33 / 100;
1013 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1016 // Passive spell hits/misses or active spells only misses (only triggers)
1017 else
1019 // Fill base damage struct (unitTarget - is real spell target)
1020 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1021 procEx = createProcExtendMask(&damageInfo, missInfo);
1022 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1023 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1024 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1027 // Call scripted function for AI if this spell is casted upon a creature (except pets)
1028 if(IS_CREATURE_GUID(target->targetGUID))
1030 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1031 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1032 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1033 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1035 if(((Creature*)unit)->AI())
1036 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1040 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1042 if(!unit || !effectMask)
1043 return;
1045 // Recheck immune (only for delayed spells)
1046 if( m_spellInfo->speed && (
1047 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1048 unit->IsImmunedToSpell(m_spellInfo)))
1050 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1051 return;
1054 if (unit->GetTypeId() == TYPEID_PLAYER)
1056 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1057 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1060 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1062 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1065 if( m_caster != unit )
1067 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1068 if (m_spellInfo->speed > 0.0f &&
1069 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1070 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1072 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1073 return;
1076 if( !m_caster->IsFriendlyTo(unit) )
1078 // for delayed spells ignore not visible explicit target
1079 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1081 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1082 return;
1085 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1087 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1089 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1090 unit->SetStandState(UNIT_STAND_STATE_STAND);
1092 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1093 ((Creature*)unit)->AI()->AttackStart(m_caster);
1095 unit->SetInCombatWith(m_caster);
1096 m_caster->SetInCombatWith(unit);
1098 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1100 m_caster->SetContestedPvP(attackedPlayer);
1102 unit->AddThreat(m_caster, 0.0f);
1105 else
1107 // for delayed spells ignore negative spells (after duel end) for friendly targets
1108 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1110 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1111 return;
1114 // assisting case, healing and resurrection
1115 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1116 m_caster->SetContestedPvP();
1117 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1119 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1120 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1125 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1126 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1127 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1128 // Increase Diminishing on unit, current informations for actually casts will use values above
1129 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1130 unit->IncrDiminishing(m_diminishGroup);
1132 // Apply additional spell effects to target
1133 if (m_preCastSpell)
1134 m_caster->CastSpell(unit,m_preCastSpell, true, m_CastItem);
1136 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1138 if (effectMask & (1<<effectNumber))
1140 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1141 if ( m_applyMultiplierMask & (1 << effectNumber) )
1143 // Get multiplier
1144 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1145 // Apply multiplier mods
1146 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1147 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1148 m_damageMultipliers[effectNumber] *= multiplier;
1154 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1156 if (target->processed) // Check target
1157 return;
1158 target->processed = true; // Target checked in apply effects procedure
1160 uint32 effectMask = target->effectMask;
1161 if(!effectMask)
1162 return;
1164 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1165 if(!go)
1166 return;
1168 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1169 if (effectMask & (1<<effectNumber))
1170 HandleEffects(NULL,NULL,go,effectNumber);
1172 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1173 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1174 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1175 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1178 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1180 uint32 effectMask = target->effectMask;
1181 if(!target->item || !effectMask)
1182 return;
1184 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1185 if (effectMask & (1<<effectNumber))
1186 HandleEffects(NULL, target->item, NULL, effectNumber);
1189 bool Spell::IsAliveUnitPresentInTargetList()
1191 // Not need check return true
1192 if (m_needAliveTargetMask == 0)
1193 return true;
1195 uint8 needAliveTargetMask = m_needAliveTargetMask;
1197 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1199 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1201 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1203 if (unit && unit->isAlive())
1204 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1208 // is all effects from m_needAliveTargetMask have alive targets
1209 return needAliveTargetMask==0;
1212 // Helper for Chain Healing
1213 // Spell target first
1214 // Raidmates then descending by injury suffered (MaxHealth - Health)
1215 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1216 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1218 const Unit* MainTarget;
1219 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1220 // functor for operator ">"
1221 bool operator()(Unit const* _Left, Unit const* _Right) const
1223 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1225 int32 ChainHealingHash(Unit const* Target) const
1227 if (Target == MainTarget)
1228 return 0;
1229 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1230 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1232 if (Target->GetHealth() == Target->GetMaxHealth())
1233 return 40000;
1234 else
1235 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1237 else
1238 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1242 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1244 public:
1245 const Unit* MainTarget;
1246 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1248 bool operator()(const Unit* Target)
1250 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1254 // Helper for targets nearest to the spell target
1255 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1256 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1258 const Unit* MainTarget;
1259 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1260 // functor for operator ">"
1261 bool operator()(const Unit* _Left, const Unit* _Right) const
1263 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1267 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1269 float radius;
1270 if (m_spellInfo->EffectRadiusIndex[i])
1271 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1272 else
1273 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1275 if(m_originalCaster)
1276 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1277 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1279 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1280 if(m_originalCaster)
1281 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1282 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1284 // Get spell max affected targets
1285 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1286 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1287 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1289 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1290 continue;
1291 unMaxTargets+=(*m)->GetModifier()->m_amount;
1293 switch(cur)
1295 case TARGET_TOTEM_EARTH:
1296 case TARGET_TOTEM_WATER:
1297 case TARGET_TOTEM_AIR:
1298 case TARGET_TOTEM_FIRE:
1299 case TARGET_SELF:
1300 case TARGET_SELF2:
1301 case TARGET_DYNAMIC_OBJECT:
1302 case TARGET_AREAEFFECT_CUSTOM:
1303 case TARGET_AREAEFFECT_CUSTOM_2:
1304 case TARGET_SUMMON:
1306 TagUnitMap.push_back(m_caster);
1307 break;
1309 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1311 m_targets.m_targetMask = 0;
1312 unMaxTargets = EffectChainTarget;
1313 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1315 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1316 Cell cell(p);
1317 cell.data.Part.reserved = ALL_DISTRICT;
1318 cell.SetNoCreate();
1320 std::list<Unit *> tempUnitMap;
1323 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1324 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1326 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1327 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1329 CellLock<GridReadGuard> cell_lock(cell, p);
1330 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1331 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1334 if(tempUnitMap.empty())
1335 break;
1337 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1339 //Now to get us a random target that's in the initial range of the spell
1340 uint32 t = 0;
1341 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1342 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1343 ++t, ++itr;
1345 if(!t)
1346 break;
1348 itr = tempUnitMap.begin();
1349 std::advance(itr, rand()%t);
1350 Unit *pUnitTarget = *itr;
1351 TagUnitMap.push_back(pUnitTarget);
1353 tempUnitMap.erase(itr);
1355 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1357 t = unMaxTargets - 1;
1358 Unit *prev = pUnitTarget;
1359 std::list<Unit*>::iterator next = tempUnitMap.begin();
1361 while(t && next != tempUnitMap.end() )
1363 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1364 break;
1366 if(!prev->IsWithinLOSInMap(*next))
1368 ++next;
1369 continue;
1372 prev = *next;
1373 TagUnitMap.push_back(prev);
1374 tempUnitMap.erase(next);
1375 tempUnitMap.sort(TargetDistanceOrder(prev));
1376 next = tempUnitMap.begin();
1378 --t;
1380 }break;
1381 case TARGET_RANDOM_FRIEND_CHAIN_IN_AREA:
1383 m_targets.m_targetMask = 0;
1384 unMaxTargets = EffectChainTarget;
1385 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1386 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1387 Cell cell(p);
1388 cell.data.Part.reserved = ALL_DISTRICT;
1389 cell.SetNoCreate();
1390 std::list<Unit *> tempUnitMap;
1392 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1393 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1395 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1396 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1398 CellLock<GridReadGuard> cell_lock(cell, p);
1399 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1400 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1403 if(tempUnitMap.empty())
1404 break;
1406 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1408 //Now to get us a random target that's in the initial range of the spell
1409 uint32 t = 0;
1410 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1411 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1412 ++t, ++itr;
1414 if(!t)
1415 break;
1417 itr = tempUnitMap.begin();
1418 std::advance(itr, rand()%t);
1419 Unit *pUnitTarget = *itr;
1420 TagUnitMap.push_back(pUnitTarget);
1422 tempUnitMap.erase(itr);
1424 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1426 t = unMaxTargets - 1;
1427 Unit *prev = pUnitTarget;
1428 std::list<Unit*>::iterator next = tempUnitMap.begin();
1430 while(t && next != tempUnitMap.end() )
1432 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1433 break;
1435 if(!prev->IsWithinLOSInMap(*next))
1437 ++next;
1438 continue;
1440 prev = *next;
1441 TagUnitMap.push_back(prev);
1442 tempUnitMap.erase(next);
1443 tempUnitMap.sort(TargetDistanceOrder(prev));
1444 next = tempUnitMap.begin();
1445 --t;
1447 }break;
1448 case TARGET_PET:
1450 Pet* tmpUnit = m_caster->GetPet();
1451 if (!tmpUnit) break;
1452 TagUnitMap.push_back(tmpUnit);
1453 break;
1455 case TARGET_CHAIN_DAMAGE:
1457 if (EffectChainTarget <= 1)
1459 Unit* pUnitTarget = SelectMagnetTarget();
1460 if(pUnitTarget)
1461 TagUnitMap.push_back(pUnitTarget);
1463 else
1465 Unit* pUnitTarget = m_targets.getUnitTarget();
1466 if(!pUnitTarget)
1467 break;
1469 unMaxTargets = EffectChainTarget;
1471 float max_range;
1472 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1473 max_range = radius; //
1474 else
1475 //FIXME: This very like horrible hack and wrong for most spells
1476 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1478 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1479 Cell cell(p);
1480 cell.data.Part.reserved = ALL_DISTRICT;
1481 cell.SetNoCreate();
1483 Unit* originalCaster = GetOriginalCaster();
1484 if(originalCaster)
1486 std::list<Unit *> tempUnitMap;
1489 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1490 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1492 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1493 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1495 CellLock<GridReadGuard> cell_lock(cell, p);
1496 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1497 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1500 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1502 if(tempUnitMap.empty())
1503 break;
1505 if(*tempUnitMap.begin() == pUnitTarget)
1506 tempUnitMap.erase(tempUnitMap.begin());
1508 TagUnitMap.push_back(pUnitTarget);
1509 uint32 t = unMaxTargets - 1;
1510 Unit *prev = pUnitTarget;
1511 std::list<Unit*>::iterator next = tempUnitMap.begin();
1513 while(t && next != tempUnitMap.end() )
1515 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1516 break;
1518 if(!prev->IsWithinLOSInMap(*next))
1520 ++next;
1521 continue;
1524 prev = *next;
1525 TagUnitMap.push_back(prev);
1526 tempUnitMap.erase(next);
1527 tempUnitMap.sort(TargetDistanceOrder(prev));
1528 next = tempUnitMap.begin();
1530 --t;
1534 }break;
1535 case TARGET_ALL_ENEMY_IN_AREA:
1537 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1538 Cell cell(p);
1539 cell.data.Part.reserved = ALL_DISTRICT;
1540 cell.SetNoCreate();
1542 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1544 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1545 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1547 CellLock<GridReadGuard> cell_lock(cell, p);
1548 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1549 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1550 }break;
1551 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1553 // targets the ground, not the units in the area
1554 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1556 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1557 Cell cell(p);
1558 cell.data.Part.reserved = ALL_DISTRICT;
1559 cell.SetNoCreate();
1561 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1563 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1564 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1566 CellLock<GridReadGuard> cell_lock(cell, p);
1567 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1568 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1570 // exclude caster (this can be important if this not original caster)
1571 TagUnitMap.remove(m_caster);
1573 }break;
1574 case TARGET_DUELVSPLAYER_COORDINATES:
1576 if(Unit* currentTarget = m_targets.getUnitTarget())
1578 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1579 TagUnitMap.push_back(currentTarget);
1581 }break;
1582 case TARGET_ALL_PARTY_AROUND_CASTER:
1583 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1584 case TARGET_ALL_PARTY:
1585 case TARGET_ALL_RAID_AROUND_CASTER:
1587 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1588 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1590 if(pGroup)
1592 uint8 subgroup = pTarget->GetSubGroup();
1594 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1596 Player* Target = itr->getSource();
1598 // IsHostileTo check duel and controlled by enemy
1599 if( Target &&
1600 (cur==TARGET_ALL_RAID_AROUND_CASTER || Target->GetSubGroup()==subgroup) &&
1601 !m_caster->IsHostileTo(Target) )
1603 if( m_caster->IsWithinDistInMap(Target, radius) )
1604 TagUnitMap.push_back(Target);
1606 if(Pet* pet = Target->GetPet())
1607 if( m_caster->IsWithinDistInMap(pet, radius) )
1608 TagUnitMap.push_back(pet);
1612 else
1614 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1615 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1616 TagUnitMap.push_back(ownerOrSelf);
1617 if(Pet* pet = ownerOrSelf->GetPet())
1618 if( m_caster->IsWithinDistInMap(pet, radius) )
1619 TagUnitMap.push_back(pet);
1621 }break;
1622 case TARGET_SINGLE_FRIEND:
1623 case TARGET_SINGLE_FRIEND_2:
1625 if(m_targets.getUnitTarget())
1626 TagUnitMap.push_back(m_targets.getUnitTarget());
1627 }break;
1628 case TARGET_NONCOMBAT_PET:
1630 if(Unit* target = m_targets.getUnitTarget())
1631 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1632 TagUnitMap.push_back(target);
1633 }break;
1634 case TARGET_CASTER_COORDINATES:
1636 // Check original caster is GO - set its coordinates as dst cast
1637 WorldObject *caster = NULL;
1638 if (m_originalCasterGUID)
1639 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
1640 if (!caster)
1641 caster = m_caster;
1642 // Set dest for targets
1643 m_targets.setDestination(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ());
1644 }break;
1645 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1647 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1648 Cell cell(p);
1649 cell.data.Part.reserved = ALL_DISTRICT;
1650 cell.SetNoCreate();
1652 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1654 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1655 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1657 CellLock<GridReadGuard> cell_lock(cell, p);
1658 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1659 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1660 }break;
1661 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1663 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1664 Cell cell(p);
1665 cell.data.Part.reserved = ALL_DISTRICT;
1666 cell.SetNoCreate();
1668 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1670 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1671 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1673 CellLock<GridReadGuard> cell_lock(cell, p);
1674 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1675 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1676 }break;
1677 // TARGET_SINGLE_PARTY means that the spells can only be casted on a party member and not on the caster (some seals, fire shield from imp, etc..)
1678 case TARGET_SINGLE_PARTY:
1680 Unit *target = m_targets.getUnitTarget();
1681 // Thoses spells apparently can't be casted on the caster.
1682 if( target && target != m_caster)
1684 // Can only be casted on group's members or its pets
1685 Group *pGroup = NULL;
1687 Unit* owner = m_caster->GetCharmerOrOwner();
1688 Unit *targetOwner = target->GetCharmerOrOwner();
1689 if(owner)
1691 if(owner->GetTypeId() == TYPEID_PLAYER)
1693 if( target == owner )
1695 TagUnitMap.push_back(target);
1696 break;
1698 pGroup = ((Player*)owner)->GetGroup();
1701 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1703 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1705 TagUnitMap.push_back(target);
1706 break;
1708 pGroup = ((Player*)m_caster)->GetGroup();
1711 if(pGroup)
1713 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1714 if(targetOwner)
1716 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1717 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1718 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1719 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1721 TagUnitMap.push_back(target);
1724 // 1Our target can be a player who is on our group
1725 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1727 TagUnitMap.push_back(target);
1731 }break;
1732 case TARGET_GAMEOBJECT:
1734 if(m_targets.getGOTarget())
1735 AddGOTarget(m_targets.getGOTarget(), i);
1736 }break;
1737 case TARGET_IN_FRONT_OF_CASTER:
1739 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1740 Cell cell(p);
1741 cell.data.Part.reserved = ALL_DISTRICT;
1742 cell.SetNoCreate();
1744 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1745 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1747 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1748 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1750 CellLock<GridReadGuard> cell_lock(cell, p);
1751 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1752 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1753 }break;
1754 case TARGET_DUELVSPLAYER:
1756 Unit *target = m_targets.getUnitTarget();
1757 if(target)
1759 if(m_caster->IsFriendlyTo(target))
1761 TagUnitMap.push_back(target);
1763 else
1765 Unit* pUnitTarget = SelectMagnetTarget();
1766 if(pUnitTarget)
1767 TagUnitMap.push_back(pUnitTarget);
1770 }break;
1771 case TARGET_GAMEOBJECT_ITEM:
1773 if(m_targets.getGOTargetGUID())
1774 AddGOTarget(m_targets.getGOTarget(), i);
1775 else if(m_targets.getItemTarget())
1776 AddItemTarget(m_targets.getItemTarget(), i);
1777 break;
1779 case TARGET_MASTER:
1781 if(Unit* owner = m_caster->GetCharmerOrOwner())
1782 TagUnitMap.push_back(owner);
1783 break;
1785 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1787 // targets the ground, not the units in the area
1788 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1790 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1791 Cell cell(p);
1792 cell.data.Part.reserved = ALL_DISTRICT;
1793 cell.SetNoCreate();
1795 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1797 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1798 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1800 CellLock<GridReadGuard> cell_lock(cell, p);
1801 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1802 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1804 }break;
1805 case TARGET_MINION:
1807 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1808 TagUnitMap.push_back(m_caster);
1809 }break;
1810 case TARGET_SINGLE_ENEMY:
1812 Unit* pUnitTarget = SelectMagnetTarget();
1813 if(pUnitTarget)
1814 TagUnitMap.push_back(pUnitTarget);
1815 }break;
1816 case TARGET_AREAEFFECT_PARTY:
1818 Unit* owner = m_caster->GetCharmerOrOwner();
1819 Player *pTarget = NULL;
1821 if(owner)
1823 TagUnitMap.push_back(m_caster);
1824 if(owner->GetTypeId() == TYPEID_PLAYER)
1825 pTarget = (Player*)owner;
1827 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1829 if(Unit* target = m_targets.getUnitTarget())
1831 if( target->GetTypeId() != TYPEID_PLAYER)
1833 if(((Creature*)target)->isPet())
1835 Unit *targetOwner = target->GetOwner();
1836 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1837 pTarget = (Player*)targetOwner;
1840 else
1841 pTarget = (Player*)target;
1845 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1847 if(pGroup)
1849 uint8 subgroup = pTarget->GetSubGroup();
1851 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1853 Player* Target = itr->getSource();
1855 // IsHostileTo check duel and controlled by enemy
1856 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1858 if( pTarget->IsWithinDistInMap(Target, radius) )
1859 TagUnitMap.push_back(Target);
1861 if(Pet* pet = Target->GetPet())
1862 if( pTarget->IsWithinDistInMap(pet, radius) )
1863 TagUnitMap.push_back(pet);
1867 else if (owner)
1869 if(m_caster->IsWithinDistInMap(owner, radius))
1870 TagUnitMap.push_back(owner);
1872 else if(pTarget)
1874 TagUnitMap.push_back(pTarget);
1876 if(Pet* pet = pTarget->GetPet())
1877 if( m_caster->IsWithinDistInMap(pet, radius) )
1878 TagUnitMap.push_back(pet);
1881 }break;
1882 case TARGET_SCRIPT:
1884 if(m_targets.getUnitTarget())
1885 TagUnitMap.push_back(m_targets.getUnitTarget());
1886 if(m_targets.getItemTarget())
1887 AddItemTarget(m_targets.getItemTarget(), i);
1888 }break;
1889 case TARGET_SELF_FISHING:
1891 TagUnitMap.push_back(m_caster);
1892 }break;
1893 case TARGET_CHAIN_HEAL:
1895 Unit* pUnitTarget = m_targets.getUnitTarget();
1896 if(!pUnitTarget)
1897 break;
1899 if (EffectChainTarget <= 1)
1900 TagUnitMap.push_back(pUnitTarget);
1901 else
1903 unMaxTargets = EffectChainTarget;
1904 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1906 std::list<Unit *> tempUnitMap;
1909 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1910 Cell cell(p);
1911 cell.data.Part.reserved = ALL_DISTRICT;
1912 cell.SetNoCreate();
1914 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1916 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1917 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1919 CellLock<GridReadGuard> cell_lock(cell, p);
1920 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1921 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1925 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1926 tempUnitMap.push_front(m_caster);
1928 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1930 if(tempUnitMap.empty())
1931 break;
1933 if(*tempUnitMap.begin() == pUnitTarget)
1934 tempUnitMap.erase(tempUnitMap.begin());
1936 TagUnitMap.push_back(pUnitTarget);
1937 uint32 t = unMaxTargets - 1;
1938 Unit *prev = pUnitTarget;
1939 std::list<Unit*>::iterator next = tempUnitMap.begin();
1941 while(t && next != tempUnitMap.end() )
1943 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1944 break;
1946 if(!prev->IsWithinLOSInMap(*next))
1948 ++next;
1949 continue;
1952 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1954 next = tempUnitMap.erase(next);
1955 continue;
1958 prev = *next;
1959 TagUnitMap.push_back(prev);
1960 tempUnitMap.erase(next);
1961 tempUnitMap.sort(TargetDistanceOrder(prev));
1962 next = tempUnitMap.begin();
1964 --t;
1967 }break;
1968 case TARGET_CURRENT_ENEMY_COORDINATES:
1970 Unit* currentTarget = m_targets.getUnitTarget();
1971 if(currentTarget)
1973 TagUnitMap.push_back(currentTarget);
1974 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1975 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1977 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1978 Cell cell(p);
1979 cell.data.Part.reserved = ALL_DISTRICT;
1980 cell.SetNoCreate();
1981 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1982 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1983 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1984 CellLock<GridReadGuard> cell_lock(cell, p);
1985 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1986 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1989 }break;
1990 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1992 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1993 ? (Player*)m_targets.getUnitTarget() : NULL;
1995 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1996 if(pGroup)
1998 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
2000 Player* Target = itr->getSource();
2002 // IsHostileTo check duel and controlled by enemy
2003 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
2004 targetPlayer->getClass() == Target->getClass() &&
2005 !m_caster->IsHostileTo(Target) )
2007 TagUnitMap.push_back(Target);
2011 else if(m_targets.getUnitTarget())
2012 TagUnitMap.push_back(m_targets.getUnitTarget());
2013 break;
2015 case TARGET_TABLE_X_Y_Z_COORDINATES:
2017 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
2018 if(st)
2020 if (st->target_mapId == m_caster->GetMapId())
2021 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
2023 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
2024 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
2026 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
2027 Cell cell(p);
2028 cell.data.Part.reserved = ALL_DISTRICT;
2029 cell.SetNoCreate();
2031 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
2032 // Select friendly targets for positive effect
2033 if (IsPositiveEffect(m_spellInfo->Id, i))
2034 targetB = SPELL_TARGETS_FRIENDLY;
2036 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
2038 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
2039 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
2041 CellLock<GridReadGuard> cell_lock(cell, p);
2042 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
2043 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
2046 else
2047 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
2048 }break;
2049 case TARGET_BEHIND_VICTIM:
2051 Unit *pTarget = m_caster->getVictim();
2052 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
2053 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
2055 if(pTarget)
2057 float _target_x, _target_y, _target_z;
2058 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
2059 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
2060 m_targets.setDestination(_target_x, _target_y, _target_z);
2062 }break;
2063 case TARGET_DYNAMIC_OBJECT_COORDINATES:
2065 // if parent spell create dynamic object extract area from it
2066 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
2067 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
2068 }break;
2069 default:
2070 break;
2073 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2075 // make sure one unit is always removed per iteration
2076 uint32 removed_utarget = 0;
2077 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2079 next = itr;
2080 ++next;
2081 if (!*itr) continue;
2082 if ((*itr) == m_targets.getUnitTarget())
2084 TagUnitMap.erase(itr);
2085 removed_utarget = 1;
2086 // break;
2089 // remove random units from the map
2090 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2092 uint32 poz = urand(0, TagUnitMap.size()-1);
2093 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2095 if (!*itr) continue;
2096 if (!poz)
2098 TagUnitMap.erase(itr);
2099 break;
2103 // the player's target will always be added to the map
2104 if (removed_utarget && m_targets.getUnitTarget())
2105 TagUnitMap.push_back(m_targets.getUnitTarget());
2109 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2111 m_targets = *targets;
2113 m_spellState = SPELL_STATE_PREPARING;
2115 m_castPositionX = m_caster->GetPositionX();
2116 m_castPositionY = m_caster->GetPositionY();
2117 m_castPositionZ = m_caster->GetPositionZ();
2118 m_castOrientation = m_caster->GetOrientation();
2120 if(triggeredByAura)
2121 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2123 // create and add update event for this spell
2124 SpellEvent* Event = new SpellEvent(this);
2125 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2127 //Prevent casting at cast another spell (ServerSide check)
2128 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2130 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2131 finish(false);
2132 return;
2135 // Fill cost data
2136 m_powerCost = CalculatePowerCost();
2138 uint8 result = CanCast(true);
2139 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2141 if(triggeredByAura)
2143 SendChannelUpdate(0);
2144 triggeredByAura->SetAuraDuration(0);
2146 SendCastResult(result);
2147 finish(false);
2148 return;
2151 // Prepare data for triggers
2152 prepareDataForTriggerSystem();
2154 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2155 m_casttime = GetSpellCastTime(m_spellInfo, this);
2157 // set timer base at cast time
2158 ReSetTimer();
2160 // stealth must be removed at cast starting (at show channel bar)
2161 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2162 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2164 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2165 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2168 if(m_IsTriggeredSpell)
2169 cast(true);
2170 else
2172 m_caster->SetCurrentCastedSpell( this );
2173 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2174 SendSpellStart();
2178 void Spell::cancel()
2180 if(m_spellState == SPELL_STATE_FINISHED)
2181 return;
2183 m_autoRepeat = false;
2184 switch (m_spellState)
2186 case SPELL_STATE_PREPARING:
2187 case SPELL_STATE_DELAYED:
2189 SendInterrupted(0);
2190 SendCastResult(SPELL_FAILED_INTERRUPTED);
2191 } break;
2193 case SPELL_STATE_CASTING:
2195 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2197 if( ihit->missCondition == SPELL_MISS_NONE )
2199 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2200 if( unit && unit->isAlive() )
2201 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2205 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2206 SendChannelUpdate(0);
2207 SendInterrupted(0);
2208 SendCastResult(SPELL_FAILED_INTERRUPTED);
2209 } break;
2211 default:
2213 } break;
2216 finish(false);
2217 m_caster->RemoveDynObject(m_spellInfo->Id);
2218 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2221 void Spell::cast(bool skipCheck)
2223 SetExecutedCurrently(true);
2225 uint8 castResult = 0;
2227 // update pointers base at GUIDs to prevent access to non-existed already object
2228 UpdatePointers();
2230 // cancel at lost main target unit
2231 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2233 cancel();
2234 SetExecutedCurrently(false);
2235 return;
2238 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2239 m_caster->SetInFront(m_targets.getUnitTarget());
2241 castResult = CheckPower();
2242 if(castResult != 0)
2244 SendCastResult(castResult);
2245 finish(false);
2246 SetExecutedCurrently(false);
2247 return;
2250 // triggered cast called from Spell::prepare where it was already checked
2251 if(!skipCheck)
2253 castResult = CanCast(false);
2254 if(castResult != 0)
2256 SendCastResult(castResult);
2257 finish(false);
2258 SetExecutedCurrently(false);
2259 return;
2263 switch(m_spellInfo->SpellFamilyName)
2265 case SPELLFAMILY_GENERIC:
2267 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2268 m_preCastSpell = 11196; // Recently Bandaged
2269 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2270 m_preCastSpell = 23230; // Blood Fury - Healing Reduction
2271 break;
2273 case SPELLFAMILY_MAGE:
2275 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2276 m_preCastSpell = 41425; // Hypothermia
2277 break;
2279 case SPELLFAMILY_PRIEST:
2281 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2282 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2283 m_preCastSpell = 6788; // Weakened Soul
2284 if (m_spellInfo->Id == 47585) // Dispersion (transform)
2285 m_preCastSpell = 60069; // Dispersion (mana regen)
2286 break;
2288 case SPELLFAMILY_PALADIN:
2290 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2291 m_preCastSpell = 25771; // Forbearance
2292 break;
2294 case SPELLFAMILY_SHAMAN:
2296 if (m_spellInfo->Id == 2825) // Bloodlust
2297 m_preCastSpell = 57724; // Sated
2298 else if (m_spellInfo->Id == 32182) // Heroism
2299 m_preCastSpell = 57723; // Exhaustion
2300 break;
2302 default:
2303 break;
2306 // Conflagrate - consumes immolate
2307 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2309 // for caster applied auras only
2310 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2311 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2313 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2314 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2316 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2317 break;
2322 // traded items have trade slot instead of guid in m_itemTargetGUID
2323 // set to real guid to be sent later to the client
2324 m_targets.updateTradeSlotItem();
2326 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2328 if (m_CastItem)
2329 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2331 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2334 // CAST SPELL
2335 SendSpellCooldown();
2337 TakePower();
2338 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2339 FillTargetMap();
2341 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2343 SetExecutedCurrently(false);
2344 return;
2347 SendCastResult(castResult);
2348 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2350 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2351 if (m_spellInfo->speed > 0.0f)
2354 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2355 // in case delayed spell remove item at cast delay start
2356 TakeCastItem();
2358 // Okay, maps created, now prepare flags
2359 m_immediateHandled = false;
2360 m_spellState = SPELL_STATE_DELAYED;
2361 SetDelayStart(0);
2363 else
2365 // Immediate spell, no big deal
2366 handle_immediate();
2369 SetExecutedCurrently(false);
2372 void Spell::handle_immediate()
2374 // start channeling if applicable
2375 if(IsChanneledSpell(m_spellInfo))
2377 int32 duration = GetSpellDuration(m_spellInfo);
2378 if (duration)
2380 // Apply duration mod
2381 if(Player* modOwner = m_caster->GetSpellModOwner())
2382 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
2383 m_spellState = SPELL_STATE_CASTING;
2384 SendChannelStart(duration);
2388 // process immediate effects (items, ground, etc.) also initialize some variables
2389 _handle_immediate_phase();
2391 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2392 DoAllEffectOnTarget(&(*ihit));
2394 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2395 DoAllEffectOnTarget(&(*ihit));
2397 // spell is finished, perform some last features of the spell here
2398 _handle_finish_phase();
2400 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2401 TakeCastItem();
2403 if(m_spellState != SPELL_STATE_CASTING)
2404 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2407 uint64 Spell::handle_delayed(uint64 t_offset)
2409 uint64 next_time = 0;
2411 if (!m_immediateHandled)
2413 _handle_immediate_phase();
2414 m_immediateHandled = true;
2417 // 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)
2418 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2420 if (ihit->processed == false)
2422 if ( ihit->timeDelay <= t_offset )
2423 DoAllEffectOnTarget(&(*ihit));
2424 else if( next_time == 0 || ihit->timeDelay < next_time )
2425 next_time = ihit->timeDelay;
2429 // now recheck gameobject targeting correctness
2430 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2432 if (ighit->processed == false)
2434 if ( ighit->timeDelay <= t_offset )
2435 DoAllEffectOnTarget(&(*ighit));
2436 else if( next_time == 0 || ighit->timeDelay < next_time )
2437 next_time = ighit->timeDelay;
2440 // All targets passed - need finish phase
2441 if (next_time == 0)
2443 // spell is finished, perform some last features of the spell here
2444 _handle_finish_phase();
2446 finish(true); // successfully finish spell cast
2448 // return zero, spell is finished now
2449 return 0;
2451 else
2453 // spell is unfinished, return next execution time
2454 return next_time;
2458 void Spell::_handle_immediate_phase()
2460 // handle some immediate features of the spell here
2461 HandleThreatSpells(m_spellInfo->Id);
2463 m_needSpellLog = IsNeedSendToClient();
2464 for(uint32 j = 0;j<3;j++)
2466 if(m_spellInfo->Effect[j]==0)
2467 continue;
2469 // apply Send Event effect to ground in case empty target lists
2470 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2472 HandleEffects(NULL,NULL,NULL, j);
2473 continue;
2476 // Don't do spell log, if is school damage spell
2477 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2478 m_needSpellLog = false;
2480 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2481 if(m_originalCaster)
2482 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2483 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2485 // initialize multipliers
2486 m_damageMultipliers[j] = 1.0f;
2487 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2488 (EffectChainTarget > 1) )
2489 m_applyMultiplierMask |= 1 << j;
2492 // initialize Diminishing Returns Data
2493 m_diminishLevel = DIMINISHING_LEVEL_1;
2494 m_diminishGroup = DIMINISHING_NONE;
2496 // process items
2497 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2498 DoAllEffectOnTarget(&(*ihit));
2500 // process ground
2501 for(uint32 j = 0;j<3;j++)
2503 // persistent area auras target only the ground
2504 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2505 HandleEffects(NULL,NULL,NULL, j);
2509 void Spell::_handle_finish_phase()
2511 // spell log
2512 if(m_needSpellLog)
2513 SendLogExecute();
2516 void Spell::SendSpellCooldown()
2518 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2519 return;
2521 Player* _player = (Player*)m_caster;
2522 // Add cooldown for max (disable spell)
2523 // Cooldown started on SendCooldownEvent call
2524 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2526 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2527 return;
2530 // init cooldown values
2531 uint32 cat = 0;
2532 int32 rec = -1;
2533 int32 catrec = -1;
2535 // some special item spells without correct cooldown in SpellInfo
2536 // cooldown information stored in item prototype
2537 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2539 if(m_CastItem)
2541 ItemPrototype const* proto = m_CastItem->GetProto();
2542 if(proto)
2544 for(int idx = 0; idx < 5; ++idx)
2546 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2548 cat = proto->Spells[idx].SpellCategory;
2549 rec = proto->Spells[idx].SpellCooldown;
2550 catrec = proto->Spells[idx].SpellCategoryCooldown;
2551 break;
2557 // if no cooldown found above then base at DBC data
2558 if(rec < 0 && catrec < 0)
2560 cat = m_spellInfo->Category;
2561 rec = m_spellInfo->RecoveryTime;
2562 catrec = m_spellInfo->CategoryRecoveryTime;
2565 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2566 // prevent 0 cooldowns set by another way
2567 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT))
2568 rec = _player->GetAttackTime(RANGED_ATTACK);
2570 // Now we have cooldown data (if found any), time to apply mods
2571 if(rec > 0)
2572 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2574 if(catrec > 0)
2575 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2577 // replace negative cooldowns by 0
2578 if (rec < 0) rec = 0;
2579 if (catrec < 0) catrec = 0;
2581 // no cooldown after applying spell mods
2582 if( rec == 0 && catrec == 0)
2583 return;
2585 time_t curTime = time(NULL);
2587 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2588 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2590 // self spell cooldown
2591 if(recTime > 0)
2592 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2594 // category spells
2595 if (catrec > 0)
2597 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2598 if(i_scstore != sSpellCategoryStore.end())
2600 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2602 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2603 continue;
2605 _player->AddSpellCooldown(*i_scset, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2611 void Spell::update(uint32 difftime)
2613 // update pointers based at it's GUIDs
2614 UpdatePointers();
2616 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2618 cancel();
2619 return;
2622 // check if the player caster has moved before the spell finished
2623 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2624 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2625 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2627 // always cancel for channeled spells
2628 if( m_spellState == SPELL_STATE_CASTING )
2629 cancel();
2630 // don't cancel for melee, autorepeat, triggered and instant spells
2631 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2632 cancel();
2635 switch(m_spellState)
2637 case SPELL_STATE_PREPARING:
2639 if(m_timer)
2641 if(difftime >= m_timer)
2642 m_timer = 0;
2643 else
2644 m_timer -= difftime;
2647 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2648 cast();
2649 } break;
2650 case SPELL_STATE_CASTING:
2652 if(m_timer > 0)
2654 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2656 // check if player has jumped before the channeling finished
2657 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2658 cancel();
2660 // check for incapacitating player states
2661 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2662 cancel();
2664 // check if player has turned if flag is set
2665 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2666 cancel();
2669 // check if there are alive targets left
2670 if (!IsAliveUnitPresentInTargetList())
2672 SendChannelUpdate(0);
2673 finish();
2676 if(difftime >= m_timer)
2677 m_timer = 0;
2678 else
2679 m_timer -= difftime;
2682 if(m_timer == 0)
2684 SendChannelUpdate(0);
2686 // channeled spell processed independently for quest targeting
2687 // cast at creature (or GO) quest objectives update at successful cast channel finished
2688 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2689 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2691 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2693 TargetInfo* target = &*ihit;
2694 if(!IS_CREATURE_GUID(target->targetGUID))
2695 continue;
2697 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2698 if (unit==NULL)
2699 continue;
2701 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2704 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2706 GOTargetInfo* target = &*ihit;
2708 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2709 if(!go)
2710 continue;
2712 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2716 finish();
2718 } break;
2719 default:
2721 }break;
2725 void Spell::finish(bool ok)
2727 if(!m_caster)
2728 return;
2730 if(m_spellState == SPELL_STATE_FINISHED)
2731 return;
2733 m_spellState = SPELL_STATE_FINISHED;
2735 // other code related only to successfully finished spells
2736 if(!ok)
2737 return;
2739 //remove spell mods
2740 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2741 ((Player*)m_caster)->RemoveSpellMods(this);
2743 // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2744 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2745 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2747 if (!(*i)->isAffectedOnSpell(m_spellInfo))
2748 continue;
2749 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2750 if( ihit->missCondition == SPELL_MISS_NONE )
2752 // check m_caster->GetGUID() let load auras at login and speedup most often case
2753 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2754 if (unit && unit->isAlive())
2756 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2757 uint32 auraSpellIdx = (*i)->GetEffIndex();
2758 // Calculate chance at that moment (can be depend for example from combo points)
2759 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2760 if(roll_chance_i(chance))
2761 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2766 // Heal caster for all health leech from all targets
2767 if (m_healthLeech)
2769 m_caster->ModifyHealth(m_healthLeech);
2770 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2773 if (IsMeleeAttackResetSpell())
2775 m_caster->resetAttackTimer(BASE_ATTACK);
2776 if(m_caster->haveOffhandWeapon())
2777 m_caster->resetAttackTimer(OFF_ATTACK);
2780 /*if (IsRangedAttackResetSpell())
2781 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2783 // Clear combo at finish state
2784 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2786 // Not drop combopoints if negative spell and if any miss on enemy exist
2787 bool needDrop = true;
2788 if (!IsPositiveSpell(m_spellInfo->Id))
2789 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2790 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2792 needDrop = false;
2793 break;
2795 if (needDrop)
2796 ((Player*)m_caster)->ClearComboPoints();
2799 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2800 if(!m_TriggerSpells.empty())
2801 TriggerSpell();
2803 // Stop Attack for some spells
2804 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2805 m_caster->AttackStop();
2808 void Spell::SendCastResult(uint8 result)
2810 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2811 return;
2813 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2814 return;
2816 if(result != 0)
2818 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2819 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2820 data << uint32(m_spellInfo->Id);
2821 data << uint8(result); // problem
2822 switch (result)
2824 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2825 data << uint32(m_spellInfo->RequiresSpellFocus);
2826 break;
2827 case SPELL_FAILED_REQUIRES_AREA:
2828 // hardcode areas limitation case
2829 switch(m_spellInfo->Id)
2831 case 41617: // Cenarion Mana Salve
2832 case 41619: // Cenarion Healing Salve
2833 data << uint32(3905);
2834 break;
2835 case 41618: // Bottled Nethergon Energy
2836 case 41620: // Bottled Nethergon Vapor
2837 data << uint32(3842);
2838 break;
2839 case 45373: // Bloodberry Elixir
2840 data << uint32(4075);
2841 break;
2842 default: // default case (don't must be)
2843 data << uint32(0);
2844 break;
2846 break;
2847 case SPELL_FAILED_TOTEMS:
2848 if(m_spellInfo->Totem[0])
2849 data << uint32(m_spellInfo->Totem[0]);
2850 if(m_spellInfo->Totem[1])
2851 data << uint32(m_spellInfo->Totem[1]);
2852 break;
2853 case SPELL_FAILED_TOTEM_CATEGORY:
2854 if(m_spellInfo->TotemCategory[0])
2855 data << uint32(m_spellInfo->TotemCategory[0]);
2856 if(m_spellInfo->TotemCategory[1])
2857 data << uint32(m_spellInfo->TotemCategory[1]);
2858 break;
2859 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2860 data << uint32(m_spellInfo->EquippedItemClass);
2861 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2862 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2863 break;
2865 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2869 void Spell::SendSpellStart()
2871 if(!IsNeedSendToClient())
2872 return;
2874 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2876 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2877 if(IsRangedSpell())
2878 castFlags |= CAST_FLAG_AMMO;
2880 if(m_spellInfo->runeCostID)
2881 castFlags |= CAST_FLAG_UNKNOWN10;
2883 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2885 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2886 if(m_CastItem)
2887 data.append(m_CastItem->GetPackGUID());
2888 else
2889 data.append(m_caster->GetPackGUID());
2891 data.append(m_caster->GetPackGUID());
2892 data << uint8(m_cast_count); // pending spell cast?
2893 data << uint32(m_spellInfo->Id); // spellId
2894 data << uint32(castFlags); // cast flags
2895 data << uint32(m_timer); // delay?
2897 m_targets.write(&data);
2899 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2900 data << uint32(0);
2902 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2904 uint8 v1 = 0;//m_runesState;
2905 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2906 data << uint8(v1); // runes state before
2907 data << uint8(v2); // runes state after
2908 for(uint8 i = 0; i < MAX_RUNES; ++i)
2910 uint8 m = (1 << i);
2911 if(m & v1) // usable before...
2912 if(!(m & v2)) // ...but on cooldown now...
2913 data << uint8(0); // some unknown byte (time?)
2917 if ( castFlags & CAST_FLAG_AMMO )
2918 WriteAmmoToPacket(&data);
2920 m_caster->SendMessageToSet(&data, true);
2923 void Spell::SendSpellGo()
2925 // not send invisible spell casting
2926 if(!IsNeedSendToClient())
2927 return;
2929 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2931 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2933 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2934 if(IsRangedSpell())
2935 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2937 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2939 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2940 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2941 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2944 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2946 if(m_CastItem)
2947 data.append(m_CastItem->GetPackGUID());
2948 else
2949 data.append(m_caster->GetPackGUID());
2951 data.append(m_caster->GetPackGUID());
2952 data << uint8(m_cast_count); // pending spell cast?
2953 data << uint32(m_spellInfo->Id); // spellId
2954 data << uint32(castFlags); // cast flags
2955 data << uint32(getMSTime()); // timestamp
2957 WriteSpellGoTargets(&data);
2959 m_targets.write(&data);
2961 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2962 data << uint32(0);
2964 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2966 uint8 v1 = m_runesState;
2967 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2968 data << uint8(v1); // runes state before
2969 data << uint8(v2); // runes state after
2970 for(uint8 i = 0; i < MAX_RUNES; ++i)
2972 uint8 m = (1 << i);
2973 if(m & v1) // usable before...
2974 if(!(m & v2)) // ...but on cooldown now...
2975 data << uint8(0); // some unknown byte (time?)
2979 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2981 data << float(0);
2982 data << uint32(0);
2985 if ( castFlags & CAST_FLAG_AMMO )
2986 WriteAmmoToPacket(&data);
2988 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2990 data << uint32(0);
2991 data << uint32(0);
2994 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2996 data << uint8(0);
2999 m_caster->SendMessageToSet(&data, true);
3002 void Spell::WriteAmmoToPacket( WorldPacket * data )
3004 uint32 ammoInventoryType = 0;
3005 uint32 ammoDisplayID = 0;
3007 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3009 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
3010 if(pItem)
3012 ammoInventoryType = pItem->GetProto()->InventoryType;
3013 if( ammoInventoryType == INVTYPE_THROWN )
3014 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
3015 else
3017 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
3018 if(ammoID)
3020 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
3021 if(pProto)
3023 ammoDisplayID = pProto->DisplayInfoID;
3024 ammoInventoryType = pProto->InventoryType;
3027 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
3029 ammoDisplayID = 5996; // normal arrow
3030 ammoInventoryType = INVTYPE_AMMO;
3035 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
3037 *data << uint32(ammoDisplayID);
3038 *data << uint32(ammoInventoryType);
3041 void Spell::WriteSpellGoTargets( WorldPacket * data )
3043 // This function also fill data for channeled spells:
3044 // m_needAliveTargetMask req for stop channelig if one target die
3045 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
3046 uint32 miss = 0;
3047 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3049 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
3051 // possibly SPELL_MISS_IMMUNE2 for this??
3052 ihit->missCondition = SPELL_MISS_IMMUNE2;
3053 miss++;
3055 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3056 hit++;
3057 else
3058 miss++;
3061 *data << (uint8)hit;
3062 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3063 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3065 *data << uint64(ihit->targetGUID);
3066 m_needAliveTargetMask |=ihit->effectMask;
3069 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3070 *data << uint64(ighit->targetGUID); // Always hits
3072 *data << (uint8)miss;
3073 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3075 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3077 *data << uint64(ihit->targetGUID);
3078 *data << uint8(ihit->missCondition);
3079 if( ihit->missCondition == SPELL_MISS_REFLECT )
3080 *data << uint8(ihit->reflectResult);
3083 // Reset m_needAliveTargetMask for non channeled spell
3084 if(!IsChanneledSpell(m_spellInfo))
3085 m_needAliveTargetMask = 0;
3088 void Spell::SendLogExecute()
3090 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3092 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3094 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3095 data.append(m_caster->GetPackGUID());
3096 else
3097 data.append(target->GetPackGUID());
3099 data << uint32(m_spellInfo->Id);
3100 uint32 count1 = 1;
3101 data << uint32(count1); // count1 (effect count?)
3102 for(uint32 i = 0; i < count1; ++i)
3104 data << uint32(m_spellInfo->Effect[0]); // spell effect
3105 uint32 count2 = 1;
3106 data << uint32(count2); // count2 (target count?)
3107 for(uint32 j = 0; j < count2; ++j)
3109 switch(m_spellInfo->Effect[0])
3111 case SPELL_EFFECT_POWER_DRAIN:
3112 if(Unit *unit = m_targets.getUnitTarget())
3113 data.append(unit->GetPackGUID());
3114 else
3115 data << uint8(0);
3116 data << uint32(0);
3117 data << uint32(0);
3118 data << float(0);
3119 break;
3120 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3121 if(Unit *unit = m_targets.getUnitTarget())
3122 data.append(unit->GetPackGUID());
3123 else
3124 data << uint8(0);
3125 data << uint32(0); // count?
3126 break;
3127 case SPELL_EFFECT_INTERRUPT_CAST:
3128 if(Unit *unit = m_targets.getUnitTarget())
3129 data.append(unit->GetPackGUID());
3130 else
3131 data << uint8(0);
3132 data << uint32(0); // spellid
3133 break;
3134 case SPELL_EFFECT_DURABILITY_DAMAGE:
3135 if(Unit *unit = m_targets.getUnitTarget())
3136 data.append(unit->GetPackGUID());
3137 else
3138 data << uint8(0);
3139 data << uint32(0);
3140 data << uint32(0);
3141 break;
3142 case SPELL_EFFECT_OPEN_LOCK:
3143 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3144 if(Item *item = m_targets.getItemTarget())
3145 data.append(item->GetPackGUID());
3146 else
3147 data << uint8(0);
3148 break;
3149 case SPELL_EFFECT_CREATE_ITEM:
3150 case SPELL_EFFECT_CREATE_ITEM_2:
3151 data << uint32(m_spellInfo->EffectItemType[0]);
3152 break;
3153 case SPELL_EFFECT_SUMMON:
3154 case SPELL_EFFECT_TRANS_DOOR:
3155 case SPELL_EFFECT_SUMMON_PET:
3156 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3157 case SPELL_EFFECT_CREATE_HOUSE:
3158 case SPELL_EFFECT_DUEL:
3159 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3160 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3161 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3162 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3163 if(Unit *unit = m_targets.getUnitTarget())
3164 data.append(unit->GetPackGUID());
3165 else if(m_targets.getItemTargetGUID())
3166 data.appendPackGUID(m_targets.getItemTargetGUID());
3167 else if(GameObject *go = m_targets.getGOTarget())
3168 data.append(go->GetPackGUID());
3169 else
3170 data << uint8(0); // guid
3171 break;
3172 case SPELL_EFFECT_FEED_PET:
3173 data << uint32(m_targets.getItemTargetEntry());
3174 break;
3175 case SPELL_EFFECT_DISMISS_PET:
3176 if(Unit *unit = m_targets.getUnitTarget())
3177 data.append(unit->GetPackGUID());
3178 else
3179 data << uint8(0);
3180 break;
3181 case SPELL_EFFECT_RESURRECT:
3182 case SPELL_EFFECT_RESURRECT_NEW:
3183 if(Unit *unit = m_targets.getUnitTarget())
3184 data.append(unit->GetPackGUID());
3185 else
3186 data << uint8(0);
3187 break;
3188 default:
3189 return;
3194 m_caster->SendMessageToSet(&data, true);
3197 void Spell::SendInterrupted(uint8 result)
3199 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3200 data.append(m_caster->GetPackGUID());
3201 data << uint8(m_cast_count);
3202 data << uint32(m_spellInfo->Id);
3203 data << uint8(result);
3204 m_caster->SendMessageToSet(&data, true);
3206 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3207 data.append(m_caster->GetPackGUID());
3208 data << uint8(m_cast_count);
3209 data << uint32(m_spellInfo->Id);
3210 data << uint8(result);
3211 m_caster->SendMessageToSet(&data, true);
3214 void Spell::SendChannelUpdate(uint32 time)
3216 if(time == 0)
3218 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3219 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3222 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3223 return;
3225 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3226 data.append(m_caster->GetPackGUID());
3227 data << uint32(time);
3229 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3232 void Spell::SendChannelStart(uint32 duration)
3234 WorldObject* target = NULL;
3236 // select first not resisted target from target list for _0_ effect
3237 if(!m_UniqueTargetInfo.empty())
3239 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3241 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3243 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3244 break;
3248 else if(!m_UniqueGOTargetInfo.empty())
3250 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3252 if(itr->effectMask & (1<<0) )
3254 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3255 break;
3260 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3262 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3263 data.append(m_caster->GetPackGUID());
3264 data << uint32(m_spellInfo->Id);
3265 data << uint32(duration);
3267 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3270 m_timer = duration;
3271 if(target)
3272 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3273 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3276 void Spell::SendResurrectRequest(Player* target)
3278 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3279 // However, the packet structure differs slightly
3281 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3283 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3284 data << uint64(m_caster->GetGUID());
3285 data << uint32(strlen(sentName)+1);
3287 data << sentName;
3288 data << uint8(0);
3290 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3291 target->GetSession()->SendPacket(&data);
3294 void Spell::SendPlaySpellVisual(uint32 SpellID)
3296 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3297 return;
3299 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3300 data << uint64(m_caster->GetGUID());
3301 data << uint32(SpellID); // spell visual id?
3302 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3305 void Spell::TakeCastItem()
3307 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3308 return;
3310 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3311 if(m_IsTriggeredSpell)
3312 return;
3314 ItemPrototype const *proto = m_CastItem->GetProto();
3316 if(!proto)
3318 // This code is to avoid a crash
3319 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3320 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3321 return;
3324 bool expendable = false;
3325 bool withoutCharges = false;
3327 for (int i = 0; i<5; i++)
3329 if (proto->Spells[i].SpellId)
3331 // item has limited charges
3332 if (proto->Spells[i].SpellCharges)
3334 if (proto->Spells[i].SpellCharges < 0)
3335 expendable = true;
3337 int32 charges = m_CastItem->GetSpellCharges(i);
3339 // item has charges left
3340 if (charges)
3342 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3343 if (proto->Stackable == 1)
3344 m_CastItem->SetSpellCharges(i, charges);
3345 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3348 // all charges used
3349 withoutCharges = (charges == 0);
3354 if (expendable && withoutCharges)
3356 uint32 count = 1;
3357 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3359 // prevent crash at access to deleted m_targets.getItemTarget
3360 if(m_CastItem==m_targets.getItemTarget())
3361 m_targets.setItemTarget(NULL);
3363 m_CastItem = NULL;
3367 void Spell::TakePower()
3369 if(m_CastItem || m_triggeredByAuraSpell)
3370 return;
3372 // health as power used
3373 if(m_spellInfo->powerType == POWER_HEALTH)
3375 m_caster->ModifyHealth( -(int32)m_powerCost );
3376 return;
3379 if(m_spellInfo->powerType >= MAX_POWERS)
3381 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3382 return;
3385 Powers powerType = Powers(m_spellInfo->powerType);
3387 if(powerType == POWER_RUNE)
3389 TakeRunePower();
3390 return;
3393 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3395 // Set the five second timer
3396 if (powerType == POWER_MANA && m_powerCost > 0)
3397 m_caster->SetLastManaUse(getMSTime());
3400 uint8 Spell::CheckRuneCost(uint32 runeCostID)
3402 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3403 return 0;
3405 Player *plr = (Player*)m_caster;
3407 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3408 return 0;
3410 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3412 if(!src)
3413 return 0;
3415 if(src->NoRuneCost())
3416 return 0;
3418 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3420 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3422 runeCost[i] = src->RuneCost[i];
3425 runeCost[RUNE_DEATH] = 0; // calculated later
3427 for(uint32 i = 0; i < MAX_RUNES; ++i)
3429 uint8 rune = plr->GetCurrentRune(i);
3430 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3432 runeCost[rune]--;
3436 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3438 if(runeCost[i] > 0)
3440 runeCost[RUNE_DEATH] += runeCost[i];
3444 if(runeCost[RUNE_DEATH] > 0)
3445 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3447 return 0;
3450 void Spell::TakeRunePower()
3452 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3453 return;
3455 Player *plr = (Player*)m_caster;
3457 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3458 return;
3460 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3462 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3463 return;
3465 m_runesState = plr->GetRunesState(); // store previous state
3467 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3469 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3471 runeCost[i] = src->RuneCost[i];
3474 runeCost[RUNE_DEATH] = 0; // calculated later
3476 for(uint32 i = 0; i < MAX_RUNES; ++i)
3478 uint8 rune = plr->GetCurrentRune(i);
3479 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3481 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3482 runeCost[rune]--;
3486 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3488 if(runeCost[RUNE_DEATH] > 0)
3490 for(uint32 i = 0; i < MAX_RUNES; ++i)
3492 uint8 rune = plr->GetCurrentRune(i);
3493 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3495 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3496 runeCost[rune]--;
3497 plr->ConvertRune(i, plr->GetBaseRune(i));
3498 if(runeCost[RUNE_DEATH] == 0)
3499 break;
3504 // you can gain some runic power when use runes
3505 float rp = src->runePowerGain;;
3506 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3507 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3510 void Spell::TakeReagents()
3512 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3513 return;
3515 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3516 return;
3518 Player* p_caster = (Player*)m_caster;
3519 if (p_caster->CanNoReagentCast(m_spellInfo))
3520 return;
3522 for(uint32 x=0;x<8;x++)
3524 if(m_spellInfo->Reagent[x] <= 0)
3525 continue;
3527 uint32 itemid = m_spellInfo->Reagent[x];
3528 uint32 itemcount = m_spellInfo->ReagentCount[x];
3530 // if CastItem is also spell reagent
3531 if (m_CastItem)
3533 ItemPrototype const *proto = m_CastItem->GetProto();
3534 if( proto && proto->ItemId == itemid )
3536 for(int s=0;s<5;s++)
3538 // CastItem will be used up and does not count as reagent
3539 int32 charges = m_CastItem->GetSpellCharges(s);
3540 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3542 ++itemcount;
3543 break;
3547 m_CastItem = NULL;
3551 // if getItemTarget is also spell reagent
3552 if (m_targets.getItemTargetEntry()==itemid)
3553 m_targets.setItemTarget(NULL);
3555 p_caster->DestroyItemCount(itemid, itemcount, true);
3559 void Spell::HandleThreatSpells(uint32 spellId)
3561 if(!m_targets.getUnitTarget() || !spellId)
3562 return;
3564 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3565 return;
3567 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3568 if(!threatSpell)
3569 return;
3571 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3573 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3576 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3578 unitTarget = pUnitTarget;
3579 itemTarget = pItemTarget;
3580 gameObjTarget = pGOTarget;
3582 uint8 eff = m_spellInfo->Effect[i];
3584 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3586 sLog.outDebug( "Spell: Effect : %u", eff);
3588 if(eff<TOTAL_SPELL_EFFECTS)
3590 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3591 (*this.*SpellEffects[eff])(i);
3594 else
3596 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3597 if (m_CastItem)
3598 EffectEnchantItemTmp(i);
3599 else
3601 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3602 eff, m_spellInfo->Id);
3608 void Spell::TriggerSpell()
3610 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3612 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3613 spell->prepare(&m_targets); // use original spell original targets
3617 uint8 Spell::CanCast(bool strict)
3619 // check cooldowns to prevent cheating
3620 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3622 if(m_triggeredByAuraSpell)
3623 return SPELL_FAILED_DONT_REPORT;
3624 else
3625 return SPELL_FAILED_NOT_READY;
3628 // only allow triggered spells if at an ended battleground
3629 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3630 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3631 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3632 return SPELL_FAILED_DONT_REPORT;
3634 // only check at first call, Stealth auras are already removed at second call
3635 // for now, ignore triggered spells
3636 if( strict && !m_IsTriggeredSpell)
3638 bool checkForm = true;
3639 // Ignore form req aura
3640 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3641 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3643 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3644 continue;
3645 checkForm = false;
3646 break;
3648 if (checkForm)
3650 // Cannot be used in this stance/form
3651 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3652 return shapeError;
3654 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3655 return SPELL_FAILED_ONLY_STEALTHED;
3659 // caster state requirements
3660 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3661 return SPELL_FAILED_CASTER_AURASTATE;
3662 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3663 return SPELL_FAILED_CASTER_AURASTATE;
3665 // Caster aura req check if need
3666 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3667 return SPELL_FAILED_CASTER_AURASTATE;
3668 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3669 return SPELL_FAILED_CASTER_AURASTATE;
3671 // cancel autorepeat spells if cast start when moving
3672 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3673 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3675 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3676 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3677 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3678 return SPELL_FAILED_MOVING;
3681 Unit *target = m_targets.getUnitTarget();
3683 if(target)
3685 // target state requirements (not allowed state), apply to self also
3686 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3687 return SPELL_FAILED_TARGET_AURASTATE;
3689 // Target aura req check if need
3690 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3691 return SPELL_FAILED_CASTER_AURASTATE;
3692 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3693 return SPELL_FAILED_CASTER_AURASTATE;
3695 if(target != m_caster)
3697 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3698 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3699 return SPELL_FAILED_TARGET_AURASTATE;
3701 // Not allow casting on flying player
3702 if (target->isInFlight())
3703 return SPELL_FAILED_BAD_TARGETS;
3705 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3706 return SPELL_FAILED_LINE_OF_SIGHT;
3708 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3709 // this case can be triggered if rank not found (too low-level target for first rank)
3710 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3712 for(int i=0;i<3;i++)
3714 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3715 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3716 return SPELL_FAILED_LOWLEVEL;
3720 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3722 // Additional check for some spells
3723 // If 0 spell effect empty - client not send target data (need use selection)
3724 // TODO: check it on next client version
3725 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3726 m_spellInfo->Effect[0] == 0 && m_spellInfo->EffectImplicitTargetA[1] != TARGET_SELF)
3728 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3729 m_targets.setUnitTarget(target);
3730 else
3731 return SPELL_FAILED_BAD_TARGETS;
3735 // check pet presents
3736 for(int j=0;j<3;j++)
3738 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3740 target = m_caster->GetPet();
3741 if(!target)
3743 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3744 return SPELL_FAILED_DONT_REPORT;
3745 else
3746 return SPELL_FAILED_NO_PET;
3748 break;
3752 //check creature type
3753 //ignore self casts (including area casts when caster selected as target)
3754 if(target != m_caster)
3756 if(!CheckTargetCreatureType(target))
3758 if(target->GetTypeId()==TYPEID_PLAYER)
3759 return SPELL_FAILED_TARGET_IS_PLAYER;
3760 else
3761 return SPELL_FAILED_BAD_TARGETS;
3765 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3766 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3767 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3769 // check correctness positive/negative cast target (pet cast real check and cheating check)
3770 if(IsPositiveSpell(m_spellInfo->Id))
3772 if(m_caster->IsHostileTo(target))
3773 return SPELL_FAILED_BAD_TARGETS;
3775 else
3777 if(m_caster->IsFriendlyTo(target))
3778 return SPELL_FAILED_BAD_TARGETS;
3782 if(IsPositiveSpell(m_spellInfo->Id))
3784 if(target->IsImmunedToSpell(m_spellInfo))
3785 return SPELL_FAILED_TARGET_AURASTATE;
3788 //Must be behind the target.
3789 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3791 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3792 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3794 SendInterrupted(2);
3795 return SPELL_FAILED_NOT_BEHIND;
3799 //Target must be facing you.
3800 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3802 SendInterrupted(2);
3803 return SPELL_FAILED_NOT_INFRONT;
3806 // check if target is in combat
3807 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3809 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3812 // Spell casted only on battleground
3813 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3814 if(!((Player*)m_caster)->InBattleGround())
3815 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3817 // do not allow spells to be cast in arenas
3818 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3819 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3820 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3821 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3822 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3823 if(mapEntry->IsBattleArena())
3824 return SPELL_FAILED_NOT_IN_ARENA;
3826 // zone check
3827 if(uint8 res= GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3828 return res;
3830 // not let players cast spells at mount (and let do it to creatures)
3831 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3832 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3834 if(m_caster->isInFlight())
3835 return SPELL_FAILED_NOT_FLYING;
3836 else
3837 return SPELL_FAILED_NOT_MOUNTED;
3840 // always (except passive spells) check items (focus object can be required for any type casts)
3841 if(!IsPassiveSpell(m_spellInfo->Id))
3842 if(uint8 castResult = CheckItems())
3843 return castResult;
3845 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3846 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3848 for(uint8 j = 0; j < 3; j++)
3850 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3851 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3852 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3853 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3855 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3856 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3857 if(lower==upper)
3858 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);
3860 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3861 float range = GetSpellMaxRange(srange);
3863 Creature* creatureScriptTarget = NULL;
3864 GameObject* goScriptTarget = NULL;
3866 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3868 switch(i_spellST->second.type)
3870 case SPELL_TARGET_TYPE_GAMEOBJECT:
3872 GameObject* p_GameObject = NULL;
3874 if(i_spellST->second.targetEntry)
3876 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3877 Cell cell(p);
3878 cell.data.Part.reserved = ALL_DISTRICT;
3880 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3881 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
3883 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3884 CellLock<GridReadGuard> cell_lock(cell, p);
3885 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3887 if(p_GameObject)
3889 // remember found target and range, next attempt will find more near target with another entry
3890 creatureScriptTarget = NULL;
3891 goScriptTarget = p_GameObject;
3892 range = go_check.GetLastRange();
3895 else if( focusObject ) //Focus Object
3897 float frange = m_caster->GetDistance(focusObject);
3898 if(range >= frange)
3900 creatureScriptTarget = NULL;
3901 goScriptTarget = focusObject;
3902 range = frange;
3905 break;
3907 case SPELL_TARGET_TYPE_CREATURE:
3908 case SPELL_TARGET_TYPE_DEAD:
3909 default:
3911 Creature *p_Creature = NULL;
3913 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3914 Cell cell(p);
3915 cell.data.Part.reserved = ALL_DISTRICT;
3916 cell.SetNoCreate(); // Really don't know what is that???
3918 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3919 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
3921 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3923 CellLock<GridReadGuard> cell_lock(cell, p);
3924 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
3926 if(p_Creature )
3928 creatureScriptTarget = p_Creature;
3929 goScriptTarget = NULL;
3930 range = u_check.GetLastRange();
3932 break;
3937 if(creatureScriptTarget)
3939 // store coordinates for TARGET_SCRIPT_COORDINATES
3940 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3941 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3943 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3945 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3946 AddUnitTarget(creatureScriptTarget, j);
3948 // store explicit target for TARGET_SCRIPT
3949 else
3950 AddUnitTarget(creatureScriptTarget, j);
3952 else if(goScriptTarget)
3954 // store coordinates for TARGET_SCRIPT_COORDINATES
3955 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3956 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3958 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3960 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3961 AddGOTarget(goScriptTarget, j);
3963 // store explicit target for TARGET_SCRIPT
3964 else
3965 AddGOTarget(goScriptTarget, j);
3967 //Missing DB Entry or targets for this spellEffect.
3968 else
3970 // not report target not existence for triggered spells
3971 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3972 return SPELL_FAILED_DONT_REPORT;
3973 else
3974 return SPELL_FAILED_BAD_TARGETS;
3980 if(!m_IsTriggeredSpell)
3981 if(uint8 castResult = CheckRange(strict))
3982 return castResult;
3985 if(uint8 castResult = CheckPower())
3986 return castResult;
3989 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
3990 if(uint8 castResult = CheckCasterAuras())
3991 return castResult;
3993 for (int i = 0; i < 3; i++)
3995 // for effects of spells that have only one target
3996 switch(m_spellInfo->Effect[i])
3998 case SPELL_EFFECT_DUMMY:
4000 if(m_spellInfo->SpellIconID == 1648) // Execute
4002 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4003 return SPELL_FAILED_BAD_TARGETS;
4005 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
4007 if(m_caster->IsInWater())
4008 return SPELL_FAILED_ONLY_ABOVEWATER;
4010 else if(m_spellInfo->SpellIconID==156) // Holy Shock
4012 // spell different for friends and enemies
4013 // hart version required facing
4014 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
4015 return SPELL_FAILED_UNIT_NOT_INFRONT;
4017 break;
4019 case SPELL_EFFECT_SCHOOL_DAMAGE:
4021 // Hammer of Wrath
4022 if(m_spellInfo->SpellVisual[0] == 7250)
4024 if (!m_targets.getUnitTarget())
4025 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4027 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4028 return SPELL_FAILED_BAD_TARGETS;
4030 break;
4032 case SPELL_EFFECT_TAMECREATURE:
4034 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
4035 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4037 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
4038 return SPELL_FAILED_HIGHLEVEL;
4040 // use SMSG_PET_TAME_FAILURE?
4041 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
4042 return SPELL_FAILED_BAD_TARGETS;
4044 if(m_caster->GetPetGUID())
4045 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4047 if(m_caster->GetCharmGUID())
4048 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4050 break;
4052 case SPELL_EFFECT_LEARN_SPELL:
4054 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
4055 break;
4057 Pet* pet = m_caster->GetPet();
4059 if(!pet)
4060 return SPELL_FAILED_NO_PET;
4062 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4064 if(!learn_spellproto)
4065 return SPELL_FAILED_NOT_KNOWN;
4067 if(m_spellInfo->spellLevel > pet->getLevel())
4068 return SPELL_FAILED_LOWLEVEL;
4070 break;
4072 case SPELL_EFFECT_LEARN_PET_SPELL:
4074 Pet* pet = m_caster->GetPet();
4076 if(!pet)
4077 return SPELL_FAILED_NO_PET;
4079 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4081 if(!learn_spellproto)
4082 return SPELL_FAILED_NOT_KNOWN;
4084 if(m_spellInfo->spellLevel > pet->getLevel())
4085 return SPELL_FAILED_LOWLEVEL;
4087 break;
4089 case SPELL_EFFECT_FEED_PET:
4091 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4092 return SPELL_FAILED_BAD_TARGETS;
4094 Item* foodItem = m_targets.getItemTarget();
4095 if(!foodItem)
4096 return SPELL_FAILED_BAD_TARGETS;
4098 Pet* pet = m_caster->GetPet();
4100 if(!pet)
4101 return SPELL_FAILED_NO_PET;
4103 if(!pet->HaveInDiet(foodItem->GetProto()))
4104 return SPELL_FAILED_WRONG_PET_FOOD;
4106 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4107 return SPELL_FAILED_FOOD_LOWLEVEL;
4109 if(m_caster->isInCombat() || pet->isInCombat())
4110 return SPELL_FAILED_AFFECTING_COMBAT;
4112 break;
4114 case SPELL_EFFECT_POWER_BURN:
4115 case SPELL_EFFECT_POWER_DRAIN:
4117 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4118 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4119 if(Unit* target = m_targets.getUnitTarget())
4120 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
4121 return SPELL_FAILED_BAD_TARGETS;
4122 break;
4124 case SPELL_EFFECT_CHARGE:
4126 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4127 return SPELL_FAILED_ROOTED;
4129 break;
4131 case SPELL_EFFECT_SKINNING:
4133 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4134 return SPELL_FAILED_BAD_TARGETS;
4136 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4137 return SPELL_FAILED_TARGET_UNSKINNABLE;
4139 Creature* creature = (Creature*)m_targets.getUnitTarget();
4140 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4142 return SPELL_FAILED_TARGET_NOT_LOOTED;
4145 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4147 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4148 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4149 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
4150 if (ReqValue > skillValue)
4151 return SPELL_FAILED_LOW_CASTLEVEL;
4153 // chance for fail at orange skinning attempt
4154 if( (m_selfContainer && (*m_selfContainer) == this) &&
4155 skillValue < sWorld.GetConfigMaxSkillValue() &&
4156 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
4157 return SPELL_FAILED_TRY_AGAIN;
4159 break;
4161 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4162 case SPELL_EFFECT_OPEN_LOCK:
4164 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4165 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4166 break;
4168 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4169 // we need a go target in case of TARGET_GAMEOBJECT
4170 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4171 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4172 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4173 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4174 return SPELL_FAILED_BAD_TARGETS;
4176 // In BattleGround players can use only flags and banners
4177 if( ((Player*)m_caster)->InBattleGround() &&
4178 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
4179 return SPELL_FAILED_TRY_AGAIN;
4181 // get the lock entry
4182 LockEntry const *lockInfo = NULL;
4183 if (GameObject* go=m_targets.getGOTarget())
4184 lockInfo = sLockStore.LookupEntry(go->GetLockId());
4185 else if(Item* itm=m_targets.getItemTarget())
4186 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
4188 // check lock compatibility
4189 if (lockInfo)
4191 // check for lock - key pair (checked by client also, just prevent cheating
4192 bool ok_key = false;
4193 for(int it = 0; it < 8; ++it)
4195 switch(lockInfo->Type[it])
4197 case LOCK_KEY_NONE:
4198 break;
4199 case LOCK_KEY_ITEM:
4201 if(lockInfo->Index[it])
4203 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4204 ok_key =true;
4205 break;
4208 case LOCK_KEY_SKILL:
4210 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->Index[it])
4211 break;
4213 switch(lockInfo->Index[it])
4215 case LOCKTYPE_HERBALISM:
4216 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
4217 ok_key =true;
4218 break;
4219 case LOCKTYPE_MINING:
4220 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
4221 ok_key =true;
4222 break;
4223 default:
4224 ok_key =true;
4225 break;
4229 if(ok_key)
4230 break;
4233 if(!ok_key)
4234 return SPELL_FAILED_BAD_TARGETS;
4237 // chance for fail at orange mining/herb/LockPicking gathering attempt
4238 if (!m_selfContainer || ((*m_selfContainer) != this))
4239 break;
4241 // get the skill value of the player
4242 int32 SkillValue = 0;
4243 bool canFailAtMax = true;
4244 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
4246 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
4247 canFailAtMax = false;
4249 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
4251 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
4252 canFailAtMax = false;
4254 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4255 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
4257 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
4258 if(m_CastItem)
4259 SkillValue = 0;
4261 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
4262 SkillValue += m_currentBasePoints[i]+1;
4264 // get the required lock value
4265 int32 ReqValue=0;
4266 if (lockInfo)
4268 // check for lock - key pair
4269 bool ok = false;
4270 for(int it = 0; it < 8; ++it)
4272 if(lockInfo->Type[it]==LOCK_KEY_ITEM && lockInfo->Index[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4274 // if so, we're good to go
4275 ok = true;
4276 break;
4279 if(ok)
4280 break;
4282 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4283 ReqValue = lockInfo->Skill[1];
4284 else
4285 ReqValue = lockInfo->Skill[0];
4288 // skill doesn't meet the required value
4289 if (ReqValue > SkillValue)
4290 return SPELL_FAILED_LOW_CASTLEVEL;
4292 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4293 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
4294 return SPELL_FAILED_TRY_AGAIN;
4296 break;
4298 case SPELL_EFFECT_SUMMON_DEAD_PET:
4300 Creature *pet = m_caster->GetPet();
4301 if(!pet)
4302 return SPELL_FAILED_NO_PET;
4304 if(pet->isAlive())
4305 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4307 break;
4309 // This is generic summon effect
4310 case SPELL_EFFECT_SUMMON:
4312 switch(m_spellInfo->EffectMiscValueB[i])
4314 case SUMMON_TYPE_POSESSED:
4315 case SUMMON_TYPE_POSESSED2:
4316 case SUMMON_TYPE_DEMON:
4317 case SUMMON_TYPE_SUMMON:
4319 if(m_caster->GetPetGUID())
4320 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4322 if(m_caster->GetCharmGUID())
4323 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4324 break;
4327 break;
4329 // Not used for summon?
4330 case SPELL_EFFECT_SUMMON_PHANTASM:
4332 if(m_caster->GetPetGUID())
4333 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4335 if(m_caster->GetCharmGUID())
4336 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4338 break;
4340 case SPELL_EFFECT_SUMMON_PET:
4342 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4345 Pet* pet = ((Player*)m_caster)->GetPet();
4347 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4349 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4350 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4352 else
4353 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4356 if(m_caster->GetCharmGUID())
4357 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4359 break;
4361 case SPELL_EFFECT_SUMMON_PLAYER:
4363 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4364 return SPELL_FAILED_BAD_TARGETS;
4365 if(!((Player*)m_caster)->GetSelection())
4366 return SPELL_FAILED_BAD_TARGETS;
4368 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4369 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4370 return SPELL_FAILED_BAD_TARGETS;
4372 // check if our map is dungeon
4373 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4375 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4376 if(!instance)
4377 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4378 if ( instance->levelMin > target->getLevel() )
4379 return SPELL_FAILED_LOWLEVEL;
4380 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4381 return SPELL_FAILED_HIGHLEVEL;
4383 break;
4385 case SPELL_EFFECT_LEAP:
4386 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4388 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4389 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4390 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4391 // teleport a bit above terrain level to avoid falling below it
4392 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4393 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4394 return SPELL_FAILED_TRY_AGAIN;
4396 float caster_pos_z = m_caster->GetPositionZ();
4397 // Control the caster to not climb or drop when +-fz > 8
4398 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4399 return SPELL_FAILED_TRY_AGAIN;
4401 // not allow use this effect at battleground until battleground start
4402 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4403 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4404 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4405 return SPELL_FAILED_TRY_AGAIN;
4406 break;
4408 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4410 if (m_targets.getUnitTarget()==m_caster)
4411 return SPELL_FAILED_BAD_TARGETS;
4412 break;
4414 default:break;
4418 for (int i = 0; i < 3; i++)
4420 switch(m_spellInfo->EffectApplyAuraName[i])
4422 case SPELL_AURA_MOD_POSSESS:
4423 case SPELL_AURA_MOD_CHARM:
4425 if(m_caster->GetPetGUID())
4426 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4428 if(m_caster->GetCharmGUID())
4429 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4431 if(m_caster->GetCharmerGUID())
4432 return SPELL_FAILED_CHARMED;
4434 if(!m_targets.getUnitTarget())
4435 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4437 if(m_targets.getUnitTarget()->GetCharmerGUID())
4438 return SPELL_FAILED_CHARMED;
4440 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4441 return SPELL_FAILED_HIGHLEVEL;
4443 break;
4445 case SPELL_AURA_MOUNTED:
4447 if (m_caster->IsInWater())
4448 return SPELL_FAILED_ONLY_ABOVEWATER;
4450 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4451 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4453 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4454 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4455 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4457 ShapeshiftForm form = m_caster->m_form;
4458 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4459 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4460 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4461 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4462 return SPELL_FAILED_NOT_SHAPESHIFT;
4464 break;
4466 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4468 if(!m_targets.getUnitTarget())
4469 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4471 // can be casted at non-friendly unit or own pet/charm
4472 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4473 return SPELL_FAILED_TARGET_FRIENDLY;
4475 break;
4477 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4478 case SPELL_AURA_FLY:
4480 // not allow cast fly spells at old maps by players (all spells is self target)
4481 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4483 if( !((Player*)m_caster)->IsAllowUseFlyMountsHere() )
4484 return SPELL_FAILED_NOT_HERE;
4487 break;
4489 case SPELL_AURA_PERIODIC_MANA_LEECH:
4491 if (!m_targets.getUnitTarget())
4492 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4494 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4495 break;
4497 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4498 return SPELL_FAILED_BAD_TARGETS;
4500 break;
4502 default:
4503 break;
4507 // all ok
4508 return 0;
4511 int16 Spell::PetCanCast(Unit* target)
4513 if(!m_caster->isAlive())
4514 return SPELL_FAILED_CASTER_DEAD;
4516 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4517 return SPELL_FAILED_SPELL_IN_PROGRESS;
4518 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4519 return SPELL_FAILED_AFFECTING_COMBAT;
4521 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4523 //dead owner (pets still alive when owners ressed?)
4524 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4525 return SPELL_FAILED_CASTER_DEAD;
4527 if(!target && m_targets.getUnitTarget())
4528 target = m_targets.getUnitTarget();
4530 bool need = false;
4531 for(uint32 i = 0;i<3;i++)
4533 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)
4535 need = true;
4536 if(!target)
4537 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4538 break;
4541 if(need)
4542 m_targets.setUnitTarget(target);
4544 Unit* _target = m_targets.getUnitTarget();
4546 if(_target) //for target dead/target not valid
4548 if(!_target->isAlive())
4549 return SPELL_FAILED_BAD_TARGETS;
4551 if(IsPositiveSpell(m_spellInfo->Id))
4553 if(m_caster->IsHostileTo(_target))
4554 return SPELL_FAILED_BAD_TARGETS;
4556 else
4558 bool duelvsplayertar = false;
4559 for(int j=0;j<3;j++)
4561 //TARGET_DUELVSPLAYER is positive AND negative
4562 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4564 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4566 return SPELL_FAILED_BAD_TARGETS;
4570 //cooldown
4571 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4572 return SPELL_FAILED_NOT_READY;
4575 uint16 result = CanCast(true);
4576 if(result != 0)
4577 return result;
4578 else
4579 return -1; //this allows to check spell fail 0, in combat
4582 uint8 Spell::CheckCasterAuras() const
4584 // Flag drop spells totally immuned to caster auras
4585 // FIXME: find more nice check for all totally immuned spells
4586 // AttributesEx3 & 0x10000000?
4587 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4588 return 0;
4590 uint8 school_immune = 0;
4591 uint32 mechanic_immune = 0;
4592 uint32 dispel_immune = 0;
4594 //Check if the spell grants school or mechanic immunity.
4595 //We use bitmasks so the loop is done only once and not on every aura check below.
4596 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4598 for(int i = 0;i < 3; i ++)
4600 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4601 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4602 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4603 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4604 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4605 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4607 //immune movement impairment and loss of control
4608 if(m_spellInfo->Id==(uint32)42292)
4609 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4612 //Check whether the cast should be prevented by any state you might have.
4613 uint8 prevented_reason = 0;
4614 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4615 uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
4616 if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4617 prevented_reason = SPELL_FAILED_STUNNED;
4618 else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4619 prevented_reason = SPELL_FAILED_CONFUSED;
4620 else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4621 prevented_reason = SPELL_FAILED_FLEEING;
4622 else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4623 prevented_reason = SPELL_FAILED_SILENCED;
4624 else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4625 prevented_reason = SPELL_FAILED_PACIFIED;
4627 // Attr must make flag drop spell totally immune from all effects
4628 if(prevented_reason)
4630 if(school_immune || mechanic_immune || dispel_immune)
4632 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4633 Unit::AuraMap const& auras = m_caster->GetAuras();
4634 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4636 if(itr->second)
4638 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4639 continue;
4640 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4641 continue;
4642 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4643 continue;
4645 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4646 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4647 switch(itr->second->GetModifier()->m_auraname)
4649 case SPELL_AURA_MOD_STUN:
4650 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4651 return SPELL_FAILED_STUNNED;
4652 break;
4653 case SPELL_AURA_MOD_CONFUSE:
4654 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4655 return SPELL_FAILED_CONFUSED;
4656 break;
4657 case SPELL_AURA_MOD_FEAR:
4658 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4659 return SPELL_FAILED_FLEEING;
4660 break;
4661 case SPELL_AURA_MOD_SILENCE:
4662 case SPELL_AURA_MOD_PACIFY:
4663 case SPELL_AURA_MOD_PACIFY_SILENCE:
4664 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4665 return SPELL_FAILED_PACIFIED;
4666 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4667 return SPELL_FAILED_SILENCED;
4668 break;
4673 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4674 else
4675 return prevented_reason;
4677 return 0; // all ok
4680 bool Spell::CanAutoCast(Unit* target)
4682 uint64 targetguid = target->GetGUID();
4684 for(uint32 j = 0;j<3;j++)
4686 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4688 if( m_spellInfo->StackAmount <= 1)
4690 if( target->HasAura(m_spellInfo->Id, j) )
4691 return false;
4693 else
4695 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4696 return false;
4699 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4701 if( target->HasAura(m_spellInfo->Id, j) )
4702 return false;
4706 int16 result = PetCanCast(target);
4708 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4710 FillTargetMap();
4711 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4712 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4713 if( ihit->targetGUID == targetguid )
4714 return true;
4716 return false; //target invalid
4719 uint8 Spell::CheckRange(bool strict)
4721 float range_mod;
4723 // self cast doesn't need range checking -- also for Starshards fix
4724 if (m_spellInfo->rangeIndex == 1) return 0;
4726 if (strict) //add radius of caster
4727 range_mod = 1.25;
4728 else //add radius of caster and ~5 yds "give"
4729 range_mod = 6.25;
4731 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4732 float max_range = GetSpellMaxRange(srange) + range_mod;
4733 float min_range = GetSpellMinRange(srange);
4735 if(Player* modOwner = m_caster->GetSpellModOwner())
4736 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4738 Unit *target = m_targets.getUnitTarget();
4740 if(target && target != m_caster)
4742 // distance from target center in checks
4743 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4744 if(dist > max_range)
4745 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4746 if(dist < min_range)
4747 return SPELL_FAILED_TOO_CLOSE;
4748 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4749 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4750 return SPELL_FAILED_UNIT_NOT_INFRONT;
4753 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4755 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4756 if(dist > max_range)
4757 return SPELL_FAILED_OUT_OF_RANGE;
4758 if(dist < min_range)
4759 return SPELL_FAILED_TOO_CLOSE;
4762 return 0; // ok
4765 int32 Spell::CalculatePowerCost()
4767 // item cast not used power
4768 if(m_CastItem)
4769 return 0;
4771 // Spell drain all exist power on cast (Only paladin lay of Hands)
4772 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4774 // If power type - health drain all
4775 if (m_spellInfo->powerType == POWER_HEALTH)
4776 return m_caster->GetHealth();
4777 // Else drain all power
4778 if (m_spellInfo->powerType < MAX_POWERS)
4779 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4780 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4781 return 0;
4784 // Base powerCost
4785 int32 powerCost = m_spellInfo->manaCost;
4786 // PCT cost from total amount
4787 if (m_spellInfo->ManaCostPercentage)
4789 switch (m_spellInfo->powerType)
4791 // health as power used
4792 case POWER_HEALTH:
4793 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4794 break;
4795 case POWER_MANA:
4796 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4797 break;
4798 case POWER_RAGE:
4799 case POWER_FOCUS:
4800 case POWER_ENERGY:
4801 case POWER_HAPPINESS:
4802 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4803 break;
4804 case POWER_RUNE:
4805 case POWER_RUNIC_POWER:
4806 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4807 break;
4808 default:
4809 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4810 return 0;
4813 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4814 // Flat mod from caster auras by spell school
4815 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4816 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4817 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4818 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4819 // Apply cost mod by spell
4820 if(Player* modOwner = m_caster->GetSpellModOwner())
4821 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4823 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4824 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4826 // PCT mod from user auras by school
4827 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4828 if (powerCost < 0)
4829 powerCost = 0;
4830 return powerCost;
4833 uint8 Spell::CheckPower()
4835 // item cast not used power
4836 if(m_CastItem)
4837 return 0;
4839 // health as power used - need check health amount
4840 if(m_spellInfo->powerType == POWER_HEALTH)
4842 if(m_caster->GetHealth() <= m_powerCost)
4843 return SPELL_FAILED_CASTER_AURASTATE;
4844 return 0;
4846 // Check valid power type
4847 if( m_spellInfo->powerType >= MAX_POWERS )
4849 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4850 return SPELL_FAILED_UNKNOWN;
4853 uint8 failReason = CheckRuneCost(m_spellInfo->runeCostID);
4854 if(failReason)
4855 return failReason;
4857 // Check power amount
4858 Powers powerType = Powers(m_spellInfo->powerType);
4859 if(m_caster->GetPower(powerType) < m_powerCost)
4860 return SPELL_FAILED_NO_POWER;
4861 else
4862 return 0;
4865 uint8 Spell::CheckItems()
4867 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4868 return 0;
4870 uint32 itemid, itemcount;
4871 Player* p_caster = (Player*)m_caster;
4873 if(m_CastItem)
4875 itemid = m_CastItem->GetEntry();
4876 if( !p_caster->HasItemCount(itemid,1) )
4877 return SPELL_FAILED_ITEM_NOT_READY;
4878 else
4880 ItemPrototype const *proto = m_CastItem->GetProto();
4881 if(!proto)
4882 return SPELL_FAILED_ITEM_NOT_READY;
4884 for (int i = 0; i<5; i++)
4886 if (proto->Spells[i].SpellCharges)
4888 if(m_CastItem->GetSpellCharges(i)==0)
4889 return SPELL_FAILED_NO_CHARGES_REMAIN;
4893 uint32 ItemClass = proto->Class;
4894 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4896 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4897 uint8 failReason = 0;
4898 for (int i = 0; i < 3; i++)
4900 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4901 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4902 continue;
4904 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4906 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4908 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4909 continue;
4911 else
4913 failReason = 0;
4914 break;
4918 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4919 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4921 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4923 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4924 continue;
4927 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4928 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4930 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4931 continue;
4933 else
4935 failReason = 0;
4936 break;
4940 if (failReason)
4941 return failReason;
4946 if(m_targets.getItemTargetGUID())
4948 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4949 return SPELL_FAILED_BAD_TARGETS;
4951 if(!m_targets.getItemTarget())
4952 return SPELL_FAILED_ITEM_GONE;
4954 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4955 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4957 // if not item target then required item must be equipped
4958 else
4960 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4961 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4964 if(m_spellInfo->RequiresSpellFocus)
4966 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4967 Cell cell(p);
4968 cell.data.Part.reserved = ALL_DISTRICT;
4970 GameObject* ok = NULL;
4971 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4972 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(m_caster,ok,go_check);
4974 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4975 CellLock<GridReadGuard> cell_lock(cell, p);
4976 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4978 if(!ok)
4979 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4981 focusObject = ok; // game object found in range
4984 if (!p_caster->CanNoReagentCast(m_spellInfo))
4986 for(uint32 i=0;i<8;i++)
4988 if(m_spellInfo->Reagent[i] <= 0)
4989 continue;
4991 itemid = m_spellInfo->Reagent[i];
4992 itemcount = m_spellInfo->ReagentCount[i];
4994 // if CastItem is also spell reagent
4995 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4997 ItemPrototype const *proto = m_CastItem->GetProto();
4998 if(!proto)
4999 return SPELL_FAILED_ITEM_NOT_READY;
5000 for(int s=0;s<5;s++)
5002 // CastItem will be used up and does not count as reagent
5003 int32 charges = m_CastItem->GetSpellCharges(s);
5004 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
5006 ++itemcount;
5007 break;
5011 if( !p_caster->HasItemCount(itemid,itemcount) )
5012 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
5016 uint32 totems = 2;
5017 for(int i=0;i<2;++i)
5019 if(m_spellInfo->Totem[i] != 0)
5021 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
5023 totems -= 1;
5024 continue;
5026 }else
5027 totems -= 1;
5029 if(totems != 0)
5030 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
5032 //Check items for TotemCategory
5033 uint32 TotemCategory = 2;
5034 for(int i=0;i<2;++i)
5036 if(m_spellInfo->TotemCategory[i] != 0)
5038 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
5040 TotemCategory -= 1;
5041 continue;
5044 else
5045 TotemCategory -= 1;
5047 if(TotemCategory != 0)
5048 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
5050 for(int i = 0; i < 3; i++)
5052 switch (m_spellInfo->Effect[i])
5054 case SPELL_EFFECT_CREATE_ITEM:
5056 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
5058 ItemPosCountVec dest;
5059 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
5060 if (msg != EQUIP_ERR_OK )
5062 p_caster->SendEquipError( msg, NULL, NULL );
5063 return SPELL_FAILED_DONT_REPORT;
5066 break;
5068 case SPELL_EFFECT_ENCHANT_ITEM:
5070 Item* targetItem = m_targets.getItemTarget();
5071 if(!targetItem)
5072 return SPELL_FAILED_ITEM_NOT_FOUND;
5074 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5075 return SPELL_FAILED_LOWLEVEL;
5076 // Not allow enchant in trade slot for some enchant type
5077 if( targetItem->GetOwner() != m_caster )
5079 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5080 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5081 if(!pEnchant)
5082 return SPELL_FAILED_ERROR;
5083 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5084 return SPELL_FAILED_NOT_TRADEABLE;
5086 break;
5088 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5090 Item *item = m_targets.getItemTarget();
5091 if(!item)
5092 return SPELL_FAILED_ITEM_NOT_FOUND;
5093 // Not allow enchant in trade slot for some enchant type
5094 if( item->GetOwner() != m_caster )
5096 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5097 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5098 if(!pEnchant)
5099 return SPELL_FAILED_ERROR;
5100 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5101 return SPELL_FAILED_NOT_TRADEABLE;
5103 break;
5105 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5106 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5107 break;
5108 case SPELL_EFFECT_DISENCHANT:
5110 if(!m_targets.getItemTarget())
5111 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5113 // prevent disenchanting in trade slot
5114 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5115 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5117 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5118 if(!itemProto)
5119 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5121 uint32 item_quality = itemProto->Quality;
5122 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5123 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5124 if (item_disenchantskilllevel == uint32(-1))
5125 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5126 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5127 return SPELL_FAILED_LOW_CASTLEVEL;
5128 if(item_quality > 4 || item_quality < 2)
5129 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5130 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5131 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5132 if (!itemProto->DisenchantID)
5133 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5134 break;
5136 case SPELL_EFFECT_PROSPECTING:
5138 if(!m_targets.getItemTarget())
5139 return SPELL_FAILED_CANT_BE_PROSPECTED;
5140 //ensure item is a prospectable ore
5141 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5142 return SPELL_FAILED_CANT_BE_PROSPECTED;
5143 //prevent prospecting in trade slot
5144 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5145 return SPELL_FAILED_CANT_BE_PROSPECTED;
5146 //Check for enough skill in jewelcrafting
5147 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5148 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5149 return SPELL_FAILED_LOW_CASTLEVEL;
5150 //make sure the player has the required ores in inventory
5151 if(m_targets.getItemTarget()->GetCount() < 5)
5152 return SPELL_FAILED_NEED_MORE_ITEMS;
5154 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5155 return SPELL_FAILED_CANT_BE_PROSPECTED;
5157 break;
5159 case SPELL_EFFECT_MILLING:
5161 if(!m_targets.getItemTarget())
5162 return SPELL_FAILED_CANT_BE_MILLED;
5163 //ensure item is a millable herb
5164 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5165 return SPELL_FAILED_CANT_BE_MILLED;
5166 //prevent milling in trade slot
5167 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5168 return SPELL_FAILED_CANT_BE_MILLED;
5169 //Check for enough skill in inscription
5170 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5171 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5172 return SPELL_FAILED_LOW_CASTLEVEL;
5173 //make sure the player has the required herbs in inventory
5174 if(m_targets.getItemTarget()->GetCount() < 5)
5175 return SPELL_FAILED_NEED_MORE_ITEMS;
5177 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5178 return SPELL_FAILED_CANT_BE_MILLED;
5180 break;
5182 case SPELL_EFFECT_WEAPON_DAMAGE:
5183 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5185 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5186 if( m_attackType != RANGED_ATTACK )
5187 break;
5188 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5189 if(!pItem || pItem->IsBroken())
5190 return SPELL_FAILED_EQUIPPED_ITEM;
5192 switch(pItem->GetProto()->SubClass)
5194 case ITEM_SUBCLASS_WEAPON_THROWN:
5196 uint32 ammo = pItem->GetEntry();
5197 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5198 return SPELL_FAILED_NO_AMMO;
5199 }; break;
5200 case ITEM_SUBCLASS_WEAPON_GUN:
5201 case ITEM_SUBCLASS_WEAPON_BOW:
5202 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5204 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5205 if(!ammo)
5207 // Requires No Ammo
5208 if(m_caster->GetDummyAura(46699))
5209 break; // skip other checks
5211 return SPELL_FAILED_NO_AMMO;
5214 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5215 if(!ammoProto)
5216 return SPELL_FAILED_NO_AMMO;
5218 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5219 return SPELL_FAILED_NO_AMMO;
5221 // check ammo ws. weapon compatibility
5222 switch(pItem->GetProto()->SubClass)
5224 case ITEM_SUBCLASS_WEAPON_BOW:
5225 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5226 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5227 return SPELL_FAILED_NO_AMMO;
5228 break;
5229 case ITEM_SUBCLASS_WEAPON_GUN:
5230 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5231 return SPELL_FAILED_NO_AMMO;
5232 break;
5233 default:
5234 return SPELL_FAILED_NO_AMMO;
5237 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5238 return SPELL_FAILED_NO_AMMO;
5239 }; break;
5240 case ITEM_SUBCLASS_WEAPON_WAND:
5241 default:
5242 break;
5244 break;
5246 default:break;
5250 return uint8(0);
5253 void Spell::Delayed()
5255 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5256 return;
5258 if (m_spellState == SPELL_STATE_DELAYED)
5259 return; // spell is active and can't be time-backed
5261 if(isDelayableNoMore()) // Spells may only be delayed twice
5262 return;
5264 // spells not loosing casting time ( slam, dynamites, bombs.. )
5265 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5266 return;
5268 //check pushback reduce
5269 int32 delaytime = 500; // spellcasting delay is normally 500ms
5270 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5271 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5272 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5273 if(delayReduce >= 100)
5274 return;
5276 delaytime = delaytime * (100 - delayReduce) / 100;
5278 if(int32(m_timer) + delaytime > m_casttime)
5280 delaytime = m_casttime - m_timer;
5281 m_timer = m_casttime;
5283 else
5284 m_timer += delaytime;
5286 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5288 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5289 data.append(m_caster->GetPackGUID());
5290 data << uint32(delaytime);
5292 m_caster->SendMessageToSet(&data,true);
5295 void Spell::DelayedChannel()
5297 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5298 return;
5300 if(isDelayableNoMore()) // Spells may only be delayed twice
5301 return;
5303 //check pushback reduce
5304 int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
5305 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5306 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,delayReduce, this);
5307 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5308 if(delayReduce >= 100)
5309 return;
5311 delaytime = delaytime * (100 - delayReduce) / 100;
5313 if(int32(m_timer) < delaytime)
5315 delaytime = m_timer;
5316 m_timer = 0;
5318 else
5319 m_timer -= delaytime;
5321 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5323 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5325 if ((*ihit).missCondition == SPELL_MISS_NONE)
5327 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5328 if (unit)
5330 for (int j=0;j<3;j++)
5331 if( ihit->effectMask & (1<<j) )
5332 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5338 for(int j = 0; j < 3; j++)
5340 // partially interrupt persistent area auras
5341 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5342 if(dynObj)
5343 dynObj->Delay(delaytime);
5346 SendChannelUpdate(m_timer);
5349 void Spell::UpdatePointers()
5351 if(m_originalCasterGUID==m_caster->GetGUID())
5352 m_originalCaster = m_caster;
5353 else
5355 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5356 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5359 m_targets.Update(m_caster);
5362 bool Spell::IsAffectedByAura(Aura *aura)
5364 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5367 bool Spell::CheckTargetCreatureType(Unit* target) const
5369 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5371 // Curse of Doom : not find another way to fix spell target check :/
5372 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5374 // not allow cast at player
5375 if(target->GetTypeId()==TYPEID_PLAYER)
5376 return false;
5378 spellCreatureTargetMask = 0x7FF;
5381 // Dismiss Pet and Taming Lesson skipped
5382 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5383 spellCreatureTargetMask = 0;
5385 if (spellCreatureTargetMask)
5387 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5389 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5391 return true;
5394 CurrentSpellTypes Spell::GetCurrentContainer()
5396 if (IsNextMeleeSwingSpell())
5397 return(CURRENT_MELEE_SPELL);
5398 else if (IsAutoRepeat())
5399 return(CURRENT_AUTOREPEAT_SPELL);
5400 else if (IsChanneledSpell(m_spellInfo))
5401 return(CURRENT_CHANNELED_SPELL);
5402 else
5403 return(CURRENT_GENERIC_SPELL);
5406 bool Spell::CheckTarget( Unit* target, uint32 eff )
5408 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5409 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5411 if (!CheckTargetCreatureType(target))
5412 return false;
5415 // Check Aura spell req (need for AoE spells)
5416 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5417 return false;
5418 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5419 return false;
5421 // Check targets for not_selectable unit flag and remove
5422 // A player can cast spells on his pet (or other controlled unit) though in any state
5423 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5425 // any unattackable target skipped
5426 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5427 return false;
5429 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5430 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5431 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5432 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5433 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5434 return false;
5437 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5438 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5440 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5441 return false;
5443 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5444 return false;
5447 //Check targets for LOS visibility (except spells without range limitations )
5448 switch(m_spellInfo->Effect[eff])
5450 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5451 break;
5452 case SPELL_EFFECT_DUMMY:
5453 if(m_spellInfo->Id!=20577) // Cannibalize
5454 break;
5455 //fall through
5456 case SPELL_EFFECT_RESURRECT_NEW:
5457 // player far away, maybe his corpse near?
5458 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5460 if(!m_targets.getCorpseTargetGUID())
5461 return false;
5463 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5464 if(!corpse)
5465 return false;
5467 if(target->GetGUID()!=corpse->GetOwnerGUID())
5468 return false;
5470 if(!corpse->IsWithinLOSInMap(m_caster))
5471 return false;
5474 // all ok by some way or another, skip normal check
5475 break;
5476 default: // normal case
5477 // Get GO cast coordinates if original caster -> GO
5478 WorldObject *caster = NULL;
5479 if (m_originalCasterGUID)
5480 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
5481 if (!caster)
5482 caster = m_caster;
5483 if(target!=m_caster && !target->IsWithinLOSInMap(caster))
5484 return false;
5485 break;
5488 return true;
5491 Unit* Spell::SelectMagnetTarget()
5493 Unit* target = m_targets.getUnitTarget();
5495 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
5497 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
5498 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
5500 if(Unit* magnet = (*itr)->GetCaster())
5502 if(magnet->IsWithinLOSInMap(m_caster))
5504 target = magnet;
5505 m_targets.setUnitTarget(target);
5506 break;
5512 return target;
5515 bool Spell::IsNeedSendToClient() const
5517 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5518 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5521 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5523 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5524 if(itr->effectMask & (1<<effect))
5525 return true;
5527 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5528 if(itr->effectMask & (1<<effect))
5529 return true;
5531 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5532 if(itr->effectMask & (1<<effect))
5533 return true;
5535 return false;
5538 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5540 m_Spell = spell;
5543 SpellEvent::~SpellEvent()
5545 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5546 m_Spell->cancel();
5548 if (m_Spell->IsDeletable())
5550 delete m_Spell;
5552 else
5554 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5555 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5559 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5561 // update spell if it is not finished
5562 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5563 m_Spell->update(p_time);
5565 // check spell state to process
5566 switch (m_Spell->getState())
5568 case SPELL_STATE_FINISHED:
5570 // spell was finished, check deletable state
5571 if (m_Spell->IsDeletable())
5573 // check, if we do have unfinished triggered spells
5575 return(true); // spell is deletable, finish event
5577 // event will be re-added automatically at the end of routine)
5578 } break;
5580 case SPELL_STATE_CASTING:
5582 // this spell is in channeled state, process it on the next update
5583 // event will be re-added automatically at the end of routine)
5584 } break;
5586 case SPELL_STATE_DELAYED:
5588 // first, check, if we have just started
5589 if (m_Spell->GetDelayStart() != 0)
5591 // no, we aren't, do the typical update
5592 // check, if we have channeled spell on our hands
5593 if (IsChanneledSpell(m_Spell->m_spellInfo))
5595 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5596 // check, if we have casting anything else except this channeled spell and autorepeat
5597 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5599 // another non-melee non-delayed spell is casted now, abort
5600 m_Spell->cancel();
5602 else
5604 // do the action (pass spell to channeling state)
5605 m_Spell->handle_immediate();
5607 // event will be re-added automatically at the end of routine)
5609 else
5611 // run the spell handler and think about what we can do next
5612 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5613 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5614 if (n_offset)
5616 // re-add us to the queue
5617 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5618 return(false); // event not complete
5620 // event complete
5621 // finish update event will be re-added automatically at the end of routine)
5624 else
5626 // delaying had just started, record the moment
5627 m_Spell->SetDelayStart(e_time);
5628 // re-plan the event for the delay moment
5629 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5630 return(false); // event not complete
5632 } break;
5634 default:
5636 // all other states
5637 // event will be re-added automatically at the end of routine)
5638 } break;
5641 // spell processing not complete, plan event on the next update interval
5642 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5643 return(false); // event not complete
5646 void SpellEvent::Abort(uint64 /*e_time*/)
5648 // oops, the spell we try to do is aborted
5649 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5650 m_Spell->cancel();
5653 bool SpellEvent::IsDeletable() const
5655 return m_Spell->IsDeletable();