Implemented some spell achievements
[getmangos.git] / src / game / Spell.cpp
blob7c073888d7f7393cdcd3562238e694d0ea91a8b1
1 /*
2 * Copyright (C) 2005-2008 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 "Tools.h"
45 #include "LootMgr.h"
46 #include "VMapFactory.h"
47 #include "BattleGround.h"
48 #include "Util.h"
50 #define SPELL_CHANNEL_UPDATE_INTERVAL 1000
52 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
54 bool IsQuestTameSpell(uint32 spellId)
56 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
57 if (!spellproto) return false;
59 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
60 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
63 SpellCastTargets::SpellCastTargets()
65 m_unitTarget = NULL;
66 m_itemTarget = NULL;
67 m_GOTarget = NULL;
69 m_unitTargetGUID = 0;
70 m_GOTargetGUID = 0;
71 m_CorpseTargetGUID = 0;
72 m_itemTargetGUID = 0;
73 m_itemTargetEntry = 0;
75 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
76 m_strTarget = "";
77 m_targetMask = 0;
80 SpellCastTargets::~SpellCastTargets()
84 void SpellCastTargets::setUnitTarget(Unit *target)
86 if (!target)
87 return;
89 m_destX = target->GetPositionX();
90 m_destY = target->GetPositionY();
91 m_destZ = target->GetPositionZ();
92 m_unitTarget = target;
93 m_unitTargetGUID = target->GetGUID();
94 m_targetMask |= TARGET_FLAG_UNIT;
97 void SpellCastTargets::setDestination(float x, float y, float z)
99 m_destX = x;
100 m_destY = y;
101 m_destZ = z;
102 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
105 void SpellCastTargets::setGOTarget(GameObject *target)
107 m_GOTarget = target;
108 m_GOTargetGUID = target->GetGUID();
109 // m_targetMask |= TARGET_FLAG_OBJECT;
112 void SpellCastTargets::setItemTarget(Item* item)
114 if(!item)
115 return;
117 m_itemTarget = item;
118 m_itemTargetGUID = item->GetGUID();
119 m_itemTargetEntry = item->GetEntry();
120 m_targetMask |= TARGET_FLAG_ITEM;
123 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
125 m_CorpseTargetGUID = corpse->GetGUID();
128 void SpellCastTargets::Update(Unit* caster)
130 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
131 m_unitTarget = m_unitTargetGUID ?
132 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
133 NULL;
135 m_itemTarget = NULL;
136 if(caster->GetTypeId()==TYPEID_PLAYER)
138 if(m_targetMask & TARGET_FLAG_ITEM)
139 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
140 else
142 Player* pTrader = ((Player*)caster)->GetTrader();
143 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
144 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
146 if(m_itemTarget)
147 m_itemTargetEntry = m_itemTarget->GetEntry();
151 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
153 if(data->rpos()+4 > data->size())
154 return false;
156 *data >> m_targetMask;
158 if(m_targetMask == TARGET_FLAG_SELF)
160 m_destX = caster->GetPositionX();
161 m_destY = caster->GetPositionY();
162 m_destZ = caster->GetPositionZ();
163 m_unitTarget = caster;
164 m_unitTargetGUID = caster->GetGUID();
165 return true;
168 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
169 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
170 if(!readGUID(*data, m_unitTargetGUID))
171 return false;
173 if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ))
174 if(!readGUID(*data, m_GOTargetGUID))
175 return false;
177 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
178 if(!readGUID(*data, m_itemTargetGUID))
179 return false;
181 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
183 if(data->rpos()+4+4+4 > data->size())
184 return false;
186 *data >> m_srcX >> m_srcY >> m_srcZ;
187 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
188 return false;
191 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
193 if(data->rpos()+4+4+4 > data->size())
194 return false;
196 *data >> m_destX >> m_destY >> m_destZ;
197 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
198 return false;
201 if( m_targetMask & TARGET_FLAG_STRING )
203 if(data->rpos()+1 > data->size())
204 return false;
206 *data >> m_strTarget;
209 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
210 if(!readGUID(*data, m_CorpseTargetGUID))
211 return false;
213 // find real units/GOs
214 Update(caster);
215 return true;
218 void SpellCastTargets::write ( WorldPacket * data )
220 *data << uint32(m_targetMask);
222 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
224 if(m_targetMask & TARGET_FLAG_UNIT)
226 if(m_unitTarget)
227 data->append(m_unitTarget->GetPackGUID());
228 else
229 *data << uint8(0);
231 else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
233 if(m_GOTarget)
234 data->append(m_GOTarget->GetPackGUID());
235 else
236 *data << uint8(0);
238 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
239 data->appendPackGUID(m_CorpseTargetGUID);
240 else
241 *data << uint8(0);
244 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
246 if(m_itemTarget)
247 data->append(m_itemTarget->GetPackGUID());
248 else
249 *data << uint8(0);
252 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
253 *data << m_srcX << m_srcY << m_srcZ;
255 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
256 *data << m_destX << m_destY << m_destZ;
258 if( m_targetMask & TARGET_FLAG_STRING )
259 *data << m_strTarget;
262 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
264 ASSERT( Caster != NULL && info != NULL );
265 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
267 m_spellInfo = info;
268 m_caster = Caster;
269 m_selfContainer = NULL;
270 m_triggeringContainer = triggeringContainer;
271 m_referencedFromCurrentSpell = false;
272 m_executedCurrently = false;
273 m_delayAtDamageCount = 0;
275 m_applyMultiplierMask = 0;
277 // Get data for type of attack
278 switch (m_spellInfo->DmgClass)
280 case SPELL_DAMAGE_CLASS_MELEE:
281 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
282 m_attackType = OFF_ATTACK;
283 else
284 m_attackType = BASE_ATTACK;
285 break;
286 case SPELL_DAMAGE_CLASS_RANGED:
287 m_attackType = RANGED_ATTACK;
288 break;
289 default:
290 // Wands
291 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_WAND)
292 m_attackType = RANGED_ATTACK;
293 else
294 m_attackType = BASE_ATTACK;
295 break;
298 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
300 if(m_attackType == RANGED_ATTACK)
302 // wand case
303 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
305 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
306 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
310 if(originalCasterGUID)
311 m_originalCasterGUID = originalCasterGUID;
312 else
313 m_originalCasterGUID = m_caster->GetGUID();
315 if(m_originalCasterGUID==m_caster->GetGUID())
316 m_originalCaster = m_caster;
317 else
319 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
320 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
323 for(int i=0; i <3; ++i)
324 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
326 m_spellState = SPELL_STATE_NULL;
328 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
329 m_TriggerSpells.clear();
330 m_IsTriggeredSpell = triggered;
331 //m_AreaAura = false;
332 m_CastItem = NULL;
334 unitTarget = NULL;
335 itemTarget = NULL;
336 gameObjTarget = NULL;
337 focusObject = NULL;
338 m_cast_count = 0;
339 m_triggeredByAuraSpell = NULL;
341 //Auto Shot & Shoot
342 if( m_spellInfo->AttributesEx2 == 0x000020 && !triggered )
343 m_autoRepeat = true;
344 else
345 m_autoRepeat = false;
347 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
348 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
349 m_timer = 0; // will set to castime in prepare
351 m_needAliveTargetMask = 0;
353 // determine reflection
354 m_canReflect = false;
356 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
358 for(int j=0;j<3;j++)
360 if (m_spellInfo->Effect[j]==0)
361 continue;
363 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
364 m_canReflect = true;
365 else
366 m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
368 if(m_canReflect)
369 continue;
370 else
371 break;
375 CleanupTargetList();
378 Spell::~Spell()
382 void Spell::FillTargetMap()
384 // TODO: ADD the correct target FILLS!!!!!!
386 for(uint32 i=0;i<3;i++)
388 // not call for empty effect.
389 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
390 if(m_spellInfo->Effect[i]==0)
391 continue;
393 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
394 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
395 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
396 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
397 continue;
399 // TODO: find a way so this is not needed?
400 // for area auras always add caster as target (needed for totems for example)
401 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
402 AddUnitTarget(m_caster, i);
404 std::list<Unit*> tmpUnitMap;
406 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
407 // but need it support in some know cases
408 switch(m_spellInfo->EffectImplicitTargetA[i])
410 case TARGET_ALL_AROUND_CASTER:
411 if( m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_PARTY ||
412 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER ||
413 m_spellInfo->EffectImplicitTargetB[i]==TARGET_RANDOM_RAID_MEMBER )
415 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
417 // Note: this hack with search required until GO casting not implemented
418 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
419 // currently each enemy selected explicitly and self cast damage
420 else if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
422 if(m_targets.getUnitTarget())
423 tmpUnitMap.push_back(m_targets.getUnitTarget());
425 else
427 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
428 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
430 break;
431 case TARGET_TABLE_X_Y_Z_COORDINATES:
432 // Only if target A, for target B (used in teleports) dest select in effect
433 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
434 break;
435 default:
436 switch(m_spellInfo->EffectImplicitTargetB[i])
438 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
439 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
440 break;
441 default:
442 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
443 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
444 break;
446 break;
449 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
450 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
452 // add here custom effects that need default target.
453 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
454 switch(m_spellInfo->Effect[i])
456 case SPELL_EFFECT_DUMMY:
458 switch(m_spellInfo->Id)
460 case 20577: // Cannibalize
462 // non-standard target selection
463 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
464 float max_range = GetSpellMaxRange(srange);
466 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
467 Cell cell(p);
468 cell.data.Part.reserved = ALL_DISTRICT;
469 cell.SetNoCreate();
471 WorldObject* result = NULL;
473 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
474 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(result, u_check);
476 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
477 CellLock<GridReadGuard> cell_lock(cell, p);
478 cell_lock->Visit(cell_lock, grid_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
480 if(!result)
482 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
483 cell_lock->Visit(cell_lock, world_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
486 if(result)
488 switch(result->GetTypeId())
490 case TYPEID_UNIT:
491 case TYPEID_PLAYER:
492 tmpUnitMap.push_back((Unit*)result);
493 break;
494 case TYPEID_CORPSE:
495 m_targets.setCorpseTarget((Corpse*)result);
496 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
497 tmpUnitMap.push_back(owner);
498 break;
501 else
503 // clear cooldown at fail
504 if(m_caster->GetTypeId()==TYPEID_PLAYER)
506 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
508 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
509 data << uint32(m_spellInfo->Id);
510 data << uint64(m_caster->GetGUID());
511 ((Player*)m_caster)->GetSession()->SendPacket(&data);
514 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
515 finish(false);
517 break;
519 default:
520 if(m_targets.getUnitTarget())
521 tmpUnitMap.push_back(m_targets.getUnitTarget());
522 break;
524 break;
526 case SPELL_EFFECT_RESURRECT:
527 case SPELL_EFFECT_PARRY:
528 case SPELL_EFFECT_BLOCK:
529 case SPELL_EFFECT_CREATE_ITEM:
530 case SPELL_EFFECT_TRIGGER_SPELL:
531 case SPELL_EFFECT_TRIGGER_MISSILE:
532 case SPELL_EFFECT_LEARN_SPELL:
533 case SPELL_EFFECT_SKILL_STEP:
534 case SPELL_EFFECT_PROFICIENCY:
535 case SPELL_EFFECT_SUMMON_POSSESSED:
536 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
537 case SPELL_EFFECT_SELF_RESURRECT:
538 case SPELL_EFFECT_REPUTATION:
539 if(m_targets.getUnitTarget())
540 tmpUnitMap.push_back(m_targets.getUnitTarget());
541 break;
542 case SPELL_EFFECT_SUMMON_PLAYER:
543 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
545 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
546 if(target)
547 tmpUnitMap.push_back(target);
549 break;
550 case SPELL_EFFECT_RESURRECT_NEW:
551 if(m_targets.getUnitTarget())
552 tmpUnitMap.push_back(m_targets.getUnitTarget());
553 if(m_targets.getCorpseTargetGUID())
555 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
556 if(corpse)
558 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
559 if(owner)
560 tmpUnitMap.push_back(owner);
563 break;
564 case SPELL_EFFECT_SUMMON:
565 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
567 if(m_targets.getUnitTarget())
568 tmpUnitMap.push_back(m_targets.getUnitTarget());
570 else
571 tmpUnitMap.push_back(m_caster);
572 break;
573 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
574 case SPELL_EFFECT_SUMMON_WILD:
575 case SPELL_EFFECT_SUMMON_GUARDIAN:
576 case SPELL_EFFECT_TRANS_DOOR:
577 case SPELL_EFFECT_ADD_FARSIGHT:
578 case SPELL_EFFECT_APPLY_GLYPH:
579 case SPELL_EFFECT_STUCK:
580 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
581 case SPELL_EFFECT_SUMMON_DEMON:
582 case SPELL_EFFECT_SKILL:
583 tmpUnitMap.push_back(m_caster);
584 break;
585 case SPELL_EFFECT_LEARN_PET_SPELL:
586 if(Pet* pet = m_caster->GetPet())
587 tmpUnitMap.push_back(pet);
588 break;
589 case SPELL_EFFECT_ENCHANT_ITEM:
590 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
591 case SPELL_EFFECT_DISENCHANT:
592 case SPELL_EFFECT_FEED_PET:
593 case SPELL_EFFECT_PROSPECTING:
594 if(m_targets.getItemTarget())
595 AddItemTarget(m_targets.getItemTarget(), i);
596 break;
597 case SPELL_EFFECT_APPLY_AURA:
598 switch(m_spellInfo->EffectApplyAuraName[i])
600 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)
601 case SPELL_AURA_ADD_PCT_MODIFIER:
602 tmpUnitMap.push_back(m_caster);
603 break;
604 default: // apply to target in other case
605 if(m_targets.getUnitTarget())
606 tmpUnitMap.push_back(m_targets.getUnitTarget());
607 break;
609 break;
610 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
611 // AreaAura
612 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
613 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
614 break;
615 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
616 if(m_targets.getUnitTarget())
618 tmpUnitMap.push_back(m_targets.getUnitTarget());
620 else if (m_targets.getCorpseTargetGUID())
622 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
623 if(corpse)
625 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
626 if(owner)
627 tmpUnitMap.push_back(owner);
630 break;
631 default:
632 break;
635 if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
636 m_needAliveTargetMask |= (1<<i);
638 if(m_caster->GetTypeId() == TYPEID_PLAYER)
640 Player *me = (Player*)m_caster;
641 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); itr++)
643 Unit *owner = (*itr)->GetOwner();
644 Unit *u = owner ? owner : (*itr);
645 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
647 me->UpdatePvP(true);
648 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
649 break;
654 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
656 if (!CheckTarget (*itr, i))
658 itr = tmpUnitMap.erase(itr);
659 continue;
661 else
662 ++itr;
665 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
666 AddUnitTarget((*iunit), i);
670 void Spell::CleanupTargetList()
672 m_UniqueTargetInfo.clear();
673 m_UniqueGOTargetInfo.clear();
674 m_UniqueItemInfo.clear();
675 m_countOfHit = 0;
676 m_countOfMiss = 0;
677 m_delayMoment = 0;
680 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
682 if( m_spellInfo->Effect[effIndex]==0 )
683 return;
685 uint64 targetGUID = pVictim->GetGUID();
687 // Lookup target in already in list
688 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
690 if (targetGUID == ihit->targetGUID) // Found in list
692 ihit->effectMask |= 1<<effIndex; // Add only effect mask
693 return;
697 // This is new target calculate data for him
699 // Get spell hit result on target
700 TargetInfo target;
701 target.targetGUID = targetGUID; // Store target GUID
702 target.effectMask = 1<<effIndex; // Store index of effect
703 target.processed = false; // Effects not apply on target
705 // Calculate hit result
706 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
707 if (target.missCondition == SPELL_MISS_NONE)
708 ++m_countOfHit;
709 else
710 ++m_countOfMiss;
712 // Spell have speed - need calculate incoming time
713 if (m_spellInfo->speed > 0.0f)
715 // calculate spell incoming interval
716 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
717 if (dist < 5.0f) dist = 5.0f;
718 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
720 // Calculate minimum incoming time
721 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
722 m_delayMoment = target.timeDelay;
724 else
725 target.timeDelay = 0LL;
727 // If target reflect spell back to caster
728 if (target.missCondition==SPELL_MISS_REFLECT)
730 // Calculate reflected spell result on caster
731 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
733 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
734 target.reflectResult = SPELL_MISS_PARRY;
736 // Increase time interval for reflected spells by 1.5
737 target.timeDelay+=target.timeDelay>>1;
739 else
740 target.reflectResult = SPELL_MISS_NONE;
742 // Add target to list
743 m_UniqueTargetInfo.push_back(target);
746 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
748 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
749 if (unit)
750 AddUnitTarget(unit, effIndex);
753 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
755 if( m_spellInfo->Effect[effIndex]==0 )
756 return;
758 uint64 targetGUID = pVictim->GetGUID();
760 // Lookup target in already in list
761 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
763 if (targetGUID == ihit->targetGUID) // Found in list
765 ihit->effectMask |= 1<<effIndex; // Add only effect mask
766 return;
770 // This is new target calculate data for him
772 GOTargetInfo target;
773 target.targetGUID = targetGUID;
774 target.effectMask = 1<<effIndex;
775 target.processed = false; // Effects not apply on target
777 // Spell have speed - need calculate incoming time
778 if (m_spellInfo->speed > 0.0f)
780 // calculate spell incoming interval
781 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
782 if (dist < 5.0f) dist = 5.0f;
783 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
784 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
785 m_delayMoment = target.timeDelay;
787 else
788 target.timeDelay = 0LL;
790 ++m_countOfHit;
792 // Add target to list
793 m_UniqueGOTargetInfo.push_back(target);
796 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
798 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
799 if (go)
800 AddGOTarget(go, effIndex);
803 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
805 if( m_spellInfo->Effect[effIndex]==0 )
806 return;
808 // Lookup target in already in list
809 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
811 if (pitem == ihit->item) // Found in list
813 ihit->effectMask |= 1<<effIndex; // Add only effect mask
814 return;
818 // This is new target add data
820 ItemTargetInfo target;
821 target.item = pitem;
822 target.effectMask = 1<<effIndex;
823 m_UniqueItemInfo.push_back(target);
826 void Spell::doTriggers(SpellMissInfo missInfo, uint32 damage, SpellSchoolMask damageSchoolMask, uint32 block, uint32 absorb, bool crit)
828 // Do triggers depends from hit result (triggers on hit do in effects)
829 // Set aura states depends from hit result
830 if (missInfo!=SPELL_MISS_NONE)
832 // Miss/dodge/parry/block only for melee based spells
833 // Resist only for magic based spells
834 switch (missInfo)
836 case SPELL_MISS_MISS:
837 if(m_caster->GetTypeId()== TYPEID_PLAYER)
838 ((Player*)m_caster)->UpdateWeaponSkill(BASE_ATTACK);
840 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_MISS, m_spellInfo, m_IsTriggeredSpell);
841 break;
842 case SPELL_MISS_RESIST:
843 m_caster->ProcDamageAndSpell(unitTarget, PROC_FLAG_TARGET_RESISTS, PROC_FLAG_RESIST_SPELL, 0, damageSchoolMask, m_spellInfo, m_IsTriggeredSpell);
844 break;
845 case SPELL_MISS_DODGE:
846 if(unitTarget->GetTypeId() == TYPEID_PLAYER)
847 ((Player*)unitTarget)->UpdateDefense();
849 // Overpower
850 if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARRIOR)
852 ((Player*) m_caster)->AddComboPoints(unitTarget, 1);
853 m_caster->StartReactiveTimer( REACTIVE_OVERPOWER );
856 // Riposte
857 if (unitTarget->getClass() != CLASS_ROGUE)
859 unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
860 unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
863 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_DODGE, m_spellInfo, m_IsTriggeredSpell);
864 break;
865 case SPELL_MISS_PARRY:
866 // Update victim defense ?
867 if(unitTarget->GetTypeId() == TYPEID_PLAYER)
868 ((Player*)unitTarget)->UpdateDefense();
869 // Mongoose bite - set only Counterattack here
870 if (unitTarget->getClass() == CLASS_HUNTER)
872 unitTarget->ModifyAuraState(AURA_STATE_HUNTER_PARRY,true);
873 unitTarget->StartReactiveTimer( REACTIVE_HUNTER_PARRY );
875 else
877 unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
878 unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
880 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_PARRY, m_spellInfo, m_IsTriggeredSpell);
881 break;
882 case SPELL_MISS_BLOCK:
883 unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
884 unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
886 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_BLOCK, m_spellInfo, m_IsTriggeredSpell);
887 break;
888 // Trigger from this events not supported
889 case SPELL_MISS_EVADE:
890 case SPELL_MISS_IMMUNE:
891 case SPELL_MISS_IMMUNE2:
892 case SPELL_MISS_DEFLECT:
893 case SPELL_MISS_ABSORB:
894 // Trigger from reflects need do after get reflect result
895 case SPELL_MISS_REFLECT:
896 break;
897 default:
898 break;
903 void Spell::DoAllEffectOnTarget(TargetInfo *target)
905 if (target->processed) // Check target
906 return;
907 target->processed = true; // Target checked in apply effects procedure
909 // Get mask of effects for target
910 uint32 mask = target->effectMask;
911 if (mask == 0) // No effects
912 return;
914 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
915 if (!unit)
916 return;
918 SpellMissInfo missInfo = target->missCondition;
919 // Need init unitTarget by default unit (can changed in code on reflect)
920 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
921 unitTarget = unit;
923 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
924 DoSpellHitOnUnit(unit, mask);
925 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
927 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
928 DoSpellHitOnUnit(m_caster, mask);
931 // Do triggers only on miss/resist/parry/dodge
932 if (missInfo!=SPELL_MISS_NONE)
933 doTriggers(missInfo);
935 // Call scripted function for AI if this spell is casted upon a creature (except pets)
936 if(IS_CREATURE_GUID(target->targetGUID))
938 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
939 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
940 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
941 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
943 if(((Creature*)unit)->AI())
944 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
948 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
950 if(!unit || !effectMask)
951 return;
953 // Recheck immune (only for delayed spells)
954 if( m_spellInfo->speed && (
955 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo),true) ||
956 unit->IsImmunedToSpell(m_spellInfo,true) ))
958 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
959 return;
962 if (unit->GetTypeId() == TYPEID_PLAYER)
964 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
965 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
968 if(m_caster->GetTypeId() == TYPEID_PLAYER)
970 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
973 if( m_caster != unit )
975 if( !m_caster->IsFriendlyTo(unit) )
977 // for delayed spells ignore not visible explicit target
978 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
980 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
981 return;
984 // exclude Arcane Missiles Dummy Aura aura for now (attack on hit)
985 // TODO: find way to not need this?
986 if(!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE &&
987 m_spellInfo->SpellFamilyFlags & 0x800LL))
989 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
991 if( !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
993 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
994 unit->SetStandState(PLAYER_STATE_NONE);
996 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
997 ((Creature*)unit)->AI()->AttackStart(m_caster);
999 unit->SetInCombatWith(m_caster);
1000 m_caster->SetInCombatWith(unit);
1002 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1004 m_caster->SetContestedPvP(attackedPlayer);
1006 unit->AddThreat(m_caster, 0.0f);
1010 else
1012 // for delayed spells ignore negative spells (after duel end) for friendly targets
1013 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1015 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1016 return;
1019 // assisting case, healing and resurrection
1020 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1021 m_caster->SetContestedPvP();
1022 if( unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
1024 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1025 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1030 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1031 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1032 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1033 // Increase Diminishing on unit, current informations for actually casts will use values above
1034 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1035 unit->IncrDiminishing(m_diminishGroup);
1037 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1039 if (effectMask & (1<<effectNumber))
1041 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1042 if ( m_applyMultiplierMask & (1 << effectNumber) )
1044 // Get multiplier
1045 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1046 // Apply multiplier mods
1047 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1048 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1049 m_damageMultipliers[effectNumber] *= multiplier;
1055 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1057 if (target->processed) // Check target
1058 return;
1059 target->processed = true; // Target checked in apply effects procedure
1061 uint32 effectMask = target->effectMask;
1062 if(!effectMask)
1063 return;
1065 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1066 if(!go)
1067 return;
1069 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1070 if (effectMask & (1<<effectNumber))
1071 HandleEffects(NULL,NULL,go,effectNumber);
1073 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1074 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1075 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1076 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1079 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1081 uint32 effectMask = target->effectMask;
1082 if(!target->item || !effectMask)
1083 return;
1085 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1086 if (effectMask & (1<<effectNumber))
1087 HandleEffects(NULL, target->item, NULL, effectNumber);
1090 bool Spell::IsAliveUnitPresentInTargetList()
1092 // Not need check return true
1093 if (m_needAliveTargetMask == 0)
1094 return true;
1096 uint8 needAliveTargetMask = m_needAliveTargetMask;
1098 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1100 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1102 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1104 if (unit && unit->isAlive())
1105 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1109 // is all effects from m_needAliveTargetMask have alive targets
1110 return needAliveTargetMask==0;
1113 // Helper for Chain Healing
1114 // Spell target first
1115 // Raidmates then descending by injury suffered (MaxHealth - Health)
1116 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1117 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1119 const Unit* MainTarget;
1120 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1121 // functor for operator ">"
1122 bool operator()(Unit const* _Left, Unit const* _Right) const
1124 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1126 int32 ChainHealingHash(Unit const* Target) const
1128 if (Target == MainTarget)
1129 return 0;
1130 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1131 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1133 if (Target->GetHealth() == Target->GetMaxHealth())
1134 return 40000;
1135 else
1136 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1138 else
1139 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1143 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1145 public:
1146 const Unit* MainTarget;
1147 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1149 bool operator()(const Unit* Target)
1151 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1155 // Helper for targets nearest to the spell target
1156 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1157 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1159 const Unit* MainTarget;
1160 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1161 // functor for operator ">"
1162 bool operator()(const Unit* _Left, const Unit* _Right) const
1164 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1168 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1170 float radius;
1171 if (m_spellInfo->EffectRadiusIndex[i])
1172 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1173 else
1174 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1176 if(m_originalCaster)
1177 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1178 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1180 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1181 if(m_originalCaster)
1182 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1183 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1185 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1186 switch(cur)
1188 case TARGET_TOTEM_EARTH:
1189 case TARGET_TOTEM_WATER:
1190 case TARGET_TOTEM_AIR:
1191 case TARGET_TOTEM_FIRE:
1192 case TARGET_SELF:
1193 case TARGET_SELF2:
1194 case TARGET_DYNAMIC_OBJECT:
1195 case TARGET_AREAEFFECT_CUSTOM:
1196 case TARGET_AREAEFFECT_CUSTOM_2:
1197 case TARGET_SUMMON:
1199 TagUnitMap.push_back(m_caster);
1200 break;
1202 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1204 m_targets.m_targetMask = 0;
1205 unMaxTargets = EffectChainTarget;
1206 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1208 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1209 Cell cell(p);
1210 cell.data.Part.reserved = ALL_DISTRICT;
1211 cell.SetNoCreate();
1213 std::list<Unit *> tempUnitMap;
1216 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1217 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1219 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1220 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1222 CellLock<GridReadGuard> cell_lock(cell, p);
1223 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1224 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1227 if(tempUnitMap.empty())
1228 break;
1230 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1232 //Now to get us a random target that's in the initial range of the spell
1233 uint32 t = 0;
1234 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1235 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1236 ++t, ++itr;
1238 if(!t)
1239 break;
1241 itr = tempUnitMap.begin();
1242 std::advance(itr, rand()%t);
1243 Unit *pUnitTarget = *itr;
1244 TagUnitMap.push_back(pUnitTarget);
1246 tempUnitMap.erase(itr);
1248 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1250 t = unMaxTargets - 1;
1251 Unit *prev = pUnitTarget;
1252 std::list<Unit*>::iterator next = tempUnitMap.begin();
1254 while(t && next != tempUnitMap.end() )
1256 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1257 break;
1259 if(!prev->IsWithinLOSInMap(*next))
1261 ++next;
1262 continue;
1265 prev = *next;
1266 TagUnitMap.push_back(prev);
1267 tempUnitMap.erase(next);
1268 tempUnitMap.sort(TargetDistanceOrder(prev));
1269 next = tempUnitMap.begin();
1271 --t;
1273 }break;
1274 case TARGET_PET:
1276 Pet* tmpUnit = m_caster->GetPet();
1277 if (!tmpUnit) break;
1278 TagUnitMap.push_back(tmpUnit);
1279 break;
1281 case TARGET_CHAIN_DAMAGE:
1283 if (EffectChainTarget <= 1)
1285 Unit* pUnitTarget = SelectMagnetTarget();
1286 if(pUnitTarget)
1287 TagUnitMap.push_back(pUnitTarget);
1289 else
1291 Unit* pUnitTarget = m_targets.getUnitTarget();
1292 if(!pUnitTarget)
1293 break;
1295 unMaxTargets = EffectChainTarget;
1297 float max_range;
1298 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1299 max_range = radius; //
1300 else
1301 //FIXME: This very like horrible hack and wrong for most spells
1302 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1304 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1305 Cell cell(p);
1306 cell.data.Part.reserved = ALL_DISTRICT;
1307 cell.SetNoCreate();
1309 Unit* originalCaster = GetOriginalCaster();
1310 if(originalCaster)
1312 std::list<Unit *> tempUnitMap;
1315 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1316 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1318 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1319 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1321 CellLock<GridReadGuard> cell_lock(cell, p);
1322 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1323 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1326 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1328 if(tempUnitMap.empty())
1329 break;
1331 if(*tempUnitMap.begin() == pUnitTarget)
1332 tempUnitMap.erase(tempUnitMap.begin());
1334 TagUnitMap.push_back(pUnitTarget);
1335 uint32 t = unMaxTargets - 1;
1336 Unit *prev = pUnitTarget;
1337 std::list<Unit*>::iterator next = tempUnitMap.begin();
1339 while(t && next != tempUnitMap.end() )
1341 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1342 break;
1344 if(!prev->IsWithinLOSInMap(*next))
1346 ++next;
1347 continue;
1350 prev = *next;
1351 TagUnitMap.push_back(prev);
1352 tempUnitMap.erase(next);
1353 tempUnitMap.sort(TargetDistanceOrder(prev));
1354 next = tempUnitMap.begin();
1356 --t;
1360 }break;
1361 case TARGET_ALL_ENEMY_IN_AREA:
1363 }break;
1364 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1366 // targets the ground, not the units in the area
1367 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1369 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1370 Cell cell(p);
1371 cell.data.Part.reserved = ALL_DISTRICT;
1372 cell.SetNoCreate();
1374 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1376 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1377 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1379 CellLock<GridReadGuard> cell_lock(cell, p);
1380 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1381 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1383 // exclude caster (this can be important if this not original caster)
1384 TagUnitMap.remove(m_caster);
1386 }break;
1387 case TARGET_DUELVSPLAYER_COORDINATES:
1389 if(Unit* currentTarget = m_targets.getUnitTarget())
1391 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1392 TagUnitMap.push_back(currentTarget);
1394 }break;
1395 case TARGET_ALL_PARTY_AROUND_CASTER:
1396 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1397 case TARGET_ALL_PARTY:
1399 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1400 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1402 if(pGroup)
1404 uint8 subgroup = pTarget->GetSubGroup();
1406 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1408 Player* Target = itr->getSource();
1410 // IsHostileTo check duel and controlled by enemy
1411 if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1413 if( m_caster->IsWithinDistInMap(Target, radius) )
1414 TagUnitMap.push_back(Target);
1416 if(Pet* pet = Target->GetPet())
1417 if( m_caster->IsWithinDistInMap(pet, radius) )
1418 TagUnitMap.push_back(pet);
1422 else
1424 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1425 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1426 TagUnitMap.push_back(ownerOrSelf);
1427 if(Pet* pet = ownerOrSelf->GetPet())
1428 if( m_caster->IsWithinDistInMap(pet, radius) )
1429 TagUnitMap.push_back(pet);
1431 }break;
1432 case TARGET_RANDOM_RAID_MEMBER:
1434 if (m_caster->GetTypeId() == TYPEID_PLAYER)
1435 if(Player* target = ((Player*)m_caster)->GetNextRandomRaidMember(radius))
1436 TagUnitMap.push_back(target);
1437 }break;
1438 case TARGET_SINGLE_FRIEND:
1439 case TARGET_SINGLE_FRIEND_2:
1441 if(m_targets.getUnitTarget())
1442 TagUnitMap.push_back(m_targets.getUnitTarget());
1443 }break;
1444 case TARGET_NONCOMBAT_PET:
1446 if(Unit* target = m_targets.getUnitTarget())
1447 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1448 TagUnitMap.push_back(target);
1449 }break;
1450 case TARGET_ALL_AROUND_CASTER:
1452 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1453 Cell cell(p);
1454 cell.data.Part.reserved = ALL_DISTRICT;
1455 cell.SetNoCreate();
1457 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1459 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1460 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1462 CellLock<GridReadGuard> cell_lock(cell, p);
1463 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1464 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1465 }break;
1466 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1468 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1469 Cell cell(p);
1470 cell.data.Part.reserved = ALL_DISTRICT;
1471 cell.SetNoCreate();
1473 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1475 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1476 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1478 CellLock<GridReadGuard> cell_lock(cell, p);
1479 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1480 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1481 }break;
1482 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1484 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1485 Cell cell(p);
1486 cell.data.Part.reserved = ALL_DISTRICT;
1487 cell.SetNoCreate();
1489 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1491 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1492 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1494 CellLock<GridReadGuard> cell_lock(cell, p);
1495 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1496 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1497 }break;
1498 // 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..)
1499 case TARGET_SINGLE_PARTY:
1501 Unit *target = m_targets.getUnitTarget();
1502 // Thoses spells apparently can't be casted on the caster.
1503 if( target && target != m_caster)
1505 // Can only be casted on group's members or its pets
1506 Group *pGroup = NULL;
1508 Unit* owner = m_caster->GetCharmerOrOwner();
1509 Unit *targetOwner = target->GetCharmerOrOwner();
1510 if(owner)
1512 if(owner->GetTypeId() == TYPEID_PLAYER)
1514 if( target == owner )
1516 TagUnitMap.push_back(target);
1517 break;
1519 pGroup = ((Player*)owner)->GetGroup();
1522 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1524 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1526 TagUnitMap.push_back(target);
1527 break;
1529 pGroup = ((Player*)m_caster)->GetGroup();
1532 if(pGroup)
1534 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1535 if(targetOwner)
1537 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1538 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1539 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1540 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1542 TagUnitMap.push_back(target);
1545 // 1Our target can be a player who is on our group
1546 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1548 TagUnitMap.push_back(target);
1552 }break;
1553 case TARGET_GAMEOBJECT:
1555 if(m_targets.getGOTarget())
1556 AddGOTarget(m_targets.getGOTarget(), i);
1557 }break;
1558 case TARGET_IN_FRONT_OF_CASTER:
1560 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1561 Cell cell(p);
1562 cell.data.Part.reserved = ALL_DISTRICT;
1563 cell.SetNoCreate();
1565 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1566 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1568 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1569 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1571 CellLock<GridReadGuard> cell_lock(cell, p);
1572 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1573 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1574 }break;
1575 case TARGET_DUELVSPLAYER:
1577 Unit *target = m_targets.getUnitTarget();
1578 if(target)
1580 if(m_caster->IsFriendlyTo(target))
1582 TagUnitMap.push_back(target);
1584 else
1586 Unit* pUnitTarget = SelectMagnetTarget();
1587 if(pUnitTarget)
1588 TagUnitMap.push_back(pUnitTarget);
1591 }break;
1592 case TARGET_GAMEOBJECT_ITEM:
1594 if(m_targets.getGOTargetGUID())
1595 AddGOTarget(m_targets.getGOTarget(), i);
1596 else if(m_targets.getItemTarget())
1597 AddItemTarget(m_targets.getItemTarget(), i);
1598 break;
1600 case TARGET_MASTER:
1602 if(Unit* owner = m_caster->GetCharmerOrOwner())
1603 TagUnitMap.push_back(owner);
1604 break;
1606 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1608 // targets the ground, not the units in the area
1609 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1611 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1612 Cell cell(p);
1613 cell.data.Part.reserved = ALL_DISTRICT;
1614 cell.SetNoCreate();
1616 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1618 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1619 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1621 CellLock<GridReadGuard> cell_lock(cell, p);
1622 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1623 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1625 }break;
1626 case TARGET_MINION:
1628 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1629 TagUnitMap.push_back(m_caster);
1630 }break;
1631 case TARGET_SINGLE_ENEMY:
1633 Unit* pUnitTarget = SelectMagnetTarget();
1634 if(pUnitTarget)
1635 TagUnitMap.push_back(pUnitTarget);
1636 }break;
1637 case TARGET_AREAEFFECT_PARTY:
1639 Unit* owner = m_caster->GetCharmerOrOwner();
1640 Player *pTarget = NULL;
1642 if(owner)
1644 TagUnitMap.push_back(m_caster);
1645 if(owner->GetTypeId() == TYPEID_PLAYER)
1646 pTarget = (Player*)owner;
1648 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1650 if(Unit* target = m_targets.getUnitTarget())
1652 if( target->GetTypeId() != TYPEID_PLAYER)
1654 if(((Creature*)target)->isPet())
1656 Unit *targetOwner = target->GetOwner();
1657 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1658 pTarget = (Player*)targetOwner;
1661 else
1662 pTarget = (Player*)target;
1666 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1668 if(pGroup)
1670 uint8 subgroup = pTarget->GetSubGroup();
1672 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1674 Player* Target = itr->getSource();
1676 // IsHostileTo check duel and controlled by enemy
1677 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1679 if( pTarget->IsWithinDistInMap(Target, radius) )
1680 TagUnitMap.push_back(Target);
1682 if(Pet* pet = Target->GetPet())
1683 if( pTarget->IsWithinDistInMap(pet, radius) )
1684 TagUnitMap.push_back(pet);
1688 else if (owner)
1690 if(m_caster->IsWithinDistInMap(owner, radius))
1691 TagUnitMap.push_back(owner);
1693 else if(pTarget)
1695 TagUnitMap.push_back(pTarget);
1697 if(Pet* pet = pTarget->GetPet())
1698 if( m_caster->IsWithinDistInMap(pet, radius) )
1699 TagUnitMap.push_back(pet);
1702 }break;
1703 case TARGET_SCRIPT:
1705 if(m_targets.getUnitTarget())
1706 TagUnitMap.push_back(m_targets.getUnitTarget());
1707 if(m_targets.getItemTarget())
1708 AddItemTarget(m_targets.getItemTarget(), i);
1709 }break;
1710 case TARGET_SELF_FISHING:
1712 TagUnitMap.push_back(m_caster);
1713 }break;
1714 case TARGET_CHAIN_HEAL:
1716 Unit* pUnitTarget = m_targets.getUnitTarget();
1717 if(!pUnitTarget)
1718 break;
1720 if (EffectChainTarget <= 1)
1721 TagUnitMap.push_back(pUnitTarget);
1722 else
1724 unMaxTargets = EffectChainTarget;
1725 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1727 std::list<Unit *> tempUnitMap;
1730 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1731 Cell cell(p);
1732 cell.data.Part.reserved = ALL_DISTRICT;
1733 cell.SetNoCreate();
1735 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1737 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1738 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1740 CellLock<GridReadGuard> cell_lock(cell, p);
1741 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1742 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1746 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1747 tempUnitMap.push_front(m_caster);
1749 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1751 if(tempUnitMap.empty())
1752 break;
1754 if(*tempUnitMap.begin() == pUnitTarget)
1755 tempUnitMap.erase(tempUnitMap.begin());
1757 TagUnitMap.push_back(pUnitTarget);
1758 uint32 t = unMaxTargets - 1;
1759 Unit *prev = pUnitTarget;
1760 std::list<Unit*>::iterator next = tempUnitMap.begin();
1762 while(t && next != tempUnitMap.end() )
1764 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1765 break;
1767 if(!prev->IsWithinLOSInMap(*next))
1769 ++next;
1770 continue;
1773 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1775 next = tempUnitMap.erase(next);
1776 continue;
1779 prev = *next;
1780 TagUnitMap.push_back(prev);
1781 tempUnitMap.erase(next);
1782 tempUnitMap.sort(TargetDistanceOrder(prev));
1783 next = tempUnitMap.begin();
1785 --t;
1788 }break;
1789 case TARGET_CURRENT_ENEMY_COORDINATES:
1791 Unit* currentTarget = m_targets.getUnitTarget();
1792 if(currentTarget)
1794 TagUnitMap.push_back(currentTarget);
1795 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1796 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1798 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1799 Cell cell(p);
1800 cell.data.Part.reserved = ALL_DISTRICT;
1801 cell.SetNoCreate();
1802 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1803 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1804 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1805 CellLock<GridReadGuard> cell_lock(cell, p);
1806 cell_lock->Visit(cell_lock, world_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1807 cell_lock->Visit(cell_lock, grid_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1810 }break;
1811 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1813 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1814 ? (Player*)m_targets.getUnitTarget() : NULL;
1816 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1817 if(pGroup)
1819 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1821 Player* Target = itr->getSource();
1823 // IsHostileTo check duel and controlled by enemy
1824 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1825 targetPlayer->getClass() == Target->getClass() &&
1826 !m_caster->IsHostileTo(Target) )
1828 TagUnitMap.push_back(Target);
1832 else if(m_targets.getUnitTarget())
1833 TagUnitMap.push_back(m_targets.getUnitTarget());
1834 break;
1836 case TARGET_TABLE_X_Y_Z_COORDINATES:
1838 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
1839 if(st)
1841 if (st->target_mapId == m_caster->GetMapId())
1842 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1844 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
1845 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
1847 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1848 Cell cell(p);
1849 cell.data.Part.reserved = ALL_DISTRICT;
1850 cell.SetNoCreate();
1852 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1853 // Select friendly targets for positive effect
1854 if (IsPositiveEffect(m_spellInfo->Id, i))
1855 targetB = SPELL_TARGETS_FRIENDLY;
1857 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
1859 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1860 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1862 CellLock<GridReadGuard> cell_lock(cell, p);
1863 cell_lock->Visit(cell_lock, world_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1864 cell_lock->Visit(cell_lock, grid_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1867 else
1868 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1869 }break;
1870 case TARGET_BEHIND_VICTIM:
1872 Unit *pTarget = m_caster->getVictim();
1873 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
1874 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
1876 if(pTarget)
1878 float _target_x, _target_y, _target_z;
1879 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
1880 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
1881 m_targets.setDestination(_target_x, _target_y, _target_z);
1883 }break;
1884 default:
1885 break;
1888 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
1890 // make sure one unit is always removed per iteration
1891 uint32 removed_utarget = 0;
1892 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
1894 next = itr;
1895 ++next;
1896 if (!*itr) continue;
1897 if ((*itr) == m_targets.getUnitTarget())
1899 TagUnitMap.erase(itr);
1900 removed_utarget = 1;
1901 // break;
1904 // remove random units from the map
1905 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
1907 uint32 poz = urand(0, TagUnitMap.size()-1);
1908 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
1910 if (!*itr) continue;
1911 if (!poz)
1913 TagUnitMap.erase(itr);
1914 break;
1918 // the player's target will always be added to the map
1919 if (removed_utarget && m_targets.getUnitTarget())
1920 TagUnitMap.push_back(m_targets.getUnitTarget());
1924 void Spell::prepare(SpellCastTargets * targets, Aura* triggeredByAura)
1926 m_targets = *targets;
1928 m_spellState = SPELL_STATE_PREPARING;
1930 m_castPositionX = m_caster->GetPositionX();
1931 m_castPositionY = m_caster->GetPositionY();
1932 m_castPositionZ = m_caster->GetPositionZ();
1933 m_castOrientation = m_caster->GetOrientation();
1935 if(triggeredByAura)
1936 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
1938 // create and add update event for this spell
1939 SpellEvent* Event = new SpellEvent(this);
1940 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
1942 //Prevent casting at cast another spell (ServerSide check)
1943 if(m_caster->IsNonMeleeSpellCasted(false, true) && m_cast_count)
1945 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
1946 finish(false);
1947 return;
1950 // Fill cost data
1951 m_powerCost = CalculatePowerCost();
1953 uint8 result = CanCast(true);
1954 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
1956 if(triggeredByAura)
1958 SendChannelUpdate(0);
1959 triggeredByAura->SetAuraDuration(0);
1961 SendCastResult(result);
1962 finish(false);
1963 return;
1966 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
1967 m_casttime = GetSpellCastTime(m_spellInfo, this);
1969 // set timer base at cast time
1970 ReSetTimer();
1972 // stealth must be removed at cast starting (at show channel bar)
1973 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
1974 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
1976 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1977 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
1980 if(m_IsTriggeredSpell)
1981 cast(true);
1982 else
1984 m_caster->SetCurrentCastedSpell( this );
1985 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
1986 SendSpellStart();
1990 void Spell::cancel()
1992 if(m_spellState == SPELL_STATE_FINISHED)
1993 return;
1995 m_autoRepeat = false;
1996 switch (m_spellState)
1998 case SPELL_STATE_PREPARING:
1999 case SPELL_STATE_DELAYED:
2001 SendInterrupted(0);
2002 SendCastResult(SPELL_FAILED_INTERRUPTED);
2003 } break;
2005 case SPELL_STATE_CASTING:
2007 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2009 if( ihit->missCondition == SPELL_MISS_NONE )
2011 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2012 if( unit && unit->isAlive() )
2013 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2017 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2018 SendChannelUpdate(0);
2019 SendInterrupted(0);
2020 SendCastResult(SPELL_FAILED_INTERRUPTED);
2021 } break;
2023 default:
2025 } break;
2028 finish(false);
2029 m_caster->RemoveDynObject(m_spellInfo->Id);
2030 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2033 void Spell::cast(bool skipCheck)
2035 SetExecutedCurrently(true);
2037 uint8 castResult = 0;
2039 // update pointers base at GUIDs to prevent access to non-existed already object
2040 UpdatePointers();
2042 // cancel at lost main target unit
2043 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2045 cancel();
2046 SetExecutedCurrently(false);
2047 return;
2050 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2051 m_caster->SetInFront(m_targets.getUnitTarget());
2053 castResult = CheckPower();
2054 if(castResult != 0)
2056 SendCastResult(castResult);
2057 finish(false);
2058 SetExecutedCurrently(false);
2059 return;
2062 // triggered cast called from Spell::prepare where it was already checked
2063 if(!skipCheck)
2065 castResult = CanCast(false);
2066 if(castResult != 0)
2068 SendCastResult(castResult);
2069 finish(false);
2070 SetExecutedCurrently(false);
2071 return;
2075 // Conflagrate - consumes immolate
2076 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2078 // for caster applied auras only
2079 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2080 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2082 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2083 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2085 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2086 break;
2091 // traded items have trade slot instead of guid in m_itemTargetGUID
2092 // set to real guid to be sent later to the client
2093 m_targets.updateTradeSlotItem();
2095 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2097 if (m_CastItem)
2098 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2100 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2103 // CAST SPELL
2104 SendSpellCooldown();
2106 TakePower();
2107 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2108 FillTargetMap();
2110 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2112 SetExecutedCurrently(false);
2113 return;
2116 SendCastResult(castResult);
2117 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2119 // Pass cast spell event to handler (not send triggered by aura spells)
2120 if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE && m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_RANGED && !m_triggeredByAuraSpell)
2122 m_caster->ProcDamageAndSpell(m_targets.getUnitTarget(), PROC_FLAG_CAST_SPELL, PROC_FLAG_NONE, 0, SPELL_SCHOOL_MASK_NONE, m_spellInfo, m_IsTriggeredSpell);
2124 // update pointers base at GUIDs to prevent access to non-existed already object
2125 UpdatePointers(); // pointers can be invalidate at triggered spell casting
2128 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2129 if (m_spellInfo->speed > 0.0f)
2132 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2133 // in case delayed spell remove item at cast delay start
2134 TakeCastItem();
2136 // Okay, maps created, now prepare flags
2137 m_immediateHandled = false;
2138 m_spellState = SPELL_STATE_DELAYED;
2139 SetDelayStart(0);
2141 else
2143 // Immediate spell, no big deal
2144 handle_immediate();
2147 SetExecutedCurrently(false);
2150 void Spell::handle_immediate()
2152 // start channeling if applicable
2153 if(IsChanneledSpell(m_spellInfo))
2155 m_spellState = SPELL_STATE_CASTING;
2156 SendChannelStart(GetSpellDuration(m_spellInfo));
2159 // process immediate effects (items, ground, etc.) also initialize some variables
2160 _handle_immediate_phase();
2162 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2163 DoAllEffectOnTarget(&(*ihit));
2165 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2166 DoAllEffectOnTarget(&(*ihit));
2168 // spell is finished, perform some last features of the spell here
2169 _handle_finish_phase();
2171 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2172 TakeCastItem();
2174 if(m_spellState != SPELL_STATE_CASTING)
2175 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2178 uint64 Spell::handle_delayed(uint64 t_offset)
2180 uint64 next_time = 0;
2182 if (!m_immediateHandled)
2184 _handle_immediate_phase();
2185 m_immediateHandled = true;
2188 // 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)
2189 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2191 if (ihit->processed == false)
2193 if ( ihit->timeDelay <= t_offset )
2194 DoAllEffectOnTarget(&(*ihit));
2195 else if( next_time == 0 || ihit->timeDelay < next_time )
2196 next_time = ihit->timeDelay;
2200 // now recheck gameobject targeting correctness
2201 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2203 if (ighit->processed == false)
2205 if ( ighit->timeDelay <= t_offset )
2206 DoAllEffectOnTarget(&(*ighit));
2207 else if( next_time == 0 || ighit->timeDelay < next_time )
2208 next_time = ighit->timeDelay;
2211 // All targets passed - need finish phase
2212 if (next_time == 0)
2214 // spell is finished, perform some last features of the spell here
2215 _handle_finish_phase();
2217 finish(true); // successfully finish spell cast
2219 // return zero, spell is finished now
2220 return 0;
2222 else
2224 // spell is unfinished, return next execution time
2225 return next_time;
2229 void Spell::_handle_immediate_phase()
2231 // handle some immediate features of the spell here
2232 HandleThreatSpells(m_spellInfo->Id);
2234 m_needSpellLog = IsNeedSendToClient();
2235 for(uint32 j = 0;j<3;j++)
2237 if(m_spellInfo->Effect[j]==0)
2238 continue;
2240 // apply Send Event effect to ground in case empty target lists
2241 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2243 HandleEffects(NULL,NULL,NULL, j);
2244 continue;
2247 // Don't do spell log, if is school damage spell
2248 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2249 m_needSpellLog = false;
2251 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2252 if(m_originalCaster)
2253 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2254 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2256 // initialize multipliers
2257 m_damageMultipliers[j] = 1.0f;
2258 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2259 (EffectChainTarget > 1) )
2260 m_applyMultiplierMask |= 1 << j;
2263 // initialize Diminishing Returns Data
2264 m_diminishLevel = DIMINISHING_LEVEL_1;
2265 m_diminishGroup = DIMINISHING_NONE;
2267 // process items
2268 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2269 DoAllEffectOnTarget(&(*ihit));
2271 // process ground
2272 for(uint32 j = 0;j<3;j++)
2274 // persistent area auras target only the ground
2275 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2276 HandleEffects(NULL,NULL,NULL, j);
2280 void Spell::_handle_finish_phase()
2282 // spell log
2283 if(m_needSpellLog)
2284 SendLogExecute();
2287 void Spell::SendSpellCooldown()
2289 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2290 return;
2292 Player* _player = (Player*)m_caster;
2293 // Add cooldown for max (disable spell)
2294 // Cooldown started on SendCooldownEvent call
2295 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2297 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2298 return;
2301 // init cooldown values
2302 uint32 cat = 0;
2303 int32 rec = -1;
2304 int32 catrec = -1;
2306 // some special item spells without correct cooldown in SpellInfo
2307 // cooldown information stored in item prototype
2308 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2310 if(m_CastItem)
2312 ItemPrototype const* proto = m_CastItem->GetProto();
2313 if(proto)
2315 for(int idx = 0; idx < 5; ++idx)
2317 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2319 cat = proto->Spells[idx].SpellCategory;
2320 rec = proto->Spells[idx].SpellCooldown;
2321 catrec = proto->Spells[idx].SpellCategoryCooldown;
2322 break;
2328 // if no cooldown found above then base at DBC data
2329 if(rec < 0 && catrec < 0)
2331 cat = m_spellInfo->Category;
2332 rec = m_spellInfo->RecoveryTime;
2333 catrec = m_spellInfo->CategoryRecoveryTime;
2336 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2337 // prevent 0 cooldowns set by another way
2338 if (rec <= 0 && catrec <= 0 && (cat == 76 || cat == 351))
2339 rec = _player->GetAttackTime(RANGED_ATTACK);
2341 // Now we have cooldown data (if found any), time to apply mods
2342 if(rec > 0)
2343 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2345 if(catrec > 0)
2346 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2348 // replace negative cooldowns by 0
2349 if (rec < 0) rec = 0;
2350 if (catrec < 0) catrec = 0;
2352 // no cooldown after applying spell mods
2353 if( rec == 0 && catrec == 0)
2354 return;
2356 time_t curTime = time(NULL);
2358 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2359 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2361 // self spell cooldown
2362 if(recTime > 0)
2363 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2365 // category spells
2366 if (catrec > 0)
2368 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2369 if(i_scstore != sSpellCategoryStore.end())
2371 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2373 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2374 continue;
2376 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2382 void Spell::update(uint32 difftime)
2384 // update pointers based at it's GUIDs
2385 UpdatePointers();
2387 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2389 cancel();
2390 return;
2393 // check if the player caster has moved before the spell finished
2394 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2395 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2396 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2398 // always cancel for channeled spells
2399 if( m_spellState == SPELL_STATE_CASTING )
2400 cancel();
2401 // don't cancel for melee, autorepeat, triggered and instant spells
2402 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2403 cancel();
2406 switch(m_spellState)
2408 case SPELL_STATE_PREPARING:
2410 if(m_timer)
2412 if(difftime >= m_timer)
2413 m_timer = 0;
2414 else
2415 m_timer -= difftime;
2418 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2419 cast();
2420 } break;
2421 case SPELL_STATE_CASTING:
2423 if(m_timer > 0)
2425 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2427 // check if player has jumped before the channeling finished
2428 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2429 cancel();
2431 // check for incapacitating player states
2432 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2433 cancel();
2435 // check if player has turned if flag is set
2436 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2437 cancel();
2440 // check if there are alive targets left
2441 if (!IsAliveUnitPresentInTargetList())
2443 SendChannelUpdate(0);
2444 finish();
2447 if(difftime >= m_timer)
2448 m_timer = 0;
2449 else
2450 m_timer -= difftime;
2453 if(m_timer == 0)
2455 SendChannelUpdate(0);
2457 // channeled spell processed independently for quest targeting
2458 // cast at creature (or GO) quest objectives update at successful cast channel finished
2459 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2460 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2462 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2464 TargetInfo* target = &*ihit;
2465 if(!IS_CREATURE_GUID(target->targetGUID))
2466 continue;
2468 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2469 if (unit==NULL)
2470 continue;
2472 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2475 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2477 GOTargetInfo* target = &*ihit;
2479 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2480 if(!go)
2481 continue;
2483 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2487 finish();
2489 } break;
2490 default:
2492 }break;
2496 void Spell::finish(bool ok)
2498 if(!m_caster)
2499 return;
2501 if(m_spellState == SPELL_STATE_FINISHED)
2502 return;
2504 m_spellState = SPELL_STATE_FINISHED;
2506 //remove spell mods
2507 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2508 ((Player*)m_caster)->RemoveSpellMods(this);
2510 // other code related only to successfully finished spells
2511 if(!ok)
2512 return;
2514 //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2515 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2516 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2518 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2519 uint32 auraSpellIdx = (*i)->GetEffIndex();
2520 if (IsAffectedBy(auraSpellInfo, auraSpellIdx))
2522 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2523 if( ihit->effectMask & (1<<auraSpellIdx) )
2525 // check m_caster->GetGUID() let load auras at login and speedup most often case
2526 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2527 if (unit && unit->isAlive())
2529 // Calculate chance at that moment (can be depend for example from combo points)
2530 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2532 if(roll_chance_i(chance))
2533 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2539 if (IsMeleeAttackResetSpell())
2541 m_caster->resetAttackTimer(BASE_ATTACK);
2542 if(m_caster->haveOffhandWeapon())
2543 m_caster->resetAttackTimer(OFF_ATTACK);
2546 /*if (IsRangedAttackResetSpell())
2547 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2549 // Clear combo at finish state
2550 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2551 ((Player*)m_caster)->ClearComboPoints();
2553 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2554 if(!m_TriggerSpells.empty())
2555 TriggerSpell();
2557 // Stop Attack for some spells
2558 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2559 m_caster->AttackStop();
2562 void Spell::SendCastResult(uint8 result)
2564 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2565 return;
2567 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2568 return;
2570 if(result != 0)
2572 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2573 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2574 data << uint32(m_spellInfo->Id);
2575 data << uint8(result); // problem
2576 switch (result)
2578 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2579 data << uint32(m_spellInfo->RequiresSpellFocus);
2580 break;
2581 case SPELL_FAILED_REQUIRES_AREA:
2582 // hardcode areas limitation case
2583 if( m_spellInfo->Id==41618 || m_spellInfo->Id==41620 )
2584 data << uint32(3842);
2585 else if( m_spellInfo->Id==41617 || m_spellInfo->Id==41619 )
2586 data << uint32(3905);
2587 // normal case
2588 else
2589 data << uint32(m_spellInfo->AreaId);
2590 break;
2591 case SPELL_FAILED_TOTEMS:
2592 if(m_spellInfo->Totem[0])
2593 data << uint32(m_spellInfo->Totem[0]);
2594 if(m_spellInfo->Totem[1])
2595 data << uint32(m_spellInfo->Totem[1]);
2596 break;
2597 case SPELL_FAILED_TOTEM_CATEGORY:
2598 if(m_spellInfo->TotemCategory[0])
2599 data << uint32(m_spellInfo->TotemCategory[0]);
2600 if(m_spellInfo->TotemCategory[1])
2601 data << uint32(m_spellInfo->TotemCategory[1]);
2602 break;
2603 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2604 data << uint32(m_spellInfo->EquippedItemClass);
2605 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2606 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2607 break;
2609 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2611 /*else
2613 WorldPacket data(SMSG_CLEAR_EXTRA_AURA_INFO_OBSOLETE, (8+4));
2614 data.append(m_caster->GetPackGUID());
2615 data << uint32(m_spellInfo->Id);
2616 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2620 void Spell::SendSpellStart()
2622 if(!IsNeedSendToClient())
2623 return;
2625 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2627 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2628 if(IsRangedSpell())
2629 castFlags |= CAST_FLAG_AMMO;
2631 Unit *target;
2632 if(!m_targets.getUnitTarget())
2633 target = m_caster;
2634 else
2635 target = m_targets.getUnitTarget();
2637 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2638 if(m_CastItem)
2639 data.append(m_CastItem->GetPackGUID());
2640 else
2641 data.append(m_caster->GetPackGUID());
2643 data.append(m_caster->GetPackGUID());
2644 data << uint8(m_cast_count); // pending spell cast?
2645 data << uint32(m_spellInfo->Id);
2646 data << uint32(castFlags);
2647 data << uint32(m_timer);
2649 m_targets.write(&data);
2651 if ( castFlags & CAST_FLAG_UNKNOWN6 )
2652 data << uint32(0);
2654 if ( castFlags & CAST_FLAG_UNKNOWN7 )
2656 uint8 v1 = 0;
2657 uint8 v2 = 0;
2658 data << v1; // v1
2659 data << v2; // v2
2660 for(uint8 i = 0; i < 6; ++i)
2661 if((1 << i) & v1)
2662 if(!(1 << i) & v2)
2663 data << uint8(0);
2666 if ( castFlags & CAST_FLAG_AMMO )
2667 WriteAmmoToPacket(&data);
2669 m_caster->SendMessageToSet(&data, true);
2672 void Spell::SendSpellGo()
2674 // not send invisible spell casting
2675 if(!IsNeedSendToClient())
2676 return;
2678 sLog.outDebug("Sending SMSG_SPELL_GO id=%u",m_spellInfo->Id);
2680 Unit * target;
2681 if(!m_targets.getUnitTarget())
2682 target = m_caster;
2683 else
2684 target = m_targets.getUnitTarget();
2686 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2687 if(IsRangedSpell())
2688 castFlags |= CAST_FLAG_AMMO;
2690 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2691 if(m_CastItem)
2692 data.append(m_CastItem->GetPackGUID());
2693 else
2694 data.append(m_caster->GetPackGUID());
2696 data.append(m_caster->GetPackGUID());
2697 data << uint8(m_cast_count); // pending spell cast?
2698 data << uint32(m_spellInfo->Id);
2699 data << uint32(castFlags);
2700 data << uint32(getMSTime()); // timestamp
2702 WriteSpellGoTargets(&data);
2704 m_targets.write(&data);
2706 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk
2707 data << uint32(0);
2709 if ( castFlags & CAST_FLAG_UNKNOWN7 )
2711 uint8 v1 = 0;
2712 uint8 v2 = 0;
2713 data << v1; // v1
2714 data << v2; // v2
2715 for(uint8 i = 0; i < 6; ++i)
2716 if((1 << i) & v1)
2717 if(!(1 << i) & v2)
2718 data << uint8(0);
2721 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2723 data << float(0);
2724 data << uint32(0);
2727 if ( castFlags & CAST_FLAG_AMMO )
2728 WriteAmmoToPacket(&data);
2730 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2732 data << uint32(0);
2733 data << uint32(0);
2736 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2738 data << uint8(0);
2741 m_caster->SendMessageToSet(&data, true);
2744 void Spell::WriteAmmoToPacket( WorldPacket * data )
2746 uint32 ammoInventoryType = 0;
2747 uint32 ammoDisplayID = 0;
2749 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2751 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2752 if(pItem)
2754 ammoInventoryType = pItem->GetProto()->InventoryType;
2755 if( ammoInventoryType == INVTYPE_THROWN )
2756 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2757 else
2759 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2760 if(ammoID)
2762 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2763 if(pProto)
2765 ammoDisplayID = pProto->DisplayInfoID;
2766 ammoInventoryType = pProto->InventoryType;
2769 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
2771 ammoDisplayID = 5996; // normal arrow
2772 ammoInventoryType = INVTYPE_AMMO;
2777 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2779 *data << uint32(ammoDisplayID);
2780 *data << uint32(ammoInventoryType);
2783 void Spell::WriteSpellGoTargets( WorldPacket * data )
2785 *data << (uint8)m_countOfHit;
2786 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2787 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
2788 *data << uint64(ihit->targetGUID);
2790 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
2791 *data << uint64(ighit->targetGUID); // Always hits
2793 *data << (uint8)m_countOfMiss;
2794 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2796 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
2798 *data << uint64(ihit->targetGUID);
2799 *data << uint8(ihit->missCondition);
2800 if( ihit->missCondition == SPELL_MISS_REFLECT )
2801 *data << uint8(ihit->reflectResult);
2806 void Spell::SendLogExecute()
2808 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2810 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
2812 if(m_caster->GetTypeId() == TYPEID_PLAYER)
2813 data.append(m_caster->GetPackGUID());
2814 else
2815 data.append(target->GetPackGUID());
2817 data << uint32(m_spellInfo->Id);
2818 uint32 count1 = 1;
2819 data << uint32(count1); // count1 (effect count?)
2820 for(uint32 i = 0; i < count1; ++i)
2822 data << uint32(m_spellInfo->Effect[0]); // spell effect
2823 uint32 count2 = 1;
2824 data << uint32(count2); // count2 (target count?)
2825 for(uint32 j = 0; j < count2; ++j)
2827 switch(m_spellInfo->Effect[0])
2829 case SPELL_EFFECT_POWER_DRAIN:
2830 if(Unit *unit = m_targets.getUnitTarget())
2831 data.append(unit->GetPackGUID());
2832 else
2833 data << uint8(0);
2834 data << uint32(0);
2835 data << uint32(0);
2836 data << float(0);
2837 break;
2838 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
2839 if(Unit *unit = m_targets.getUnitTarget())
2840 data.append(unit->GetPackGUID());
2841 else
2842 data << uint8(0);
2843 data << uint32(0); // count?
2844 break;
2845 case SPELL_EFFECT_INTERRUPT_CAST:
2846 if(Unit *unit = m_targets.getUnitTarget())
2847 data.append(unit->GetPackGUID());
2848 else
2849 data << uint8(0);
2850 data << uint32(0); // spellid
2851 break;
2852 case SPELL_EFFECT_DURABILITY_DAMAGE:
2853 if(Unit *unit = m_targets.getUnitTarget())
2854 data.append(unit->GetPackGUID());
2855 else
2856 data << uint8(0);
2857 data << uint32(0);
2858 data << uint32(0);
2859 break;
2860 case SPELL_EFFECT_OPEN_LOCK:
2861 case SPELL_EFFECT_OPEN_LOCK_ITEM:
2862 if(Item *item = m_targets.getItemTarget())
2863 data.append(item->GetPackGUID());
2864 else
2865 data << uint8(0);
2866 break;
2867 case SPELL_EFFECT_CREATE_ITEM:
2868 case SPELL_EFFECT_157:
2869 data << uint32(m_spellInfo->EffectItemType[0]);
2870 break;
2871 case SPELL_EFFECT_SUMMON:
2872 case SPELL_EFFECT_TRANS_DOOR:
2873 case SPELL_EFFECT_SUMMON_PET:
2874 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
2875 case SPELL_EFFECT_CREATE_HOUSE:
2876 case SPELL_EFFECT_DUEL:
2877 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
2878 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
2879 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
2880 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
2881 if(Unit *unit = m_targets.getUnitTarget())
2882 data.append(unit->GetPackGUID());
2883 else if(m_targets.getItemTargetGUID())
2884 data.appendPackGUID(m_targets.getItemTargetGUID());
2885 else if(GameObject *go = m_targets.getGOTarget())
2886 data.append(go->GetPackGUID());
2887 else
2888 data << uint8(0); // guid
2889 break;
2890 case SPELL_EFFECT_FEED_PET:
2891 data << uint32(m_targets.getItemTargetEntry());
2892 break;
2893 case SPELL_EFFECT_DISMISS_PET:
2894 if(Unit *unit = m_targets.getUnitTarget())
2895 data.append(unit->GetPackGUID());
2896 else
2897 data << uint8(0);
2898 break;
2899 case SPELL_EFFECT_RESURRECT:
2900 case SPELL_EFFECT_RESURRECT_NEW:
2901 if(Unit *unit = m_targets.getUnitTarget())
2902 data.append(unit->GetPackGUID());
2903 else
2904 data << uint8(0);
2905 break;
2906 default:
2907 return;
2912 m_caster->SendMessageToSet(&data, true);
2915 void Spell::SendInterrupted(uint8 result)
2917 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
2918 data.append(m_caster->GetPackGUID());
2919 data << uint8(m_cast_count);
2920 data << uint32(m_spellInfo->Id);
2921 data << uint8(result);
2922 m_caster->SendMessageToSet(&data, true);
2924 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
2925 data.append(m_caster->GetPackGUID());
2926 data << uint8(m_cast_count);
2927 data << uint32(m_spellInfo->Id);
2928 data << uint8(result);
2929 m_caster->SendMessageToSet(&data, true);
2932 void Spell::SendChannelUpdate(uint32 time)
2934 if(time == 0)
2936 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
2937 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
2940 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2941 return;
2943 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
2944 data.append(m_caster->GetPackGUID());
2945 data << uint32(time);
2947 ((Player*)m_caster)->GetSession()->SendPacket( &data );
2950 void Spell::SendChannelStart(uint32 duration)
2952 WorldObject* target = NULL;
2954 // select first not resisted target from target list for _0_ effect
2955 if(!m_UniqueTargetInfo.empty())
2957 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
2959 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
2961 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
2962 break;
2966 else if(!m_UniqueGOTargetInfo.empty())
2968 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
2970 if(itr->effectMask & (1<<0) )
2972 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
2973 break;
2978 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2980 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
2981 data.append(m_caster->GetPackGUID());
2982 data << uint32(m_spellInfo->Id);
2983 data << uint32(duration);
2985 ((Player*)m_caster)->GetSession()->SendPacket( &data );
2988 m_timer = duration;
2989 if(target)
2990 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
2991 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
2994 void Spell::SendResurrectRequest(Player* target)
2996 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+2+4));
2997 data << uint64(m_caster->GetGUID());
2998 uint32 count = 1;
2999 data << uint32(count); // amount of bytes to read
3001 for(uint32 i = 0; i < count; ++i)
3002 data << uint8(0);
3004 data << uint8(0);
3005 data << uint8(0);
3006 target->GetSession()->SendPacket(&data);
3009 void Spell::SendPlaySpellVisual(uint32 SpellID)
3011 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3012 return;
3014 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3015 data << uint64(m_caster->GetGUID());
3016 data << uint32(SpellID); // spell visual id?
3017 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3020 void Spell::TakeCastItem()
3022 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3023 return;
3025 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3026 if(m_IsTriggeredSpell)
3027 return;
3029 ItemPrototype const *proto = m_CastItem->GetProto();
3031 if(!proto)
3033 // This code is to avoid a crash
3034 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3035 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3036 return;
3039 bool expendable = false;
3040 bool withoutCharges = false;
3042 for (int i = 0; i<5; i++)
3044 if (proto->Spells[i].SpellId)
3046 // item has limited charges
3047 if (proto->Spells[i].SpellCharges)
3049 if (proto->Spells[i].SpellCharges < 0)
3050 expendable = true;
3052 int32 charges = m_CastItem->GetSpellCharges(i);
3054 // item has charges left
3055 if (charges)
3057 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3058 if (proto->Stackable < 2)
3059 m_CastItem->SetSpellCharges(i, charges);
3060 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3063 // all charges used
3064 withoutCharges = (charges == 0);
3069 if (expendable && withoutCharges)
3071 uint32 count = 1;
3072 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3074 // prevent crash at access to deleted m_targets.getItemTarget
3075 if(m_CastItem==m_targets.getItemTarget())
3076 m_targets.setItemTarget(NULL);
3078 m_CastItem = NULL;
3082 void Spell::TakePower()
3084 if(m_CastItem || m_triggeredByAuraSpell)
3085 return;
3087 // health as power used
3088 if(m_spellInfo->powerType == POWER_HEALTH)
3090 m_caster->ModifyHealth( -(int32)m_powerCost );
3091 return;
3094 if(m_spellInfo->powerType >= MAX_POWERS)
3096 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3097 return;
3100 Powers powerType = Powers(m_spellInfo->powerType);
3102 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3104 // Set the five second timer
3105 if (powerType == POWER_MANA && m_powerCost > 0)
3106 m_caster->SetLastManaUse(getMSTime());
3109 void Spell::TakeReagents()
3111 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3112 return;
3114 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3115 return;
3117 if (m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
3118 m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
3119 return;
3121 Player* p_caster = (Player*)m_caster;
3123 for(uint32 x=0;x<8;x++)
3125 if(m_spellInfo->Reagent[x] <= 0)
3126 continue;
3128 uint32 itemid = m_spellInfo->Reagent[x];
3129 uint32 itemcount = m_spellInfo->ReagentCount[x];
3131 // if CastItem is also spell reagent
3132 if (m_CastItem)
3134 ItemPrototype const *proto = m_CastItem->GetProto();
3135 if( proto && proto->ItemId == itemid )
3137 for(int s=0;s<5;s++)
3139 // CastItem will be used up and does not count as reagent
3140 int32 charges = m_CastItem->GetSpellCharges(s);
3141 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3143 ++itemcount;
3144 break;
3148 m_CastItem = NULL;
3152 // if getItemTarget is also spell reagent
3153 if (m_targets.getItemTargetEntry()==itemid)
3154 m_targets.setItemTarget(NULL);
3156 p_caster->DestroyItemCount(itemid, itemcount, true);
3160 void Spell::HandleThreatSpells(uint32 spellId)
3162 if(!m_targets.getUnitTarget() || !spellId)
3163 return;
3165 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3166 return;
3168 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3169 if(!threatSpell)
3170 return;
3172 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3174 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3177 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3179 unitTarget = pUnitTarget;
3180 itemTarget = pItemTarget;
3181 gameObjTarget = pGOTarget;
3183 uint8 eff = m_spellInfo->Effect[i];
3184 uint32 mechanic = m_spellInfo->EffectMechanic[i];
3186 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3188 sLog.outDebug( "Spell: Effect : %u", eff);
3190 //Simply return. Do not display "immune" in red text on client
3191 if(unitTarget && unitTarget->IsImmunedToSpellEffect(eff, mechanic))
3192 return;
3194 if(eff<TOTAL_SPELL_EFFECTS)
3196 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3197 (*this.*SpellEffects[eff])(i);
3200 else
3202 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3203 if (m_CastItem)
3204 EffectEnchantItemTmp(i);
3205 else
3207 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3208 eff, m_spellInfo->Id);
3214 void Spell::TriggerSpell()
3216 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3218 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3219 spell->prepare(&m_targets); // use original spell original targets
3223 uint8 Spell::CanCast(bool strict)
3225 // check cooldowns to prevent cheating
3226 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3228 if(m_triggeredByAuraSpell)
3229 return SPELL_FAILED_DONT_REPORT;
3230 else
3231 return SPELL_FAILED_NOT_READY;
3234 // only allow triggered spells if at an ended battleground
3235 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3236 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3237 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3238 return SPELL_FAILED_DONT_REPORT;
3240 // only check at first call, Stealth auras are already removed at second call
3241 // for now, ignore triggered spells
3242 if( strict && !m_IsTriggeredSpell)
3244 // Cannot be used in this stance/form
3245 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3246 return shapeError;
3248 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3249 return SPELL_FAILED_ONLY_STEALTHED;
3252 // caster state requirements
3253 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3254 return SPELL_FAILED_CASTER_AURASTATE;
3255 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3256 return SPELL_FAILED_CASTER_AURASTATE;
3258 // cancel autorepeat spells if cast start when moving
3259 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3260 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3262 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3263 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3264 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3265 return SPELL_FAILED_MOVING;
3268 Unit *target = m_targets.getUnitTarget();
3270 if(target)
3272 // target state requirements (not allowed state), apply to self also
3273 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3274 return SPELL_FAILED_TARGET_AURASTATE;
3276 if(target != m_caster)
3278 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3279 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3280 return SPELL_FAILED_TARGET_AURASTATE;
3282 // Not allow casting on flying player
3283 if (target->isInFlight())
3284 return SPELL_FAILED_BAD_TARGETS;
3286 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3287 return SPELL_FAILED_LINE_OF_SIGHT;
3289 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3290 // this case can be triggered if rank not found (too low-level target for first rank)
3291 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3293 for(int i=0;i<3;i++)
3295 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3296 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3297 return SPELL_FAILED_LOWLEVEL;
3302 // check pet presents
3303 for(int j=0;j<3;j++)
3305 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3307 target = m_caster->GetPet();
3308 if(!target)
3310 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3311 return SPELL_FAILED_DONT_REPORT;
3312 else
3313 return SPELL_FAILED_NO_PET;
3315 break;
3319 //check creature type
3320 //ignore self casts (including area casts when caster selected as target)
3321 if(target != m_caster)
3323 if(!CheckTargetCreatureType(target))
3325 if(target->GetTypeId()==TYPEID_PLAYER)
3326 return SPELL_FAILED_TARGET_IS_PLAYER;
3327 else
3328 return SPELL_FAILED_BAD_TARGETS;
3332 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3333 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3334 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3336 // check correctness positive/negative cast target (pet cast real check and cheating check)
3337 if(IsPositiveSpell(m_spellInfo->Id))
3339 if(m_caster->IsHostileTo(target))
3340 return SPELL_FAILED_BAD_TARGETS;
3342 else
3344 if(m_caster->IsFriendlyTo(target))
3345 return SPELL_FAILED_BAD_TARGETS;
3349 if(IsPositiveSpell(m_spellInfo->Id))
3351 if(target->IsImmunedToSpell(m_spellInfo,false))
3352 return SPELL_FAILED_TARGET_AURASTATE;
3355 //Must be behind the target.
3356 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3358 SendInterrupted(2);
3359 return SPELL_FAILED_NOT_BEHIND;
3362 //Target must be facing you.
3363 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3365 SendInterrupted(2);
3366 return SPELL_FAILED_NOT_INFRONT;
3369 // check if target is in combat
3370 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3372 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3375 // Spell casted only on battleground
3376 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3377 if(!((Player*)m_caster)->InBattleGround())
3378 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3380 // do not allow spells to be cast in arenas
3381 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3382 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3383 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3384 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3385 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3386 if(mapEntry->IsBattleArena())
3387 return SPELL_FAILED_NOT_IN_ARENA;
3389 // zone check
3390 if(!IsSpellAllowedInLocation(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3391 return SPELL_FAILED_REQUIRES_AREA;
3393 // not let players cast spells at mount (and let do it to creatures)
3394 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3395 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3397 if(m_caster->isInFlight())
3398 return SPELL_FAILED_NOT_FLYING;
3399 else
3400 return SPELL_FAILED_NOT_MOUNTED;
3403 // always (except passive spells) check items (focus object can be required for any type casts)
3404 if(!IsPassiveSpell(m_spellInfo->Id))
3405 if(uint8 castResult = CheckItems())
3406 return castResult;
3408 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3409 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3411 for(uint8 j = 0; j < 3; j++)
3413 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3414 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3415 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3416 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3418 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3419 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3420 if(lower==upper)
3421 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);
3423 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3424 float range = GetSpellMaxRange(srange);
3426 Creature* creatureScriptTarget = NULL;
3427 GameObject* goScriptTarget = NULL;
3429 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3431 switch(i_spellST->second.type)
3433 case SPELL_TARGET_TYPE_GAMEOBJECT:
3435 GameObject* p_GameObject = NULL;
3437 if(i_spellST->second.targetEntry)
3439 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3440 Cell cell(p);
3441 cell.data.Part.reserved = ALL_DISTRICT;
3443 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3444 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
3446 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3447 CellLock<GridReadGuard> cell_lock(cell, p);
3448 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
3450 if(p_GameObject)
3452 // remember found target and range, next attempt will find more near target with another entry
3453 creatureScriptTarget = NULL;
3454 goScriptTarget = p_GameObject;
3455 range = go_check.GetLastRange();
3458 else if( focusObject ) //Focus Object
3460 float frange = m_caster->GetDistance(focusObject);
3461 if(range >= frange)
3463 creatureScriptTarget = NULL;
3464 goScriptTarget = focusObject;
3465 range = frange;
3468 break;
3470 case SPELL_TARGET_TYPE_CREATURE:
3471 case SPELL_TARGET_TYPE_DEAD:
3472 default:
3474 Creature *p_Creature = NULL;
3476 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3477 Cell cell(p);
3478 cell.data.Part.reserved = ALL_DISTRICT;
3479 cell.SetNoCreate(); // Really don't know what is that???
3481 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3482 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
3484 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3486 CellLock<GridReadGuard> cell_lock(cell, p);
3487 cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
3489 if(p_Creature )
3491 creatureScriptTarget = p_Creature;
3492 goScriptTarget = NULL;
3493 range = u_check.GetLastRange();
3495 break;
3500 if(creatureScriptTarget)
3502 // store coordinates for TARGET_SCRIPT_COORDINATES
3503 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3504 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3506 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3508 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3509 AddUnitTarget(creatureScriptTarget, j);
3511 // store explicit target for TARGET_SCRIPT
3512 else
3513 AddUnitTarget(creatureScriptTarget, j);
3515 else if(goScriptTarget)
3517 // store coordinates for TARGET_SCRIPT_COORDINATES
3518 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3519 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3521 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3523 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3524 AddGOTarget(goScriptTarget, j);
3526 // store explicit target for TARGET_SCRIPT
3527 else
3528 AddGOTarget(goScriptTarget, j);
3530 //Missing DB Entry or targets for this spellEffect.
3531 else
3533 // not report target not existence for triggered spells
3534 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3535 return SPELL_FAILED_DONT_REPORT;
3536 else
3537 return SPELL_FAILED_BAD_TARGETS;
3543 if(uint8 castResult = CheckRange(strict))
3544 return castResult;
3547 if(uint8 castResult = CheckPower())
3548 return castResult;
3551 if(!m_triggeredByAuraSpell) // triggered spell not affected by stun/etc
3552 if(uint8 castResult = CheckCasterAuras())
3553 return castResult;
3555 for (int i = 0; i < 3; i++)
3557 // for effects of spells that have only one target
3558 switch(m_spellInfo->Effect[i])
3560 case SPELL_EFFECT_DUMMY:
3562 if(m_spellInfo->SpellIconID == 1648) // Execute
3564 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3565 return SPELL_FAILED_BAD_TARGETS;
3567 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
3569 if(m_caster->IsInWater())
3570 return SPELL_FAILED_ONLY_ABOVEWATER;
3572 else if(m_spellInfo->SpellIconID==156) // Holy Shock
3574 // spell different for friends and enemies
3575 // hart version required facing
3576 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3577 return SPELL_FAILED_UNIT_NOT_INFRONT;
3579 break;
3581 case SPELL_EFFECT_SCHOOL_DAMAGE:
3583 // Hammer of Wrath
3584 if(m_spellInfo->SpellVisual[0] == 7250)
3586 if (!m_targets.getUnitTarget())
3587 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3589 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3590 return SPELL_FAILED_BAD_TARGETS;
3592 break;
3594 case SPELL_EFFECT_TAMECREATURE:
3596 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3597 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3599 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3600 return SPELL_FAILED_HIGHLEVEL;
3602 // use SMSG_PET_TAME_FAILURE?
3603 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
3604 return SPELL_FAILED_BAD_TARGETS;
3606 if(m_caster->GetPetGUID())
3607 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3609 if(m_caster->GetCharmGUID())
3610 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3612 break;
3614 case SPELL_EFFECT_LEARN_SPELL:
3616 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
3617 break;
3619 Pet* pet = m_caster->GetPet();
3621 if(!pet)
3622 return SPELL_FAILED_NO_PET;
3624 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3626 if(!learn_spellproto)
3627 return SPELL_FAILED_NOT_KNOWN;
3629 if(m_spellInfo->spellLevel > pet->getLevel())
3630 return SPELL_FAILED_LOWLEVEL;
3632 break;
3634 case SPELL_EFFECT_LEARN_PET_SPELL:
3636 Pet* pet = m_caster->GetPet();
3638 if(!pet)
3639 return SPELL_FAILED_NO_PET;
3641 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3643 if(!learn_spellproto)
3644 return SPELL_FAILED_NOT_KNOWN;
3646 if(m_spellInfo->spellLevel > pet->getLevel())
3647 return SPELL_FAILED_LOWLEVEL;
3649 break;
3651 case SPELL_EFFECT_FEED_PET:
3653 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getItemTarget() )
3654 return SPELL_FAILED_BAD_TARGETS;
3656 Pet* pet = m_caster->GetPet();
3658 if(!pet)
3659 return SPELL_FAILED_NO_PET;
3661 if(!pet->HaveInDiet(m_targets.getItemTarget()->GetProto()))
3662 return SPELL_FAILED_WRONG_PET_FOOD;
3664 if(!pet->GetCurrentFoodBenefitLevel(m_targets.getItemTarget()->GetProto()->ItemLevel))
3665 return SPELL_FAILED_FOOD_LOWLEVEL;
3667 if(m_caster->isInCombat() || pet->isInCombat())
3668 return SPELL_FAILED_AFFECTING_COMBAT;
3670 break;
3672 case SPELL_EFFECT_POWER_BURN:
3673 case SPELL_EFFECT_POWER_DRAIN:
3675 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
3676 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3677 if(Unit* target = m_targets.getUnitTarget())
3678 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
3679 return SPELL_FAILED_BAD_TARGETS;
3680 break;
3682 case SPELL_EFFECT_CHARGE:
3684 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
3685 return SPELL_FAILED_ROOTED;
3687 break;
3689 case SPELL_EFFECT_SKINNING:
3691 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
3692 return SPELL_FAILED_BAD_TARGETS;
3694 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
3695 return SPELL_FAILED_TARGET_UNSKINNABLE;
3697 Creature* creature = (Creature*)m_targets.getUnitTarget();
3698 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
3700 return SPELL_FAILED_TARGET_NOT_LOOTED;
3703 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
3705 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
3706 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
3707 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
3708 if (ReqValue > skillValue)
3709 return SPELL_FAILED_LOW_CASTLEVEL;
3711 // chance for fail at orange skinning attempt
3712 if( (m_selfContainer && (*m_selfContainer) == this) &&
3713 skillValue < sWorld.GetConfigMaxSkillValue() &&
3714 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
3715 return SPELL_FAILED_TRY_AGAIN;
3717 break;
3719 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3720 case SPELL_EFFECT_OPEN_LOCK:
3722 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
3723 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
3724 break;
3726 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
3727 // we need a go target in case of TARGET_GAMEOBJECT
3728 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
3729 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
3730 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
3731 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
3732 return SPELL_FAILED_BAD_TARGETS;
3734 // In BattleGround players can use only flags and banners
3735 if( ((Player*)m_caster)->InBattleGround() &&
3736 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
3737 return SPELL_FAILED_TRY_AGAIN;
3739 // get the lock entry
3740 LockEntry const *lockInfo = NULL;
3741 if (GameObject* go=m_targets.getGOTarget())
3742 lockInfo = sLockStore.LookupEntry(go->GetLockId());
3743 else if(Item* itm=m_targets.getItemTarget())
3744 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
3746 // check lock compatibility
3747 if (lockInfo)
3749 // check for lock - key pair (checked by client also, just prevent cheating
3750 bool ok_key = false;
3751 for(int it = 0; it < 8; ++it)
3753 switch(lockInfo->Type[it])
3755 case LOCK_KEY_NONE:
3756 break;
3757 case LOCK_KEY_ITEM:
3759 if(lockInfo->Index[it])
3761 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
3762 ok_key =true;
3763 break;
3766 case LOCK_KEY_SKILL:
3768 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->Index[it])
3769 break;
3771 switch(lockInfo->Index[it])
3773 case LOCKTYPE_HERBALISM:
3774 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
3775 ok_key =true;
3776 break;
3777 case LOCKTYPE_MINING:
3778 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
3779 ok_key =true;
3780 break;
3781 default:
3782 ok_key =true;
3783 break;
3787 if(ok_key)
3788 break;
3791 if(!ok_key)
3792 return SPELL_FAILED_BAD_TARGETS;
3795 // chance for fail at orange mining/herb/LockPicking gathering attempt
3796 if (!m_selfContainer || ((*m_selfContainer) != this))
3797 break;
3799 // get the skill value of the player
3800 int32 SkillValue = 0;
3801 bool canFailAtMax = true;
3802 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
3804 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
3805 canFailAtMax = false;
3807 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
3809 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
3810 canFailAtMax = false;
3812 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3813 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
3815 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
3816 if(m_CastItem)
3817 SkillValue = 0;
3819 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
3820 SkillValue += m_currentBasePoints[i]+1;
3822 // get the required lock value
3823 int32 ReqValue=0;
3824 if (lockInfo)
3826 // check for lock - key pair
3827 bool ok = false;
3828 for(int it = 0; it < 8; ++it)
3830 if(lockInfo->Type[it]==LOCK_KEY_ITEM && lockInfo->Index[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
3832 // if so, we're good to go
3833 ok = true;
3834 break;
3837 if(ok)
3838 break;
3840 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3841 ReqValue = lockInfo->Skill[1];
3842 else
3843 ReqValue = lockInfo->Skill[0];
3846 // skill doesn't meet the required value
3847 if (ReqValue > SkillValue)
3848 return SPELL_FAILED_LOW_CASTLEVEL;
3850 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
3851 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
3852 return SPELL_FAILED_TRY_AGAIN;
3854 break;
3856 case SPELL_EFFECT_SUMMON_DEAD_PET:
3858 Creature *pet = m_caster->GetPet();
3859 if(!pet)
3860 return SPELL_FAILED_NO_PET;
3862 if(pet->isAlive())
3863 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3865 break;
3867 // This is generic summon effect now and don't make this check for summon types similar
3868 // SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3869 // These won't show up in m_caster->GetPetGUID()
3870 case SPELL_EFFECT_SUMMON:
3872 switch(m_spellInfo->EffectMiscValueB[i])
3874 case SUMMON_TYPE_POSESSED:
3875 case SUMMON_TYPE_POSESSED2:
3876 case SUMMON_TYPE_DEMON:
3877 case SUMMON_TYPE_SUMMON:
3879 if(m_caster->GetPetGUID())
3880 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3882 if(m_caster->GetCharmGUID())
3883 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3884 break;
3887 break;
3889 // Don't make this check for SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3890 // These won't show up in m_caster->GetPetGUID()
3891 case SPELL_EFFECT_SUMMON_POSSESSED:
3892 case SPELL_EFFECT_SUMMON_PHANTASM:
3893 case SPELL_EFFECT_SUMMON_DEMON:
3895 if(m_caster->GetPetGUID())
3896 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3898 if(m_caster->GetCharmGUID())
3899 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3901 break;
3903 case SPELL_EFFECT_SUMMON_PET:
3905 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
3908 Pet* pet = ((Player*)m_caster)->GetPet();
3910 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
3912 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
3913 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
3915 else
3916 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3919 if(m_caster->GetCharmGUID())
3920 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3922 break;
3924 case SPELL_EFFECT_SUMMON_PLAYER:
3926 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
3927 return SPELL_FAILED_BAD_TARGETS;
3928 if(!((Player*)m_caster)->GetSelection())
3929 return SPELL_FAILED_BAD_TARGETS;
3931 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
3932 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
3933 return SPELL_FAILED_BAD_TARGETS;
3935 // check if our map is dungeon
3936 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
3938 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
3939 if(!instance)
3940 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
3941 if ( instance->levelMin > target->getLevel() )
3942 return SPELL_FAILED_LOWLEVEL;
3943 if ( instance->levelMax && instance->levelMax < target->getLevel() )
3944 return SPELL_FAILED_HIGHLEVEL;
3946 break;
3948 case SPELL_EFFECT_LEAP:
3949 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
3951 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
3952 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
3953 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
3954 // teleport a bit above terrain level to avoid falling below it
3955 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
3956 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
3957 return SPELL_FAILED_TRY_AGAIN;
3959 float caster_pos_z = m_caster->GetPositionZ();
3960 // Control the caster to not climb or drop when +-fz > 8
3961 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
3962 return SPELL_FAILED_TRY_AGAIN;
3964 // not allow use this effect at battleground until battleground start
3965 if(m_caster->GetTypeId()==TYPEID_PLAYER)
3966 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
3967 if(bg->GetStatus() != STATUS_IN_PROGRESS)
3968 return SPELL_FAILED_TRY_AGAIN;
3969 break;
3971 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
3973 if (m_targets.getUnitTarget()==m_caster)
3974 return SPELL_FAILED_BAD_TARGETS;
3975 break;
3977 default:break;
3981 for (int i = 0; i < 3; i++)
3983 switch(m_spellInfo->EffectApplyAuraName[i])
3985 case SPELL_AURA_MOD_POSSESS:
3986 case SPELL_AURA_MOD_CHARM:
3988 if(m_caster->GetPetGUID())
3989 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3991 if(m_caster->GetCharmGUID())
3992 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3994 if(m_caster->GetCharmerGUID())
3995 return SPELL_FAILED_CHARMED;
3997 if(!m_targets.getUnitTarget())
3998 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4000 if(m_targets.getUnitTarget()->GetCharmerGUID())
4001 return SPELL_FAILED_CHARMED;
4003 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4004 return SPELL_FAILED_HIGHLEVEL;
4005 };break;
4006 case SPELL_AURA_MOUNTED:
4008 if (m_caster->IsInWater())
4009 return SPELL_FAILED_ONLY_ABOVEWATER;
4011 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4012 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4014 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4015 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaId)
4016 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4018 if (m_caster->GetAreaId()==35)
4019 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4021 ShapeshiftForm form = m_caster->m_form;
4022 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4023 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4024 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4025 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN )
4026 return SPELL_FAILED_NOT_SHAPESHIFT;
4028 break;
4030 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4032 if(!m_targets.getUnitTarget())
4033 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4035 // can be casted at non-friendly unit or own pet/charm
4036 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4037 return SPELL_FAILED_TARGET_FRIENDLY;
4038 };break;
4039 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4040 case SPELL_AURA_FLY:
4042 // not allow cast fly spells at old maps by players (all spells is self target)
4043 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4045 if( !((Player*)m_caster)->isGameMaster() &&
4046 GetVirtualMapForMapAndZone(m_caster->GetMapId(),m_caster->GetZoneId()) != 530)
4047 return SPELL_FAILED_NOT_HERE;
4049 };break;
4050 case SPELL_AURA_PERIODIC_MANA_LEECH:
4052 if (!m_targets.getUnitTarget())
4053 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4055 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4056 break;
4058 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4059 return SPELL_FAILED_BAD_TARGETS;
4060 break;
4062 default:break;
4066 // all ok
4067 return 0;
4070 int16 Spell::PetCanCast(Unit* target)
4072 if(!m_caster->isAlive())
4073 return SPELL_FAILED_CASTER_DEAD;
4075 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4076 return SPELL_FAILED_SPELL_IN_PROGRESS;
4077 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4078 return SPELL_FAILED_AFFECTING_COMBAT;
4080 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4082 //dead owner (pets still alive when owners ressed?)
4083 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4084 return SPELL_FAILED_CASTER_DEAD;
4086 if(!target && m_targets.getUnitTarget())
4087 target = m_targets.getUnitTarget();
4089 bool need = false;
4090 for(uint32 i = 0;i<3;i++)
4092 if(m_spellInfo->EffectImplicitTargetA[i] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_FRIEND || m_spellInfo->EffectImplicitTargetA[i] == TARGET_DUELVSPLAYER || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_PARTY || m_spellInfo->EffectImplicitTargetA[i] == TARGET_CURRENT_ENEMY_COORDINATES)
4094 need = true;
4095 if(!target)
4096 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4097 break;
4100 if(need)
4101 m_targets.setUnitTarget(target);
4103 Unit* _target = m_targets.getUnitTarget();
4105 if(_target) //for target dead/target not valid
4107 if(!_target->isAlive())
4108 return SPELL_FAILED_BAD_TARGETS;
4110 if(IsPositiveSpell(m_spellInfo->Id))
4112 if(m_caster->IsHostileTo(_target))
4113 return SPELL_FAILED_BAD_TARGETS;
4115 else
4117 bool duelvsplayertar = false;
4118 for(int j=0;j<3;j++)
4120 //TARGET_DUELVSPLAYER is positive AND negative
4121 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4123 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4125 return SPELL_FAILED_BAD_TARGETS;
4129 //cooldown
4130 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4131 return SPELL_FAILED_NOT_READY;
4134 uint16 result = CanCast(true);
4135 if(result != 0)
4136 return result;
4137 else
4138 return -1; //this allows to check spell fail 0, in combat
4141 uint8 Spell::CheckCasterAuras() const
4143 // Flag drop spells totally immuned to caster auras
4144 // FIXME: find more nice check for all totally immuned spells
4145 // AttributesEx3 & 0x10000000?
4146 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4147 return 0;
4149 uint8 school_immune = 0;
4150 uint32 mechanic_immune = 0;
4151 uint32 dispel_immune = 0;
4153 //Check if the spell grants school or mechanic immunity.
4154 //We use bitmasks so the loop is done only once and not on every aura check below.
4155 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4157 for(int i = 0;i < 3; i ++)
4159 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4160 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4161 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4162 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4163 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4164 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4166 //immune movement impairment and loss of control
4167 if(m_spellInfo->Id==(uint32)42292)
4168 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4171 //Check whether the cast should be prevented by any state you might have.
4172 uint8 prevented_reason = 0;
4173 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4174 if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4175 prevented_reason = SPELL_FAILED_STUNNED;
4176 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4177 prevented_reason = SPELL_FAILED_CONFUSED;
4178 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4179 prevented_reason = SPELL_FAILED_FLEEING;
4180 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4181 prevented_reason = SPELL_FAILED_SILENCED;
4182 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4183 prevented_reason = SPELL_FAILED_PACIFIED;
4185 // Attr must make flag drop spell totally immune from all effects
4186 if(prevented_reason)
4188 if(school_immune || mechanic_immune || dispel_immune)
4190 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4191 Unit::AuraMap const& auras = m_caster->GetAuras();
4192 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); itr++)
4194 if(itr->second)
4196 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4197 continue;
4198 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4199 continue;
4200 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4201 continue;
4203 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4204 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4205 switch(itr->second->GetModifier()->m_auraname)
4207 case SPELL_AURA_MOD_STUN:
4208 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4209 return SPELL_FAILED_STUNNED;
4210 break;
4211 case SPELL_AURA_MOD_CONFUSE:
4212 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4213 return SPELL_FAILED_CONFUSED;
4214 break;
4215 case SPELL_AURA_MOD_FEAR:
4216 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4217 return SPELL_FAILED_FLEEING;
4218 break;
4219 case SPELL_AURA_MOD_SILENCE:
4220 case SPELL_AURA_MOD_PACIFY:
4221 case SPELL_AURA_MOD_PACIFY_SILENCE:
4222 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4223 return SPELL_FAILED_PACIFIED;
4224 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4225 return SPELL_FAILED_SILENCED;
4226 break;
4231 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4232 else
4233 return prevented_reason;
4235 return 0; // all ok
4238 bool Spell::CanAutoCast(Unit* target)
4240 uint64 targetguid = target->GetGUID();
4242 for(uint32 j = 0;j<3;j++)
4244 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4246 if( m_spellInfo->StackAmount <= 1)
4248 if( target->HasAura(m_spellInfo->Id, j) )
4249 return false;
4251 else
4253 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4254 return false;
4257 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4259 if( target->HasAura(m_spellInfo->Id, j) )
4260 return false;
4264 int16 result = PetCanCast(target);
4266 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4268 FillTargetMap();
4269 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4270 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4271 if( ihit->targetGUID == targetguid )
4272 return true;
4274 return false; //target invalid
4277 uint8 Spell::CheckRange(bool strict)
4279 float range_mod;
4281 // self cast doesn't need range checking -- also for Starshards fix
4282 if (m_spellInfo->rangeIndex == 1) return 0;
4284 if (strict) //add radius of caster
4285 range_mod = 1.25;
4286 else //add radius of caster and ~5 yds "give"
4287 range_mod = 6.25;
4289 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4290 float max_range = GetSpellMaxRange(srange) + range_mod;
4291 float min_range = GetSpellMinRange(srange);
4293 if(Player* modOwner = m_caster->GetSpellModOwner())
4294 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4296 Unit *target = m_targets.getUnitTarget();
4298 if(target && target != m_caster)
4300 // distance from target center in checks
4301 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4302 if(dist > max_range)
4303 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4304 if(dist < min_range)
4305 return SPELL_FAILED_TOO_CLOSE;
4306 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4307 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4308 return SPELL_FAILED_UNIT_NOT_INFRONT;
4311 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4313 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4314 if(dist > max_range)
4315 return SPELL_FAILED_OUT_OF_RANGE;
4316 if(dist < min_range)
4317 return SPELL_FAILED_TOO_CLOSE;
4320 return 0; // ok
4323 int32 Spell::CalculatePowerCost()
4325 // item cast not used power
4326 if(m_CastItem)
4327 return 0;
4329 // Spell drain all exist power on cast (Only paladin lay of Hands)
4330 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4332 // If power type - health drain all
4333 if (m_spellInfo->powerType == POWER_HEALTH)
4334 return m_caster->GetHealth();
4335 // Else drain all power
4336 if (m_spellInfo->powerType < MAX_POWERS)
4337 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4338 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4339 return 0;
4342 // Base powerCost
4343 int32 powerCost = m_spellInfo->manaCost;
4344 // PCT cost from total amount
4345 if (m_spellInfo->ManaCostPercentage)
4347 switch (m_spellInfo->powerType)
4349 // health as power used
4350 case POWER_HEALTH:
4351 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4352 break;
4353 case POWER_MANA:
4354 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4355 break;
4356 case POWER_RAGE:
4357 case POWER_FOCUS:
4358 case POWER_ENERGY:
4359 case POWER_HAPPINESS:
4360 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4361 break;
4362 case POWER_RUNE:
4363 case POWER_RUNIC_POWER:
4364 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4365 break;
4366 default:
4367 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4368 return 0;
4371 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4372 // Flat mod from caster auras by spell school
4373 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4374 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4375 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4376 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4377 // Apply cost mod by spell
4378 if(Player* modOwner = m_caster->GetSpellModOwner())
4379 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4381 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4382 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4384 // PCT mod from user auras by school
4385 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4386 if (powerCost < 0)
4387 powerCost = 0;
4388 return powerCost;
4391 uint8 Spell::CheckPower()
4393 // item cast not used power
4394 if(m_CastItem)
4395 return 0;
4397 // health as power used - need check health amount
4398 if(m_spellInfo->powerType == POWER_HEALTH)
4400 if(m_caster->GetHealth() <= m_powerCost)
4401 return SPELL_FAILED_CASTER_AURASTATE;
4402 return 0;
4404 // Check valid power type
4405 if( m_spellInfo->powerType >= MAX_POWERS )
4407 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4408 return SPELL_FAILED_UNKNOWN;
4410 // Check power amount
4411 Powers powerType = Powers(m_spellInfo->powerType);
4412 if(m_caster->GetPower(powerType) < m_powerCost)
4413 return SPELL_FAILED_NO_POWER;
4414 else
4415 return 0;
4418 uint8 Spell::CheckItems()
4420 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4421 return 0;
4423 uint32 itemid, itemcount;
4424 Player* p_caster = (Player*)m_caster;
4426 if(m_CastItem)
4428 itemid = m_CastItem->GetEntry();
4429 if( !p_caster->HasItemCount(itemid,1) )
4430 return SPELL_FAILED_ITEM_NOT_READY;
4431 else
4433 ItemPrototype const *proto = m_CastItem->GetProto();
4434 if(!proto)
4435 return SPELL_FAILED_ITEM_NOT_READY;
4437 for (int i = 0; i<5; i++)
4439 if (proto->Spells[i].SpellCharges)
4441 if(m_CastItem->GetSpellCharges(i)==0)
4442 return SPELL_FAILED_NO_CHARGES_REMAIN;
4446 uint32 ItemClass = proto->Class;
4447 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4449 for (int i = 0; i < 3; i++)
4451 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4452 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4453 continue;
4455 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4456 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4457 return (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4459 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4460 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4462 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4463 return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4465 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4467 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4468 return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4475 if(m_targets.getItemTargetGUID())
4477 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4478 return SPELL_FAILED_BAD_TARGETS;
4480 if(!m_targets.getItemTarget())
4481 return SPELL_FAILED_ITEM_GONE;
4483 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4484 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4486 // if not item target then required item must be equipped
4487 else
4489 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4490 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4493 if(m_spellInfo->RequiresSpellFocus)
4495 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4496 Cell cell(p);
4497 cell.data.Part.reserved = ALL_DISTRICT;
4499 GameObject* ok = NULL;
4500 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4501 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(ok,go_check);
4503 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4504 CellLock<GridReadGuard> cell_lock(cell, p);
4505 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
4507 if(!ok)
4508 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4510 focusObject = ok; // game object found in range
4513 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
4514 m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION)))
4516 for(uint32 i=0;i<8;i++)
4518 if(m_spellInfo->Reagent[i] <= 0)
4519 continue;
4521 itemid = m_spellInfo->Reagent[i];
4522 itemcount = m_spellInfo->ReagentCount[i];
4524 // if CastItem is also spell reagent
4525 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4527 ItemPrototype const *proto = m_CastItem->GetProto();
4528 if(!proto)
4529 return SPELL_FAILED_ITEM_NOT_READY;
4530 for(int s=0;s<5;s++)
4532 // CastItem will be used up and does not count as reagent
4533 int32 charges = m_CastItem->GetSpellCharges(s);
4534 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4536 ++itemcount;
4537 break;
4541 if( !p_caster->HasItemCount(itemid,itemcount) )
4542 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
4546 uint32 totems = 2;
4547 for(int i=0;i<2;++i)
4549 if(m_spellInfo->Totem[i] != 0)
4551 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4553 totems -= 1;
4554 continue;
4556 }else
4557 totems -= 1;
4559 if(totems != 0)
4560 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
4562 //Check items for TotemCategory
4563 uint32 TotemCategory = 2;
4564 for(int i=0;i<2;++i)
4566 if(m_spellInfo->TotemCategory[i] != 0)
4568 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4570 TotemCategory -= 1;
4571 continue;
4574 else
4575 TotemCategory -= 1;
4577 if(TotemCategory != 0)
4578 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
4580 for(int i = 0; i < 3; i++)
4582 switch (m_spellInfo->Effect[i])
4584 case SPELL_EFFECT_CREATE_ITEM:
4586 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4588 ItemPosCountVec dest;
4589 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
4590 if (msg != EQUIP_ERR_OK )
4592 p_caster->SendEquipError( msg, NULL, NULL );
4593 return SPELL_FAILED_DONT_REPORT;
4596 break;
4598 case SPELL_EFFECT_ENCHANT_ITEM:
4600 Item* targetItem = m_targets.getItemTarget();
4601 if(!targetItem)
4602 return SPELL_FAILED_ITEM_NOT_FOUND;
4604 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
4605 return SPELL_FAILED_LOWLEVEL;
4606 // Not allow enchant in trade slot for some enchant type
4607 if( targetItem->GetOwner() != m_caster )
4609 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4610 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4611 if(!pEnchant)
4612 return SPELL_FAILED_ERROR;
4613 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4614 return SPELL_FAILED_NOT_TRADEABLE;
4616 break;
4618 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
4620 Item *item = m_targets.getItemTarget();
4621 if(!item)
4622 return SPELL_FAILED_ITEM_NOT_FOUND;
4623 // Not allow enchant in trade slot for some enchant type
4624 if( item->GetOwner() != m_caster )
4626 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4627 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4628 if(!pEnchant)
4629 return SPELL_FAILED_ERROR;
4630 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4631 return SPELL_FAILED_NOT_TRADEABLE;
4633 break;
4635 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
4636 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
4637 break;
4638 case SPELL_EFFECT_DISENCHANT:
4640 if(!m_targets.getItemTarget())
4641 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4643 // prevent disenchanting in trade slot
4644 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4645 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4647 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
4648 if(!itemProto)
4649 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4651 uint32 item_quality = itemProto->Quality;
4652 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
4653 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
4654 if (item_disenchantskilllevel == uint32(-1))
4655 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4656 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
4657 return SPELL_FAILED_LOW_CASTLEVEL;
4658 if(item_quality > 4 || item_quality < 2)
4659 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4660 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
4661 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4662 if (!itemProto->DisenchantID)
4663 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4664 break;
4666 case SPELL_EFFECT_PROSPECTING:
4668 if(!m_targets.getItemTarget())
4669 return SPELL_FAILED_CANT_BE_PROSPECTED;
4670 //ensure item is a prospectable ore
4671 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
4672 return SPELL_FAILED_CANT_BE_PROSPECTED;
4673 //prevent prospecting in trade slot
4674 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4675 return SPELL_FAILED_CANT_BE_PROSPECTED;
4676 //Check for enough skill in jewelcrafting
4677 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
4678 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
4679 return SPELL_FAILED_LOW_CASTLEVEL;
4680 //make sure the player has the required ores in inventory
4681 if(m_targets.getItemTarget()->GetCount() < 5)
4682 return SPELL_FAILED_NEED_MORE_ITEMS;
4684 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
4685 return SPELL_FAILED_CANT_BE_PROSPECTED;
4687 break;
4689 case SPELL_EFFECT_WEAPON_DAMAGE:
4690 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
4692 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
4693 if( m_attackType != RANGED_ATTACK )
4694 break;
4695 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
4696 if(!pItem || pItem->IsBroken())
4697 return SPELL_FAILED_EQUIPPED_ITEM;
4699 switch(pItem->GetProto()->SubClass)
4701 case ITEM_SUBCLASS_WEAPON_THROWN:
4703 uint32 ammo = pItem->GetEntry();
4704 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4705 return SPELL_FAILED_NO_AMMO;
4706 }; break;
4707 case ITEM_SUBCLASS_WEAPON_GUN:
4708 case ITEM_SUBCLASS_WEAPON_BOW:
4709 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4711 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
4712 if(!ammo)
4714 // Requires No Ammo
4715 if(m_caster->GetDummyAura(46699))
4716 break; // skip other checks
4718 return SPELL_FAILED_NO_AMMO;
4721 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
4722 if(!ammoProto)
4723 return SPELL_FAILED_NO_AMMO;
4725 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
4726 return SPELL_FAILED_NO_AMMO;
4728 // check ammo ws. weapon compatibility
4729 switch(pItem->GetProto()->SubClass)
4731 case ITEM_SUBCLASS_WEAPON_BOW:
4732 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4733 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
4734 return SPELL_FAILED_NO_AMMO;
4735 break;
4736 case ITEM_SUBCLASS_WEAPON_GUN:
4737 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
4738 return SPELL_FAILED_NO_AMMO;
4739 break;
4740 default:
4741 return SPELL_FAILED_NO_AMMO;
4744 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4745 return SPELL_FAILED_NO_AMMO;
4746 }; break;
4747 case ITEM_SUBCLASS_WEAPON_WAND:
4748 default:
4749 break;
4751 break;
4753 default:break;
4757 return uint8(0);
4760 void Spell::Delayed()
4762 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
4763 return;
4765 if (m_spellState == SPELL_STATE_DELAYED)
4766 return; // spell is active and can't be time-backed
4768 // spells not loosing casting time ( slam, dynamites, bombs.. )
4769 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
4770 return;
4772 //check resist chance
4773 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
4774 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4775 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4776 if (roll_chance_i(resistChance))
4777 return;
4779 int32 delaytime = GetNextDelayAtDamageMsTime();
4781 if(int32(m_timer) + delaytime > m_casttime)
4783 delaytime = m_casttime - m_timer;
4784 m_timer = m_casttime;
4786 else
4787 m_timer += delaytime;
4789 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
4791 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
4792 data.append(m_caster->GetPackGUID());
4793 data << uint32(delaytime);
4795 m_caster->SendMessageToSet(&data,true);
4798 void Spell::DelayedChannel()
4800 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
4801 return;
4803 //check resist chance
4804 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
4805 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4806 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4807 if (roll_chance_i(resistChance))
4808 return;
4810 int32 delaytime = GetNextDelayAtDamageMsTime();
4812 if(int32(m_timer) < delaytime)
4814 delaytime = m_timer;
4815 m_timer = 0;
4817 else
4818 m_timer -= delaytime;
4820 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
4822 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4824 if ((*ihit).missCondition == SPELL_MISS_NONE)
4826 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
4827 if (unit)
4829 for (int j=0;j<3;j++)
4830 if( ihit->effectMask & (1<<j) )
4831 unit->DelayAura(m_spellInfo->Id, j, delaytime);
4837 for(int j = 0; j < 3; j++)
4839 // partially interrupt persistent area auras
4840 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
4841 if(dynObj)
4842 dynObj->Delay(delaytime);
4845 SendChannelUpdate(m_timer);
4848 void Spell::UpdatePointers()
4850 if(m_originalCasterGUID==m_caster->GetGUID())
4851 m_originalCaster = m_caster;
4852 else
4854 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
4855 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
4858 m_targets.Update(m_caster);
4861 bool Spell::IsAffectedBy(SpellEntry const *spellInfo, uint32 effectId)
4863 return spellmgr.IsAffectedBySpell(m_spellInfo,spellInfo->Id,effectId,spellInfo->EffectItemType[effectId]);
4866 bool Spell::CheckTargetCreatureType(Unit* target) const
4868 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
4870 // Curse of Doom : not find another way to fix spell target check :/
4871 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
4873 // not allow cast at player
4874 if(target->GetTypeId()==TYPEID_PLAYER)
4875 return false;
4877 spellCreatureTargetMask = 0x7FF;
4880 // Dismiss Pet and Taming Lesson skipped
4881 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
4882 spellCreatureTargetMask = 0;
4884 if (spellCreatureTargetMask)
4886 uint32 TargetCreatureType = target->GetCreatureTypeMask();
4888 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
4890 return true;
4893 CurrentSpellTypes Spell::GetCurrentContainer()
4895 if (IsNextMeleeSwingSpell())
4896 return(CURRENT_MELEE_SPELL);
4897 else if (IsAutoRepeat())
4898 return(CURRENT_AUTOREPEAT_SPELL);
4899 else if (IsChanneledSpell(m_spellInfo))
4900 return(CURRENT_CHANNELED_SPELL);
4901 else
4902 return(CURRENT_GENERIC_SPELL);
4905 bool Spell::CheckTarget( Unit* target, uint32 eff )
4907 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
4908 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
4910 if (!CheckTargetCreatureType(target))
4911 return false;
4914 // Check targets for not_selectable unit flag and remove
4915 // A player can cast spells on his pet (or other controlled unit) though in any state
4916 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
4918 // any unattackable target skipped
4919 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
4920 return false;
4922 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
4923 // in case TARGET_SCRIPT target selected by server always and can't be cheated
4924 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
4925 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
4926 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
4927 return false;
4930 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
4931 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
4933 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
4934 return false;
4936 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
4937 return false;
4940 //Check targets for LOS visibility (except spells without range limitations )
4941 switch(m_spellInfo->Effect[eff])
4943 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
4944 break;
4945 case SPELL_EFFECT_DUMMY:
4946 if(m_spellInfo->Id!=20577) // Cannibalize
4947 break;
4948 //fall through
4949 case SPELL_EFFECT_RESURRECT_NEW:
4950 // player far away, maybe his corpse near?
4951 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4953 if(!m_targets.getCorpseTargetGUID())
4954 return false;
4956 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
4957 if(!corpse)
4958 return false;
4960 if(target->GetGUID()!=corpse->GetOwnerGUID())
4961 return false;
4963 if(!corpse->IsWithinLOSInMap(m_caster))
4964 return false;
4967 // all ok by some way or another, skip normal check
4968 break;
4969 default: // normal case
4970 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4971 return false;
4972 break;
4975 return true;
4978 Unit* Spell::SelectMagnetTarget()
4980 Unit* target = m_targets.getUnitTarget();
4982 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
4984 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
4985 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
4987 if(Unit* magnet = (*itr)->GetCaster())
4989 if(magnet->IsWithinLOSInMap(m_caster))
4991 target = magnet;
4992 m_targets.setUnitTarget(target);
4993 break;
4999 return target;
5002 bool Spell::IsNeedSendToClient() const
5004 return m_spellInfo->SpellVisual!=0 || IsChanneledSpell(m_spellInfo) ||
5005 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5008 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5010 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5011 if(itr->effectMask & (1<<effect))
5012 return true;
5014 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5015 if(itr->effectMask & (1<<effect))
5016 return true;
5018 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5019 if(itr->effectMask & (1<<effect))
5020 return true;
5022 return false;
5025 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5027 m_Spell = spell;
5030 SpellEvent::~SpellEvent()
5032 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5033 m_Spell->cancel();
5035 if (m_Spell->IsDeletable())
5037 delete m_Spell;
5039 else
5041 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5042 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5046 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5048 // update spell if it is not finished
5049 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5050 m_Spell->update(p_time);
5052 // check spell state to process
5053 switch (m_Spell->getState())
5055 case SPELL_STATE_FINISHED:
5057 // spell was finished, check deletable state
5058 if (m_Spell->IsDeletable())
5060 // check, if we do have unfinished triggered spells
5062 return(true); // spell is deletable, finish event
5064 // event will be re-added automatically at the end of routine)
5065 } break;
5067 case SPELL_STATE_CASTING:
5069 // this spell is in channeled state, process it on the next update
5070 // event will be re-added automatically at the end of routine)
5071 } break;
5073 case SPELL_STATE_DELAYED:
5075 // first, check, if we have just started
5076 if (m_Spell->GetDelayStart() != 0)
5078 // no, we aren't, do the typical update
5079 // check, if we have channeled spell on our hands
5080 if (IsChanneledSpell(m_Spell->m_spellInfo))
5082 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5083 // check, if we have casting anything else except this channeled spell and autorepeat
5084 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5086 // another non-melee non-delayed spell is casted now, abort
5087 m_Spell->cancel();
5089 else
5091 // do the action (pass spell to channeling state)
5092 m_Spell->handle_immediate();
5094 // event will be re-added automatically at the end of routine)
5096 else
5098 // run the spell handler and think about what we can do next
5099 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5100 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5101 if (n_offset)
5103 // re-add us to the queue
5104 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5105 return(false); // event not complete
5107 // event complete
5108 // finish update event will be re-added automatically at the end of routine)
5111 else
5113 // delaying had just started, record the moment
5114 m_Spell->SetDelayStart(e_time);
5115 // re-plan the event for the delay moment
5116 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5117 return(false); // event not complete
5119 } break;
5121 default:
5123 // all other states
5124 // event will be re-added automatically at the end of routine)
5125 } break;
5128 // spell processing not complete, plan event on the next update interval
5129 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5130 return(false); // event not complete
5133 void SpellEvent::Abort(uint64 /*e_time*/)
5135 // oops, the spell we try to do is aborted
5136 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5137 m_Spell->cancel();
5140 bool SpellEvent::IsDeletable() const
5142 return m_Spell->IsDeletable();