[7915] Implement more stricted checks and limitations at loading creature addon data.
[getmangos.git] / src / game / Spell.cpp
blobd27f6e20c452b22dba1b15c321a6787002b2169c
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "Group.h"
37 #include "UpdateData.h"
38 #include "MapManager.h"
39 #include "ObjectAccessor.h"
40 #include "CellImpl.h"
41 #include "Policies/SingletonImp.h"
42 #include "SharedDefines.h"
43 #include "LootMgr.h"
44 #include "VMapFactory.h"
45 #include "BattleGround.h"
46 #include "Util.h"
48 #define SPELL_CHANNEL_UPDATE_INTERVAL (1 * IN_MILISECONDS)
50 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
52 class PrioritizeManaPlayerWraper
54 friend struct PrioritizeMana;
56 public:
57 explicit PrioritizeManaPlayerWraper(Player* player) : player(player)
59 uint32 maxmana = player->GetMaxPower(POWER_MANA);
60 percentMana = maxmana ? player->GetPower(POWER_MANA) * 100 / maxmana : 101;
62 Player* getPlayer() const { return player; }
63 private:
64 Player* player;
65 uint32 percentMana;
68 struct PrioritizeMana
70 int operator()( PrioritizeManaPlayerWraper const& x, PrioritizeManaPlayerWraper const& y ) const
72 return x.percentMana < y.percentMana;
77 bool IsQuestTameSpell(uint32 spellId)
79 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
80 if (!spellproto) return false;
82 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
83 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
86 SpellCastTargets::SpellCastTargets()
88 m_unitTarget = NULL;
89 m_itemTarget = NULL;
90 m_GOTarget = NULL;
92 m_unitTargetGUID = 0;
93 m_GOTargetGUID = 0;
94 m_CorpseTargetGUID = 0;
95 m_itemTargetGUID = 0;
96 m_itemTargetEntry = 0;
98 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
99 m_strTarget = "";
100 m_targetMask = 0;
103 SpellCastTargets::~SpellCastTargets()
107 void SpellCastTargets::setUnitTarget(Unit *target)
109 if (!target)
110 return;
112 m_destX = target->GetPositionX();
113 m_destY = target->GetPositionY();
114 m_destZ = target->GetPositionZ();
115 m_unitTarget = target;
116 m_unitTargetGUID = target->GetGUID();
117 m_targetMask |= TARGET_FLAG_UNIT;
120 void SpellCastTargets::setDestination(float x, float y, float z)
122 m_destX = x;
123 m_destY = y;
124 m_destZ = z;
125 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
128 void SpellCastTargets::setSource(float x, float y, float z)
130 m_srcX = x;
131 m_srcY = y;
132 m_srcZ = z;
133 m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
136 void SpellCastTargets::setGOTarget(GameObject *target)
138 m_GOTarget = target;
139 m_GOTargetGUID = target->GetGUID();
140 // m_targetMask |= TARGET_FLAG_OBJECT;
143 void SpellCastTargets::setItemTarget(Item* item)
145 if(!item)
146 return;
148 m_itemTarget = item;
149 m_itemTargetGUID = item->GetGUID();
150 m_itemTargetEntry = item->GetEntry();
151 m_targetMask |= TARGET_FLAG_ITEM;
154 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
156 m_CorpseTargetGUID = corpse->GetGUID();
159 void SpellCastTargets::Update(Unit* caster)
161 m_GOTarget = m_GOTargetGUID ? caster->GetMap()->GetGameObject(m_GOTargetGUID) : NULL;
162 m_unitTarget = m_unitTargetGUID ?
163 ( m_unitTargetGUID == caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
164 NULL;
166 m_itemTarget = NULL;
167 if(caster->GetTypeId() == TYPEID_PLAYER)
169 if(m_targetMask & TARGET_FLAG_ITEM)
170 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
171 else
173 Player* pTrader = ((Player*)caster)->GetTrader();
174 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
175 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
177 if(m_itemTarget)
178 m_itemTargetEntry = m_itemTarget->GetEntry();
182 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
184 if(data->rpos() + 4 > data->size())
185 return false;
187 *data >> m_targetMask;
189 if(m_targetMask == TARGET_FLAG_SELF)
191 m_destX = caster->GetPositionX();
192 m_destY = caster->GetPositionY();
193 m_destZ = caster->GetPositionZ();
194 m_unitTarget = caster;
195 m_unitTargetGUID = caster->GetGUID();
196 return true;
199 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
200 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
201 if(!data->readPackGUID(m_unitTargetGUID))
202 return false;
204 if( m_targetMask & ( TARGET_FLAG_OBJECT ))
205 if(!data->readPackGUID(m_GOTargetGUID))
206 return false;
208 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
209 if(!data->readPackGUID(m_itemTargetGUID))
210 return false;
212 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
213 if(!data->readPackGUID(m_CorpseTargetGUID))
214 return false;
216 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
218 if(data->rpos() + 4 + 4 + 4 > data->size())
219 return false;
221 *data >> m_srcX >> m_srcY >> m_srcZ;
222 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
223 return false;
226 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
228 if(data->rpos() + 1 + 4 + 4 + 4 > data->size())
229 return false;
231 if(!data->readPackGUID(m_unitTargetGUID))
232 return false;
234 *data >> m_destX >> m_destY >> m_destZ;
235 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
236 return false;
239 if( m_targetMask & TARGET_FLAG_STRING )
241 if(data->rpos() + 1 > data->size())
242 return false;
244 *data >> m_strTarget;
247 // find real units/GOs
248 Update(caster);
249 return true;
252 void SpellCastTargets::write ( WorldPacket * data )
254 *data << uint32(m_targetMask);
256 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
258 if(m_targetMask & TARGET_FLAG_UNIT)
260 if(m_unitTarget)
261 data->append(m_unitTarget->GetPackGUID());
262 else
263 *data << uint8(0);
265 else if( m_targetMask & TARGET_FLAG_OBJECT )
267 if(m_GOTarget)
268 data->append(m_GOTarget->GetPackGUID());
269 else
270 *data << uint8(0);
272 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
273 data->appendPackGUID(m_CorpseTargetGUID);
274 else
275 *data << uint8(0);
278 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
280 if(m_itemTarget)
281 data->append(m_itemTarget->GetPackGUID());
282 else
283 *data << uint8(0);
286 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
287 *data << m_srcX << m_srcY << m_srcZ;
289 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
291 if(m_unitTarget)
292 data->append(m_unitTarget->GetPackGUID());
293 else
294 *data << uint8(0);
296 *data << m_destX << m_destY << m_destZ;
299 if( m_targetMask & TARGET_FLAG_STRING )
300 *data << m_strTarget;
303 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
305 ASSERT( Caster != NULL && info != NULL );
306 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
308 m_spellInfo = info;
309 m_caster = Caster;
310 m_selfContainer = NULL;
311 m_triggeringContainer = triggeringContainer;
312 m_referencedFromCurrentSpell = false;
313 m_executedCurrently = false;
314 m_delayStart = 0;
315 m_delayAtDamageCount = 0;
317 m_applyMultiplierMask = 0;
319 // Get data for type of attack
320 switch (m_spellInfo->DmgClass)
322 case SPELL_DAMAGE_CLASS_MELEE:
323 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
324 m_attackType = OFF_ATTACK;
325 else
326 m_attackType = BASE_ATTACK;
327 break;
328 case SPELL_DAMAGE_CLASS_RANGED:
329 m_attackType = RANGED_ATTACK;
330 break;
331 default:
332 // Wands
333 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
334 m_attackType = RANGED_ATTACK;
335 else
336 m_attackType = BASE_ATTACK;
337 break;
340 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
342 if(m_attackType == RANGED_ATTACK)
344 // wand case
345 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
347 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
348 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage[0].DamageType);
351 // Set health leech amount to zero
352 m_healthLeech = 0;
354 if(originalCasterGUID)
355 m_originalCasterGUID = originalCasterGUID;
356 else
357 m_originalCasterGUID = m_caster->GetGUID();
359 if(m_originalCasterGUID == m_caster->GetGUID())
360 m_originalCaster = m_caster;
361 else
363 m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
364 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
367 for(int i=0; i <3; ++i)
368 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
370 m_spellState = SPELL_STATE_NULL;
372 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
373 m_TriggerSpells.clear();
374 m_IsTriggeredSpell = triggered;
375 //m_AreaAura = false;
376 m_CastItem = NULL;
378 unitTarget = NULL;
379 itemTarget = NULL;
380 gameObjTarget = NULL;
381 focusObject = NULL;
382 m_cast_count = 0;
383 m_glyphIndex = 0;
384 m_preCastSpell = 0;
385 m_triggeredByAuraSpell = NULL;
387 //Auto Shot & Shoot (wand)
388 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
390 m_runesState = 0;
391 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
392 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
393 m_timer = 0; // will set to castime in prepare
395 m_needAliveTargetMask = 0;
397 // determine reflection
398 m_canReflect = false;
400 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED))
402 for(int j = 0;j < 3; ++j)
404 if (m_spellInfo->Effect[j] == 0)
405 continue;
407 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j], m_spellInfo->EffectImplicitTargetB[j]))
408 m_canReflect = true;
409 else
410 m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NEGATIVE) ? true : false;
412 if(m_canReflect)
413 continue;
414 else
415 break;
419 CleanupTargetList();
422 Spell::~Spell()
426 template<typename T>
427 WorldObject* Spell::FindCorpseUsing()
429 // non-standard target selection
430 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
431 float max_range = GetSpellMaxRange(srange);
433 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
434 Cell cell(p);
435 cell.data.Part.reserved = ALL_DISTRICT;
436 cell.SetNoCreate();
438 WorldObject* result = NULL;
440 T u_check(m_caster, max_range);
441 MaNGOS::WorldObjectSearcher<T> searcher(m_caster, result, u_check);
443 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<T>, GridTypeMapContainer > grid_searcher(searcher);
444 CellLock<GridReadGuard> cell_lock(cell, p);
445 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
447 if (!result)
449 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<T>, WorldTypeMapContainer > world_searcher(searcher);
450 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
453 return result;
456 void Spell::FillTargetMap()
458 // TODO: ADD the correct target FILLS!!!!!!
460 for(uint32 i = 0; i < 3; ++i)
462 // not call for empty effect.
463 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
464 if(m_spellInfo->Effect[i] == 0)
465 continue;
467 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::CheckCast call
468 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
469 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
470 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
471 continue;
473 // TODO: find a way so this is not needed?
474 // for area auras always add caster as target (needed for totems for example)
475 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
476 AddUnitTarget(m_caster, i);
478 std::list<Unit*> tmpUnitMap;
480 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
481 // but need it support in some know cases
482 switch(m_spellInfo->EffectImplicitTargetA[i])
484 case TARGET_SELF:
485 switch(m_spellInfo->EffectImplicitTargetB[i])
487 case 0:
488 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
489 break;
490 case TARGET_AREAEFFECT_INSTANT: // use B case that not dependent from from A in fact
491 if((m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) == 0)
492 m_targets.setDestination(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ());
493 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
494 break;
495 case TARGET_BEHIND_VICTIM: // use B case that not dependent from from A in fact
496 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
497 break;
498 default:
499 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
500 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
501 break;
503 break;
504 case TARGET_CASTER_COORDINATES:
505 // Note: this hack with search required until GO casting not implemented
506 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
507 // currently each enemy selected explicitly and self cast damage
508 if(m_spellInfo->EffectImplicitTargetB[i] == TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
510 if(m_targets.getUnitTarget())
511 tmpUnitMap.push_back(m_targets.getUnitTarget());
513 else
515 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
516 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
518 break;
519 case TARGET_TABLE_X_Y_Z_COORDINATES:
520 switch(m_spellInfo->EffectImplicitTargetB[i])
522 case 0:
523 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
525 // need some target for proccesing
526 if(m_targets.getUnitTarget())
527 tmpUnitMap.push_back(m_targets.getUnitTarget());
528 else
529 tmpUnitMap.push_back(m_caster);
530 break;
531 case TARGET_AREAEFFECT_INSTANT: // All 17/7 pairs used for dest teleportation, A processed in effect code
532 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
533 break;
534 default:
535 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
536 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
537 break;
539 break;
540 default:
541 switch(m_spellInfo->EffectImplicitTargetB[i])
543 case 0:
544 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
545 break;
546 case TARGET_SCRIPT_COORDINATES: // B case filled in CheckCast but we need fill unit list base at A case
547 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
548 break;
549 default:
550 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
551 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
552 break;
554 break;
557 if( (m_spellInfo->EffectImplicitTargetA[i] == 0 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_EFFECT_SELECT) &&
558 (m_spellInfo->EffectImplicitTargetB[i] == 0 || m_spellInfo->EffectImplicitTargetB[i] == TARGET_EFFECT_SELECT) )
560 // add here custom effects that need default target.
561 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
562 switch(m_spellInfo->Effect[i])
564 case SPELL_EFFECT_DUMMY:
566 switch(m_spellInfo->Id)
568 case 20577: // Cannibalize
570 WorldObject* result = FindCorpseUsing<MaNGOS::CannibalizeObjectCheck> ();
572 if(result)
574 switch(result->GetTypeId())
576 case TYPEID_UNIT:
577 case TYPEID_PLAYER:
578 tmpUnitMap.push_back((Unit*)result);
579 break;
580 case TYPEID_CORPSE:
581 m_targets.setCorpseTarget((Corpse*)result);
582 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
583 tmpUnitMap.push_back(owner);
584 break;
587 else
589 // clear cooldown at fail
590 if(m_caster->GetTypeId() == TYPEID_PLAYER)
591 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id, true);
592 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
593 finish(false);
595 break;
597 default:
598 if(m_targets.getUnitTarget())
599 tmpUnitMap.push_back(m_targets.getUnitTarget());
600 break;
602 break;
604 case SPELL_EFFECT_RESURRECT:
605 case SPELL_EFFECT_PARRY:
606 case SPELL_EFFECT_BLOCK:
607 case SPELL_EFFECT_CREATE_ITEM:
608 case SPELL_EFFECT_TRIGGER_SPELL:
609 case SPELL_EFFECT_TRIGGER_MISSILE:
610 case SPELL_EFFECT_LEARN_SPELL:
611 case SPELL_EFFECT_SKILL_STEP:
612 case SPELL_EFFECT_PROFICIENCY:
613 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
614 case SPELL_EFFECT_SELF_RESURRECT:
615 case SPELL_EFFECT_REPUTATION:
616 case SPELL_EFFECT_SEND_TAXI:
617 if(m_targets.getUnitTarget())
618 tmpUnitMap.push_back(m_targets.getUnitTarget());
619 // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example)
620 else if(m_spellInfo->Effect[i] == SPELL_EFFECT_TRIGGER_SPELL)
621 tmpUnitMap.push_back(m_caster);
622 break;
623 case SPELL_EFFECT_SUMMON_PLAYER:
624 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
626 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
627 if(target)
628 tmpUnitMap.push_back(target);
630 break;
631 case SPELL_EFFECT_RESURRECT_NEW:
632 if(m_targets.getUnitTarget())
633 tmpUnitMap.push_back(m_targets.getUnitTarget());
634 if(m_targets.getCorpseTargetGUID())
636 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
637 if(corpse)
639 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
640 if(owner)
641 tmpUnitMap.push_back(owner);
644 break;
645 case SPELL_EFFECT_SUMMON:
646 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
648 if(m_targets.getUnitTarget())
649 tmpUnitMap.push_back(m_targets.getUnitTarget());
651 else
652 tmpUnitMap.push_back(m_caster);
653 break;
654 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
655 case SPELL_EFFECT_TRANS_DOOR:
656 case SPELL_EFFECT_ADD_FARSIGHT:
657 case SPELL_EFFECT_APPLY_GLYPH:
658 case SPELL_EFFECT_STUCK:
659 case SPELL_EFFECT_FEED_PET:
660 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
661 case SPELL_EFFECT_SKILL:
662 tmpUnitMap.push_back(m_caster);
663 break;
664 case SPELL_EFFECT_LEARN_PET_SPELL:
665 if(Pet* pet = m_caster->GetPet())
666 tmpUnitMap.push_back(pet);
667 break;
668 case SPELL_EFFECT_ENCHANT_ITEM:
669 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
670 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
671 case SPELL_EFFECT_DISENCHANT:
672 case SPELL_EFFECT_PROSPECTING:
673 case SPELL_EFFECT_MILLING:
674 if(m_targets.getItemTarget())
675 AddItemTarget(m_targets.getItemTarget(), i);
676 break;
677 case SPELL_EFFECT_APPLY_AURA:
678 switch(m_spellInfo->EffectApplyAuraName[i])
680 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)
681 case SPELL_AURA_ADD_PCT_MODIFIER:
682 tmpUnitMap.push_back(m_caster);
683 break;
684 default: // apply to target in other case
685 if(m_targets.getUnitTarget())
686 tmpUnitMap.push_back(m_targets.getUnitTarget());
687 break;
689 break;
690 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
691 // AreaAura
692 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
693 SetTargetMap(i,TARGET_AREAEFFECT_PARTY, tmpUnitMap);
694 break;
695 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
696 if(m_targets.getUnitTarget())
698 tmpUnitMap.push_back(m_targets.getUnitTarget());
700 else if (m_targets.getCorpseTargetGUID())
702 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
703 if(corpse)
705 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
706 if(owner)
707 tmpUnitMap.push_back(owner);
710 break;
711 default:
712 break;
716 if(m_caster->GetTypeId() == TYPEID_PLAYER)
718 Player *me = (Player*)m_caster;
719 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
721 Unit *owner = (*itr)->GetOwner();
722 Unit *u = owner ? owner : (*itr);
723 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
725 me->UpdatePvP(true);
726 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
727 break;
732 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end();)
734 if (!CheckTarget (*itr, i))
736 itr = tmpUnitMap.erase(itr);
737 continue;
739 else
740 ++itr;
743 for(std::list<Unit*>::const_iterator iunit = tmpUnitMap.begin(); iunit != tmpUnitMap.end(); ++iunit)
744 AddUnitTarget((*iunit), i);
748 void Spell::prepareDataForTriggerSystem()
750 //==========================================================================================
751 // Now fill data for trigger system, need know:
752 // an spell trigger another or not ( m_canTrigger )
753 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
754 //==========================================================================================
755 // Fill flag can spell trigger or not
756 // TODO: possible exist spell attribute for this
757 m_canTrigger = false;
759 if (m_CastItem)
760 m_canTrigger = false; // Do not trigger from item cast spell
761 else if (!m_IsTriggeredSpell)
762 m_canTrigger = true; // Normal cast - can trigger
763 else if (!m_triggeredByAuraSpell)
764 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
766 if (!m_canTrigger) // Exceptions (some periodic triggers)
768 switch (m_spellInfo->SpellFamilyName)
770 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
771 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL)
772 m_canTrigger = true;
773 break;
774 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
775 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL)
776 m_canTrigger = true;
777 break;
778 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
779 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL)
780 m_canTrigger = true;
781 break;
782 case SPELLFAMILY_ROGUE: // For poisons need do it
783 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL)
784 m_canTrigger = true;
785 break;
786 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot
787 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000214LL ||
788 m_spellInfo->SpellFamilyFlags2 & 0x200)
789 m_canTrigger = true;
790 break;
791 case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it
792 if (m_spellInfo->SpellFamilyFlags & 0x0001000900B80400LL)
793 m_canTrigger = true;
794 break;
795 default:
796 break;
800 // Get data for type of attack and fill base info for trigger
801 switch (m_spellInfo->DmgClass)
803 case SPELL_DAMAGE_CLASS_MELEE:
804 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
805 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
806 break;
807 case SPELL_DAMAGE_CLASS_RANGED:
808 // Auto attack
809 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
811 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
812 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
814 else // Ranged spell attack
816 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
817 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
819 break;
820 default:
821 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
823 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
824 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
826 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
828 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
829 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
831 else // Negative spell
833 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
834 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
836 break;
838 // Hunter traps spells (for Entrapment trigger)
839 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
840 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x000020000000001CLL)
841 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
844 void Spell::CleanupTargetList()
846 m_UniqueTargetInfo.clear();
847 m_UniqueGOTargetInfo.clear();
848 m_UniqueItemInfo.clear();
849 m_delayMoment = 0;
852 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
854 if( m_spellInfo->Effect[effIndex] == 0 )
855 return;
857 // Check for effect immune skip if immuned
858 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
860 uint64 targetGUID = pVictim->GetGUID();
862 // Lookup target in already in list
863 for(std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
865 if (targetGUID == ihit->targetGUID) // Found in list
867 if (!immuned)
868 ihit->effectMask |= 1 << effIndex; // Add only effect mask if not immuned
869 return;
873 // This is new target calculate data for him
875 // Get spell hit result on target
876 TargetInfo target;
877 target.targetGUID = targetGUID; // Store target GUID
878 target.effectMask = immuned ? 0 : 1 << effIndex; // Store index of effect if not immuned
879 target.processed = false; // Effects not apply on target
881 // Calculate hit result
882 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
884 // Spell have speed - need calculate incoming time
885 if (m_spellInfo->speed > 0.0f)
887 // calculate spell incoming interval
888 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
889 if (dist < 5.0f) dist = 5.0f;
890 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
892 // Calculate minimum incoming time
893 if (m_delayMoment == 0 || m_delayMoment>target.timeDelay)
894 m_delayMoment = target.timeDelay;
896 else
897 target.timeDelay = 0LL;
899 // If target reflect spell back to caster
900 if (target.missCondition == SPELL_MISS_REFLECT)
902 // Calculate reflected spell result on caster
903 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
905 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
906 target.reflectResult = SPELL_MISS_PARRY;
908 // Increase time interval for reflected spells by 1.5
909 target.timeDelay += target.timeDelay >> 1;
911 else
912 target.reflectResult = SPELL_MISS_NONE;
914 // Add target to list
915 m_UniqueTargetInfo.push_back(target);
918 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
920 Unit* unit = m_caster->GetGUID() == unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
921 if (unit)
922 AddUnitTarget(unit, effIndex);
925 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
927 if( m_spellInfo->Effect[effIndex] == 0 )
928 return;
930 uint64 targetGUID = pVictim->GetGUID();
932 // Lookup target in already in list
933 for(std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
935 if (targetGUID == ihit->targetGUID) // Found in list
937 ihit->effectMask |= 1 << effIndex; // Add only effect mask
938 return;
942 // This is new target calculate data for him
944 GOTargetInfo target;
945 target.targetGUID = targetGUID;
946 target.effectMask = 1 << effIndex;
947 target.processed = false; // Effects not apply on target
949 // Spell have speed - need calculate incoming time
950 if (m_spellInfo->speed > 0.0f)
952 // calculate spell incoming interval
953 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
954 if (dist < 5.0f) dist = 5.0f;
955 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
956 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
957 m_delayMoment = target.timeDelay;
959 else
960 target.timeDelay = 0LL;
962 // Add target to list
963 m_UniqueGOTargetInfo.push_back(target);
966 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
968 GameObject* go = m_caster->GetMap()->GetGameObject(goGUID);
969 if (go)
970 AddGOTarget(go, effIndex);
973 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
975 if( m_spellInfo->Effect[effIndex] == 0 )
976 return;
978 // Lookup target in already in list
979 for(std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
981 if (pitem == ihit->item) // Found in list
983 ihit->effectMask |= 1<<effIndex; // Add only effect mask
984 return;
988 // This is new target add data
990 ItemTargetInfo target;
991 target.item = pitem;
992 target.effectMask = 1 << effIndex;
993 m_UniqueItemInfo.push_back(target);
996 void Spell::DoAllEffectOnTarget(TargetInfo *target)
998 if (target->processed) // Check target
999 return;
1000 target->processed = true; // Target checked in apply effects procedure
1002 // Get mask of effects for target
1003 uint32 mask = target->effectMask;
1005 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
1006 if (!unit)
1007 return;
1009 // Get original caster (if exist) and calculate damage/healing from him data
1010 Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
1012 // Skip if m_originalCaster not available
1013 if (!caster)
1014 return;
1016 SpellMissInfo missInfo = target->missCondition;
1017 // Need init unitTarget by default unit (can changed in code on reflect)
1018 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
1019 unitTarget = unit;
1021 // Reset damage/healing counter
1022 m_damage = 0;
1023 m_healing = 0;
1025 // Fill base trigger info
1026 uint32 procAttacker = m_procAttacker;
1027 uint32 procVictim = m_procVictim;
1028 uint32 procEx = PROC_EX_NONE;
1030 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
1031 DoSpellHitOnUnit(unit, mask);
1032 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
1034 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
1035 DoSpellHitOnUnit(m_caster, mask);
1038 // All calculated do it!
1039 // Do healing and triggers
1040 if (m_healing)
1042 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
1043 uint32 addhealth = m_healing;
1044 if (crit)
1046 procEx |= PROC_EX_CRITICAL_HIT;
1047 addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
1049 else
1050 procEx |= PROC_EX_NORMAL_HIT;
1052 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1053 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1054 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
1056 int32 gain = caster->DealHeal(unitTarget, addhealth, m_spellInfo, crit);
1057 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
1059 // Do damage and triggers
1060 else if (m_damage)
1062 // Fill base damage struct (unitTarget - is real spell target)
1063 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1065 // Add bonuses and fill damageInfo struct
1066 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
1067 caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
1069 // Send log damage message to client
1070 caster->SendSpellNonMeleeDamageLog(&damageInfo);
1072 procEx = createProcExtendMask(&damageInfo, missInfo);
1073 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1075 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1076 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1077 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
1079 caster->DealSpellDamage(&damageInfo, true);
1081 // Judgement of Blood
1082 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1084 int32 damagePoint = damageInfo.damage * 33 / 100;
1085 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1088 // Passive spell hits/misses or active spells only misses (only triggers)
1089 else
1091 // Fill base damage struct (unitTarget - is real spell target)
1092 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1093 procEx = createProcExtendMask(&damageInfo, missInfo);
1094 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1095 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1096 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1099 // Call scripted function for AI if this spell is casted upon a creature
1100 if(unit->GetTypeId()==TYPEID_UNIT)
1102 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1103 // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm... )
1104 if( !((Creature*)unit)->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1106 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
1107 p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id);
1110 if(((Creature*)unit)->AI())
1111 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1114 // Call scripted function for AI if this spell is casted by a creature
1115 if(m_caster->GetTypeId()==TYPEID_UNIT && ((Creature*)m_caster)->AI())
1116 ((Creature*)m_caster)->AI()->SpellHitTarget(unit, m_spellInfo);
1119 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1121 if(!unit || !effectMask)
1122 return;
1124 // Recheck immune (only for delayed spells)
1125 if( m_spellInfo->speed && (
1126 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1127 unit->IsImmunedToSpell(m_spellInfo)))
1129 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1130 return;
1133 if (unit->GetTypeId() == TYPEID_PLAYER)
1135 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1136 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1139 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1141 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1144 if( m_caster != unit )
1146 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1147 if (m_spellInfo->speed > 0.0f &&
1148 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1149 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1151 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1152 return;
1155 if( !m_caster->IsFriendlyTo(unit) )
1157 // for delayed spells ignore not visible explicit target
1158 if(m_spellInfo->speed > 0.0f && unit == m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1160 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1161 return;
1164 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1166 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1168 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1169 unit->SetStandState(UNIT_STAND_STATE_STAND);
1171 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1172 ((Creature*)unit)->AI()->AttackedBy(m_caster);
1174 unit->AddThreat(m_caster, 0.0f);
1175 unit->SetInCombatWith(m_caster);
1176 m_caster->SetInCombatWith(unit);
1178 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1180 m_caster->SetContestedPvP(attackedPlayer);
1184 else
1186 // for delayed spells ignore negative spells (after duel end) for friendly targets
1187 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1189 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1190 return;
1193 // assisting case, healing and resurrection
1194 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1195 m_caster->SetContestedPvP();
1196 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1198 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1199 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1204 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1205 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1206 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1207 // Increase Diminishing on unit, current informations for actually casts will use values above
1208 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1209 unit->IncrDiminishing(m_diminishGroup);
1211 // Apply additional spell effects to target
1212 if (m_preCastSpell)
1213 m_caster->CastSpell(unit, m_preCastSpell, true, m_CastItem);
1215 for(uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
1217 if (effectMask & (1 << effectNumber))
1219 HandleEffects(unit, NULL, NULL, effectNumber, m_damageMultipliers[effectNumber]);
1220 if ( m_applyMultiplierMask & (1 << effectNumber) )
1222 // Get multiplier
1223 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1224 // Apply multiplier mods
1225 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1226 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier, this);
1227 m_damageMultipliers[effectNumber] *= multiplier;
1233 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1235 if (target->processed) // Check target
1236 return;
1237 target->processed = true; // Target checked in apply effects procedure
1239 uint32 effectMask = target->effectMask;
1240 if(!effectMask)
1241 return;
1243 GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
1244 if(!go)
1245 return;
1247 for(uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
1248 if (effectMask & (1 << effectNumber))
1249 HandleEffects(NULL, NULL, go, effectNumber);
1251 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1252 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1253 if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1255 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
1256 p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
1260 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1262 uint32 effectMask = target->effectMask;
1263 if(!target->item || !effectMask)
1264 return;
1266 for(uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
1267 if (effectMask & (1 << effectNumber))
1268 HandleEffects(NULL, target->item, NULL, effectNumber);
1271 bool Spell::IsAliveUnitPresentInTargetList()
1273 // Not need check return true
1274 if (m_needAliveTargetMask == 0)
1275 return true;
1277 uint8 needAliveTargetMask = m_needAliveTargetMask;
1279 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
1281 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1283 Unit *unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1285 if (unit && unit->isAlive())
1286 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1290 // is all effects from m_needAliveTargetMask have alive targets
1291 return needAliveTargetMask == 0;
1294 // Helper for Chain Healing
1295 // Spell target first
1296 // Raidmates then descending by injury suffered (MaxHealth - Health)
1297 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1298 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1300 const Unit* MainTarget;
1301 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1302 // functor for operator ">"
1303 bool operator()(Unit const* _Left, Unit const* _Right) const
1305 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1307 int32 ChainHealingHash(Unit const* Target) const
1309 if (Target == MainTarget)
1310 return 0;
1311 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1312 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1314 if (Target->GetHealth() == Target->GetMaxHealth())
1315 return 40000;
1316 else
1317 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1319 else
1320 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1324 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1326 public:
1327 const Unit* MainTarget;
1328 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1330 bool operator()(const Unit* Target)
1332 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1336 // Helper for targets nearest to the spell target
1337 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1338 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1340 const Unit* MainTarget;
1341 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1342 // functor for operator ">"
1343 bool operator()(const Unit* _Left, const Unit* _Right) const
1345 return MainTarget->GetDistanceOrder(_Left,_Right);
1349 void Spell::SetTargetMap(uint32 i,uint32 cur,UnitList& TagUnitMap)
1351 float radius;
1352 if (m_spellInfo->EffectRadiusIndex[i])
1353 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1354 else
1355 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1357 if(m_originalCaster)
1358 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1359 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius, this);
1361 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1362 if(m_originalCaster)
1363 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1364 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1366 // Get spell max affected targets
1367 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1369 // custom target amount cases
1370 switch(m_spellInfo->SpellFamilyName)
1372 case SPELLFAMILY_DRUID:
1373 // Starfall
1374 if (m_spellInfo->SpellFamilyFlags2 & 0x00000100LL)
1375 unMaxTargets = 2;
1376 break;
1377 default:
1378 break;
1381 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1382 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1384 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1385 continue;
1386 unMaxTargets+=(*m)->GetModifier()->m_amount;
1389 switch(cur)
1391 case TARGET_TOTEM_EARTH:
1392 case TARGET_TOTEM_WATER:
1393 case TARGET_TOTEM_AIR:
1394 case TARGET_TOTEM_FIRE:
1395 case TARGET_SELF:
1396 case TARGET_SELF2:
1397 case TARGET_DYNAMIC_OBJECT:
1398 case TARGET_AREAEFFECT_CUSTOM:
1399 case TARGET_AREAEFFECT_CUSTOM_2:
1400 case TARGET_SUMMON:
1402 TagUnitMap.push_back(m_caster);
1403 break;
1405 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1407 m_targets.m_targetMask = 0;
1408 unMaxTargets = EffectChainTarget;
1409 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1411 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1412 Cell cell(p);
1413 cell.data.Part.reserved = ALL_DISTRICT;
1414 cell.SetNoCreate();
1416 std::list<Unit *> tempUnitMap;
1419 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1420 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1422 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1423 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1425 CellLock<GridReadGuard> cell_lock(cell, p);
1426 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1427 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1430 if(tempUnitMap.empty())
1431 break;
1433 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1435 //Now to get us a random target that's in the initial range of the spell
1436 uint32 t = 0;
1437 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1438 while(itr!= tempUnitMap.end() && (*itr)->IsWithinDist(m_caster,radius))
1439 ++t, ++itr;
1441 if(!t)
1442 break;
1444 itr = tempUnitMap.begin();
1445 std::advance(itr, rand()%t);
1446 Unit *pUnitTarget = *itr;
1447 TagUnitMap.push_back(pUnitTarget);
1449 tempUnitMap.erase(itr);
1451 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1453 t = unMaxTargets - 1;
1454 Unit *prev = pUnitTarget;
1455 std::list<Unit*>::iterator next = tempUnitMap.begin();
1457 while(t && next != tempUnitMap.end() )
1459 if(!prev->IsWithinDist(*next,CHAIN_SPELL_JUMP_RADIUS))
1460 break;
1462 if(!prev->IsWithinLOSInMap(*next))
1464 ++next;
1465 continue;
1468 prev = *next;
1469 TagUnitMap.push_back(prev);
1470 tempUnitMap.erase(next);
1471 tempUnitMap.sort(TargetDistanceOrder(prev));
1472 next = tempUnitMap.begin();
1474 --t;
1476 }break;
1477 case TARGET_RANDOM_FRIEND_CHAIN_IN_AREA:
1479 m_targets.m_targetMask = 0;
1480 unMaxTargets = EffectChainTarget;
1481 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1482 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1483 Cell cell(p);
1484 cell.data.Part.reserved = ALL_DISTRICT;
1485 cell.SetNoCreate();
1486 std::list<Unit *> tempUnitMap;
1488 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1489 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1491 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1492 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1494 CellLock<GridReadGuard> cell_lock(cell, p);
1495 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1496 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1499 if(tempUnitMap.empty())
1500 break;
1502 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1504 //Now to get us a random target that's in the initial range of the spell
1505 uint32 t = 0;
1506 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1507 while(itr!= tempUnitMap.end() && (*itr)->IsWithinDist(m_caster,radius))
1508 ++t, ++itr;
1510 if(!t)
1511 break;
1513 itr = tempUnitMap.begin();
1514 std::advance(itr, rand()%t);
1515 Unit *pUnitTarget = *itr;
1516 TagUnitMap.push_back(pUnitTarget);
1518 tempUnitMap.erase(itr);
1520 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1522 t = unMaxTargets - 1;
1523 Unit *prev = pUnitTarget;
1524 std::list<Unit*>::iterator next = tempUnitMap.begin();
1526 while(t && next != tempUnitMap.end() )
1528 if(!prev->IsWithinDist(*next,CHAIN_SPELL_JUMP_RADIUS))
1529 break;
1531 if(!prev->IsWithinLOSInMap(*next))
1533 ++next;
1534 continue;
1536 prev = *next;
1537 TagUnitMap.push_back(prev);
1538 tempUnitMap.erase(next);
1539 tempUnitMap.sort(TargetDistanceOrder(prev));
1540 next = tempUnitMap.begin();
1541 --t;
1543 }break;
1544 case TARGET_PET:
1546 Pet* tmpUnit = m_caster->GetPet();
1547 if (!tmpUnit) break;
1548 TagUnitMap.push_back(tmpUnit);
1549 break;
1551 case TARGET_CHAIN_DAMAGE:
1553 if (EffectChainTarget <= 1)
1555 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1557 m_targets.setUnitTarget(pUnitTarget);
1558 TagUnitMap.push_back(pUnitTarget);
1561 else
1563 Unit* pUnitTarget = m_targets.getUnitTarget();
1564 if(!pUnitTarget)
1565 break;
1567 unMaxTargets = EffectChainTarget;
1569 float max_range;
1570 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1571 max_range = radius; //
1572 else
1573 //FIXME: This very like horrible hack and wrong for most spells
1574 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1576 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1577 Cell cell(p);
1578 cell.data.Part.reserved = ALL_DISTRICT;
1579 cell.SetNoCreate();
1581 Unit* originalCaster = GetOriginalCaster();
1582 if(originalCaster)
1584 std::list<Unit *> tempUnitMap;
1587 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1588 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1590 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1591 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1593 CellLock<GridReadGuard> cell_lock(cell, p);
1594 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1595 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1598 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1600 if(tempUnitMap.empty())
1601 break;
1603 if(*tempUnitMap.begin() == pUnitTarget)
1604 tempUnitMap.erase(tempUnitMap.begin());
1606 TagUnitMap.push_back(pUnitTarget);
1607 uint32 t = unMaxTargets - 1;
1608 Unit *prev = pUnitTarget;
1609 std::list<Unit*>::iterator next = tempUnitMap.begin();
1611 while(t && next != tempUnitMap.end() )
1613 if(!prev->IsWithinDist(*next,CHAIN_SPELL_JUMP_RADIUS))
1614 break;
1616 if(!prev->IsWithinLOSInMap(*next))
1618 ++next;
1619 continue;
1622 prev = *next;
1623 TagUnitMap.push_back(prev);
1624 tempUnitMap.erase(next);
1625 tempUnitMap.sort(TargetDistanceOrder(prev));
1626 next = tempUnitMap.begin();
1628 --t;
1632 }break;
1633 case TARGET_ALL_ENEMY_IN_AREA:
1635 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1636 break;
1638 case TARGET_AREAEFFECT_INSTANT:
1640 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1641 // Select friendly targets for positive effect
1642 if (IsPositiveEffect(m_spellInfo->Id, i))
1643 targetB = SPELL_TARGETS_FRIENDLY;
1645 FillAreaTargets(TagUnitMap,m_caster->GetPositionX(), m_caster->GetPositionY(),radius, PUSH_DEST_CENTER, targetB);
1647 // exclude caster
1648 TagUnitMap.remove(m_caster);
1650 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1652 // targets the ground, not the units in the area
1653 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1655 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1657 // exclude caster (this can be important if this not original caster)
1658 TagUnitMap.remove(m_caster);
1660 }break;
1661 case TARGET_DUELVSPLAYER_COORDINATES:
1663 if(Unit* currentTarget = m_targets.getUnitTarget())
1665 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1666 TagUnitMap.push_back(currentTarget);
1668 }break;
1669 case TARGET_ALL_PARTY_AROUND_CASTER:
1670 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1671 case TARGET_ALL_PARTY:
1673 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1674 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1676 if(pGroup)
1678 uint8 subgroup = pTarget->GetSubGroup();
1680 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1682 Player* Target = itr->getSource();
1684 // IsHostileTo check duel and controlled by enemy
1685 if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1687 if( m_caster->IsWithinDistInMap(Target, radius) )
1688 TagUnitMap.push_back(Target);
1690 if(Pet* pet = Target->GetPet())
1691 if( m_caster->IsWithinDistInMap(pet, radius) )
1692 TagUnitMap.push_back(pet);
1696 else
1698 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1699 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1700 TagUnitMap.push_back(ownerOrSelf);
1701 if(Pet* pet = ownerOrSelf->GetPet())
1702 if( m_caster->IsWithinDistInMap(pet, radius) )
1703 TagUnitMap.push_back(pet);
1705 break;
1707 case TARGET_ALL_RAID_AROUND_CASTER:
1709 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1710 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1712 if(m_spellInfo->Id == 57669) // Replenishment (special target selection)
1714 if(pGroup)
1716 typedef std::priority_queue<PrioritizeManaPlayerWraper, std::vector<PrioritizeManaPlayerWraper>, PrioritizeMana> Top10;
1717 Top10 manaUsers;
1719 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL && manaUsers.size() < 10; itr = itr->next())
1721 Player* Target = itr->getSource();
1722 if (m_caster->GetGUID() != Target->GetGUID() && Target->getPowerType() == POWER_MANA &&
1723 !Target->isDead() && m_caster->IsWithinDistInMap(Target, radius))
1725 PrioritizeManaPlayerWraper WTarget(Target);
1726 manaUsers.push(WTarget);
1730 while(!manaUsers.empty())
1732 TagUnitMap.push_back(manaUsers.top().getPlayer());
1733 manaUsers.pop();
1736 else
1738 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1739 if ((ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius)) &&
1740 ownerOrSelf->getPowerType() == POWER_MANA)
1741 TagUnitMap.push_back(ownerOrSelf);
1743 if(Pet* pet = ownerOrSelf->GetPet())
1744 if( m_caster->IsWithinDistInMap(pet, radius) && pet->getPowerType() == POWER_MANA )
1745 TagUnitMap.push_back(pet);
1748 if (m_spellInfo->Id==52759) //Ancestral Awakening (special target selection)
1750 float lowestPerc = (float)m_caster->GetHealth() / (float)m_caster->GetMaxHealth();
1751 Unit* lowestTarget = m_caster;
1753 if (pGroup)
1755 Group::MemberSlotList const& members = pGroup->GetMemberSlots();
1756 Group::MemberSlotList::const_iterator itr = members.begin();
1757 for(; itr != members.end(); ++itr)
1759 if (Unit* member = ObjectAccessor::GetPlayer(*m_caster, (*itr).guid))
1761 if (member == m_caster || member->isDead() || m_caster->IsHostileTo(member) || !m_caster->IsWithinDistInMap(member, radius))
1762 continue;
1764 float perc = (float)member->GetHealth() / (float)member->GetMaxHealth();
1765 if (perc <= lowestPerc)
1767 lowestPerc = perc;
1768 lowestTarget = member;
1773 TagUnitMap.push_back(lowestTarget);
1775 else
1777 if(pGroup)
1779 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1781 Player* Target = itr->getSource();
1783 // IsHostileTo check duel and controlled by enemy
1784 if( Target && !m_caster->IsHostileTo(Target) )
1786 if( m_caster->IsWithinDistInMap(Target, radius) )
1787 TagUnitMap.push_back(Target);
1789 if(Pet* pet = Target->GetPet())
1790 if( m_caster->IsWithinDistInMap(pet, radius) )
1791 TagUnitMap.push_back(pet);
1795 else
1797 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1798 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1799 TagUnitMap.push_back(ownerOrSelf);
1800 if(Pet* pet = ownerOrSelf->GetPet())
1801 if( m_caster->IsWithinDistInMap(pet, radius) )
1802 TagUnitMap.push_back(pet);
1805 break;
1807 case TARGET_SINGLE_FRIEND:
1808 case TARGET_SINGLE_FRIEND_2:
1810 if(m_targets.getUnitTarget())
1811 TagUnitMap.push_back(m_targets.getUnitTarget());
1812 }break;
1813 case TARGET_NONCOMBAT_PET:
1815 if(Unit* target = m_targets.getUnitTarget())
1816 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1817 TagUnitMap.push_back(target);
1818 }break;
1819 case TARGET_CASTER_COORDINATES:
1821 // Check original caster is GO - set its coordinates as dst cast
1822 WorldObject *caster = NULL;
1823 if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
1824 caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
1825 if (!caster)
1826 caster = m_caster;
1827 // Set dest for targets
1828 m_targets.setDestination(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ());
1829 }break;
1830 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1831 FillAreaTargets(TagUnitMap, m_targets.m_destX, m_targets.m_destY, radius, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1832 break;
1833 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1834 FillAreaTargets(TagUnitMap, m_targets.m_destX, m_targets.m_destY, radius, PUSH_DEST_CENTER, SPELL_TARGETS_FRIENDLY);
1835 break;
1836 // 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..)
1837 case TARGET_SINGLE_PARTY:
1839 Unit *target = m_targets.getUnitTarget();
1840 // Thoses spells apparently can't be casted on the caster.
1841 if( target && target != m_caster)
1843 // Can only be casted on group's members or its pets
1844 Group *pGroup = NULL;
1846 Unit* owner = m_caster->GetCharmerOrOwner();
1847 Unit *targetOwner = target->GetCharmerOrOwner();
1848 if(owner)
1850 if(owner->GetTypeId() == TYPEID_PLAYER)
1852 if( target == owner )
1854 TagUnitMap.push_back(target);
1855 break;
1857 pGroup = ((Player*)owner)->GetGroup();
1860 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1862 if( targetOwner == m_caster && target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet())
1864 TagUnitMap.push_back(target);
1865 break;
1867 pGroup = ((Player*)m_caster)->GetGroup();
1870 if(pGroup)
1872 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1873 if(targetOwner)
1875 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1876 target->GetTypeId() == TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1877 target->GetOwnerGUID() == targetOwner->GetGUID() &&
1878 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1880 TagUnitMap.push_back(target);
1883 // 1Our target can be a player who is on our group
1884 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1886 TagUnitMap.push_back(target);
1890 }break;
1891 case TARGET_GAMEOBJECT:
1893 if(m_targets.getGOTarget())
1894 AddGOTarget(m_targets.getGOTarget(), i);
1895 }break;
1896 case TARGET_IN_FRONT_OF_CASTER:
1898 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1899 FillAreaTargets(TagUnitMap,m_caster->GetPositionX(), m_caster->GetPositionY(),radius,inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1900 break;
1902 case TARGET_DUELVSPLAYER:
1904 Unit *target = m_targets.getUnitTarget();
1905 if(target)
1907 if(m_caster->IsFriendlyTo(target))
1909 TagUnitMap.push_back(target);
1911 else
1913 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1915 m_targets.setUnitTarget(pUnitTarget);
1916 TagUnitMap.push_back(pUnitTarget);
1920 }break;
1921 case TARGET_GAMEOBJECT_ITEM:
1923 if(m_targets.getGOTargetGUID())
1924 AddGOTarget(m_targets.getGOTarget(), i);
1925 else if(m_targets.getItemTarget())
1926 AddItemTarget(m_targets.getItemTarget(), i);
1927 break;
1929 case TARGET_MASTER:
1931 if(Unit* owner = m_caster->GetCharmerOrOwner())
1932 TagUnitMap.push_back(owner);
1933 break;
1935 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1937 // targets the ground, not the units in the area
1938 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1939 FillAreaTargets(TagUnitMap, m_targets.m_destX, m_targets.m_destY, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1940 break;
1942 case TARGET_MINION:
1944 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1945 TagUnitMap.push_back(m_caster);
1946 }break;
1947 case TARGET_SINGLE_ENEMY:
1949 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1951 m_targets.setUnitTarget(pUnitTarget);
1952 TagUnitMap.push_back(pUnitTarget);
1954 }break;
1955 case TARGET_AREAEFFECT_PARTY:
1957 Unit* owner = m_caster->GetCharmerOrOwner();
1958 Player *pTarget = NULL;
1960 if(owner)
1962 TagUnitMap.push_back(m_caster);
1963 if(owner->GetTypeId() == TYPEID_PLAYER)
1964 pTarget = (Player*)owner;
1966 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1968 if(Unit* target = m_targets.getUnitTarget())
1970 if( target->GetTypeId() != TYPEID_PLAYER)
1972 if(((Creature*)target)->isPet())
1974 Unit *targetOwner = target->GetOwner();
1975 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1976 pTarget = (Player*)targetOwner;
1979 else
1980 pTarget = (Player*)target;
1984 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1986 if(pGroup)
1988 uint8 subgroup = pTarget->GetSubGroup();
1990 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1992 Player* Target = itr->getSource();
1994 // IsHostileTo check duel and controlled by enemy
1995 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1997 if( pTarget->IsWithinDistInMap(Target, radius) )
1998 TagUnitMap.push_back(Target);
2000 if(Pet* pet = Target->GetPet())
2001 if( pTarget->IsWithinDistInMap(pet, radius) )
2002 TagUnitMap.push_back(pet);
2006 else if (owner)
2008 if(m_caster->IsWithinDistInMap(owner, radius))
2009 TagUnitMap.push_back(owner);
2011 else if(pTarget)
2013 TagUnitMap.push_back(pTarget);
2015 if(Pet* pet = pTarget->GetPet())
2016 if( m_caster->IsWithinDistInMap(pet, radius) )
2017 TagUnitMap.push_back(pet);
2020 }break;
2021 case TARGET_SCRIPT:
2023 if(m_targets.getUnitTarget())
2024 TagUnitMap.push_back(m_targets.getUnitTarget());
2025 if(m_targets.getItemTarget())
2026 AddItemTarget(m_targets.getItemTarget(), i);
2027 }break;
2028 case TARGET_SELF_FISHING:
2030 TagUnitMap.push_back(m_caster);
2031 }break;
2032 case TARGET_CHAIN_HEAL:
2034 Unit* pUnitTarget = m_targets.getUnitTarget();
2035 if(!pUnitTarget)
2036 break;
2038 if (EffectChainTarget <= 1)
2039 TagUnitMap.push_back(pUnitTarget);
2040 else
2042 unMaxTargets = EffectChainTarget;
2043 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
2045 UnitList tempUnitMap;
2047 FillAreaTargets(tempUnitMap, m_caster->GetPositionX(), m_caster->GetPositionY(), max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
2049 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(), m_caster) == tempUnitMap.end() )
2050 tempUnitMap.push_front(m_caster);
2052 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
2054 if(tempUnitMap.empty())
2055 break;
2057 if(*tempUnitMap.begin() == pUnitTarget)
2058 tempUnitMap.erase(tempUnitMap.begin());
2060 TagUnitMap.push_back(pUnitTarget);
2061 uint32 t = unMaxTargets - 1;
2062 Unit *prev = pUnitTarget;
2063 std::list<Unit*>::iterator next = tempUnitMap.begin();
2065 while(t && next != tempUnitMap.end() )
2067 if(!prev->IsWithinDist(*next, CHAIN_SPELL_JUMP_RADIUS))
2068 break;
2070 if(!prev->IsWithinLOSInMap(*next))
2072 ++next;
2073 continue;
2076 if((*next)->GetHealth() == (*next)->GetMaxHealth())
2078 next = tempUnitMap.erase(next);
2079 continue;
2082 prev = *next;
2083 TagUnitMap.push_back(prev);
2084 tempUnitMap.erase(next);
2085 tempUnitMap.sort(TargetDistanceOrder(prev));
2086 next = tempUnitMap.begin();
2088 --t;
2091 }break;
2092 case TARGET_CURRENT_ENEMY_COORDINATES:
2094 Unit* currentTarget = m_targets.getUnitTarget();
2095 if(currentTarget)
2097 TagUnitMap.push_back(currentTarget);
2098 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
2099 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
2100 FillAreaTargets(TagUnitMap, currentTarget->GetPositionX(), currentTarget->GetPositionY(), radius, PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
2102 break;
2104 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
2106 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
2107 ? (Player*)m_targets.getUnitTarget() : NULL;
2109 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
2110 if(pGroup)
2112 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
2114 Player* Target = itr->getSource();
2116 // IsHostileTo check duel and controlled by enemy
2117 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
2118 targetPlayer->getClass() == Target->getClass() &&
2119 !m_caster->IsHostileTo(Target) )
2121 TagUnitMap.push_back(Target);
2125 else if(m_targets.getUnitTarget())
2126 TagUnitMap.push_back(m_targets.getUnitTarget());
2127 break;
2129 case TARGET_TABLE_X_Y_Z_COORDINATES:
2131 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
2132 if(st)
2134 if (st->target_mapId == m_caster->GetMapId())
2135 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
2136 else
2137 sLog.outError( "SPELL: wrong map (%u instead %u) target coordinates for spell ID %u", st->target_mapId, m_caster->GetMapId(), m_spellInfo->Id );
2139 else
2140 sLog.outError( "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id );
2141 }break;
2142 case TARGET_BEHIND_VICTIM:
2144 Unit *pTarget = NULL;
2146 // explicit cast data from client or server-side cast
2147 // some spell at client send caster
2148 if(m_targets.getUnitTarget() && m_targets.getUnitTarget()!=m_caster)
2149 pTarget = m_targets.getUnitTarget();
2150 else if(m_caster->getVictim())
2151 pTarget = m_caster->getVictim();
2152 else if(m_caster->GetTypeId() == TYPEID_PLAYER)
2153 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
2155 if(pTarget)
2157 float _target_x, _target_y, _target_z;
2158 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
2159 if(pTarget->IsWithinLOS(_target_x, _target_y, _target_z))
2161 TagUnitMap.push_back(m_caster);
2162 m_targets.setDestination(_target_x, _target_y, _target_z);
2165 break;
2167 case TARGET_DYNAMIC_OBJECT_COORDINATES:
2169 // if parent spell create dynamic object extract area from it
2170 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
2171 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
2172 break;
2174 case TARGET_DIRECTLY_FORWARD:
2176 if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION))
2178 SpellRangeEntry const* rEntry = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
2179 float minRange = GetSpellMinRange(rEntry);
2180 float maxRange = GetSpellMaxRange(rEntry);
2181 float dist = minRange+ rand_norm()*(maxRange-minRange);
2183 float _target_x, _target_y, _target_z;
2184 m_caster->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), dist);
2185 m_targets.setDestination(_target_x, _target_y, _target_z);
2188 TagUnitMap.push_back(m_caster);
2189 break;
2191 default:
2192 break;
2195 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2197 // make sure one unit is always removed per iteration
2198 uint32 removed_utarget = 0;
2199 for (UnitList::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2201 next = itr;
2202 ++next;
2203 if (!*itr) continue;
2204 if ((*itr) == m_targets.getUnitTarget())
2206 TagUnitMap.erase(itr);
2207 removed_utarget = 1;
2208 // break;
2211 // remove random units from the map
2212 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2214 uint32 poz = urand(0, TagUnitMap.size()-1);
2215 for (UnitList::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2217 if (!*itr) continue;
2219 if (!poz)
2221 TagUnitMap.erase(itr);
2222 break;
2226 // the player's target will always be added to the map
2227 if (removed_utarget && m_targets.getUnitTarget())
2228 TagUnitMap.push_back(m_targets.getUnitTarget());
2232 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2234 m_targets = *targets;
2236 m_spellState = SPELL_STATE_PREPARING;
2238 m_castPositionX = m_caster->GetPositionX();
2239 m_castPositionY = m_caster->GetPositionY();
2240 m_castPositionZ = m_caster->GetPositionZ();
2241 m_castOrientation = m_caster->GetOrientation();
2243 if(triggeredByAura)
2244 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2246 // create and add update event for this spell
2247 SpellEvent* Event = new SpellEvent(this);
2248 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2250 //Prevent casting at cast another spell (ServerSide check)
2251 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2253 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2254 finish(false);
2255 return;
2258 // Fill cost data
2259 m_powerCost = CalculatePowerCost();
2261 SpellCastResult result = CheckCast(true);
2262 if(result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2264 if(triggeredByAura)
2266 SendChannelUpdate(0);
2267 triggeredByAura->SetAuraDuration(0);
2269 SendCastResult(result);
2270 finish(false);
2271 return;
2274 // Prepare data for triggers
2275 prepareDataForTriggerSystem();
2277 // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
2278 m_casttime = GetSpellCastTime(m_spellInfo, this);
2280 // set timer base at cast time
2281 ReSetTimer();
2283 // stealth must be removed at cast starting (at show channel bar)
2284 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2285 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2287 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2288 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2291 if(m_IsTriggeredSpell)
2292 cast(true);
2293 else
2295 m_caster->SetCurrentCastedSpell( this );
2296 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2297 SendSpellStart();
2301 void Spell::cancel()
2303 if(m_spellState == SPELL_STATE_FINISHED)
2304 return;
2306 m_autoRepeat = false;
2307 switch (m_spellState)
2309 case SPELL_STATE_PREPARING:
2310 case SPELL_STATE_DELAYED:
2312 SendInterrupted(0);
2313 SendCastResult(SPELL_FAILED_INTERRUPTED);
2314 } break;
2316 case SPELL_STATE_CASTING:
2318 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2320 if( ihit->missCondition == SPELL_MISS_NONE )
2322 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2323 if( unit && unit->isAlive() )
2324 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2328 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2329 SendChannelUpdate(0);
2330 SendInterrupted(0);
2331 SendCastResult(SPELL_FAILED_INTERRUPTED);
2332 } break;
2334 default:
2336 } break;
2339 finish(false);
2340 m_caster->RemoveDynObject(m_spellInfo->Id);
2341 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2344 void Spell::cast(bool skipCheck)
2346 SetExecutedCurrently(true);
2348 // update pointers base at GUIDs to prevent access to non-existed already object
2349 UpdatePointers();
2351 // cancel at lost main target unit
2352 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2354 cancel();
2355 SetExecutedCurrently(false);
2356 return;
2359 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2360 m_caster->SetInFront(m_targets.getUnitTarget());
2362 SpellCastResult castResult = CheckPower();
2363 if(castResult != SPELL_CAST_OK)
2365 SendCastResult(castResult);
2366 finish(false);
2367 SetExecutedCurrently(false);
2368 return;
2371 // triggered cast called from Spell::prepare where it was already checked
2372 if(!skipCheck)
2374 castResult = CheckCast(false);
2375 if(castResult != SPELL_CAST_OK)
2377 SendCastResult(castResult);
2378 finish(false);
2379 SetExecutedCurrently(false);
2380 return;
2384 switch(m_spellInfo->SpellFamilyName)
2386 case SPELLFAMILY_GENERIC:
2388 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2389 m_preCastSpell = 11196; // Recently Bandaged
2390 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2391 m_preCastSpell = 23230; // Blood Fury - Healing Reduction
2392 break;
2394 case SPELLFAMILY_MAGE:
2396 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2397 m_preCastSpell = 41425; // Hypothermia
2398 break;
2400 case SPELLFAMILY_PRIEST:
2402 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2403 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2404 m_preCastSpell = 6788; // Weakened Soul
2405 if (m_spellInfo->Id == 47585) // Dispersion (transform)
2406 m_preCastSpell = 60069; // Dispersion (mana regen)
2407 break;
2409 case SPELLFAMILY_PALADIN:
2411 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2412 m_preCastSpell = 25771; // Forbearance
2413 break;
2415 case SPELLFAMILY_SHAMAN:
2417 if (m_spellInfo->Id == 2825) // Bloodlust
2418 m_preCastSpell = 57724; // Sated
2419 else if (m_spellInfo->Id == 32182) // Heroism
2420 m_preCastSpell = 57723; // Exhaustion
2421 break;
2423 default:
2424 break;
2427 // Conflagrate - consumes immolate
2428 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2430 // for caster applied auras only
2431 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2432 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2434 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2435 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2437 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2438 break;
2443 // traded items have trade slot instead of guid in m_itemTargetGUID
2444 // set to real guid to be sent later to the client
2445 m_targets.updateTradeSlotItem();
2447 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2449 if (!m_IsTriggeredSpell && m_CastItem)
2450 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2452 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2455 FillTargetMap();
2457 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in FillTargetMap
2459 SetExecutedCurrently(false);
2460 return;
2463 // CAST SPELL
2464 SendSpellCooldown();
2466 TakePower();
2467 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2469 SendCastResult(castResult);
2470 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2472 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2473 if (m_spellInfo->speed > 0.0f)
2476 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2477 // in case delayed spell remove item at cast delay start
2478 TakeCastItem();
2480 // Okay, maps created, now prepare flags
2481 m_immediateHandled = false;
2482 m_spellState = SPELL_STATE_DELAYED;
2483 SetDelayStart(0);
2485 else
2487 // Immediate spell, no big deal
2488 handle_immediate();
2491 SetExecutedCurrently(false);
2494 void Spell::handle_immediate()
2496 // start channeling if applicable
2497 if(IsChanneledSpell(m_spellInfo))
2499 int32 duration = GetSpellDuration(m_spellInfo);
2500 if (duration)
2502 // Apply duration mod
2503 if(Player* modOwner = m_caster->GetSpellModOwner())
2504 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
2505 m_spellState = SPELL_STATE_CASTING;
2506 SendChannelStart(duration);
2510 // process immediate effects (items, ground, etc.) also initialize some variables
2511 _handle_immediate_phase();
2513 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2514 DoAllEffectOnTarget(&(*ihit));
2516 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2517 DoAllEffectOnTarget(&(*ihit));
2519 // spell is finished, perform some last features of the spell here
2520 _handle_finish_phase();
2522 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2523 TakeCastItem();
2525 if(m_spellState != SPELL_STATE_CASTING)
2526 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2529 uint64 Spell::handle_delayed(uint64 t_offset)
2531 uint64 next_time = 0;
2533 if (!m_immediateHandled)
2535 _handle_immediate_phase();
2536 m_immediateHandled = true;
2539 // 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)
2540 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2542 if (ihit->processed == false)
2544 if ( ihit->timeDelay <= t_offset )
2545 DoAllEffectOnTarget(&(*ihit));
2546 else if( next_time == 0 || ihit->timeDelay < next_time )
2547 next_time = ihit->timeDelay;
2551 // now recheck gameobject targeting correctness
2552 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2554 if (ighit->processed == false)
2556 if ( ighit->timeDelay <= t_offset )
2557 DoAllEffectOnTarget(&(*ighit));
2558 else if( next_time == 0 || ighit->timeDelay < next_time )
2559 next_time = ighit->timeDelay;
2562 // All targets passed - need finish phase
2563 if (next_time == 0)
2565 // spell is finished, perform some last features of the spell here
2566 _handle_finish_phase();
2568 finish(true); // successfully finish spell cast
2570 // return zero, spell is finished now
2571 return 0;
2573 else
2575 // spell is unfinished, return next execution time
2576 return next_time;
2580 void Spell::_handle_immediate_phase()
2582 // handle some immediate features of the spell here
2583 HandleThreatSpells(m_spellInfo->Id);
2585 m_needSpellLog = IsNeedSendToClient();
2586 for(uint32 j = 0; j < 3; ++j)
2588 if(m_spellInfo->Effect[j] == 0)
2589 continue;
2591 // apply Send Event effect to ground in case empty target lists
2592 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2594 HandleEffects(NULL, NULL, NULL, j);
2595 continue;
2598 // Don't do spell log, if is school damage spell
2599 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2600 m_needSpellLog = false;
2602 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2603 if(m_originalCaster)
2604 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2605 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2607 // initialize multipliers
2608 m_damageMultipliers[j] = 1.0f;
2609 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2610 (EffectChainTarget > 1) )
2611 m_applyMultiplierMask |= 1 << j;
2614 // initialize Diminishing Returns Data
2615 m_diminishLevel = DIMINISHING_LEVEL_1;
2616 m_diminishGroup = DIMINISHING_NONE;
2618 // process items
2619 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2620 DoAllEffectOnTarget(&(*ihit));
2622 // process ground
2623 for(uint32 j = 0; j < 3; ++j)
2625 // persistent area auras target only the ground
2626 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2627 HandleEffects(NULL, NULL, NULL, j);
2631 void Spell::_handle_finish_phase()
2633 // spell log
2634 if(m_needSpellLog)
2635 SendLogExecute();
2638 void Spell::SendSpellCooldown()
2640 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2641 return;
2643 Player* _player = (Player*)m_caster;
2645 // mana/health/etc potions, disabled by client (until combat out as declarate)
2646 if (m_CastItem && m_CastItem->IsPotion())
2648 // need in some way provided data for Spell::finish SendCooldownEvent
2649 _player->SetLastPotionId(m_CastItem->GetEntry());
2650 return;
2653 // have infinity cooldown but set at aura apply
2654 if(m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2655 return;
2657 _player->AddSpellAndCategoryCooldowns(m_spellInfo,m_CastItem ? m_CastItem->GetEntry() : 0, this);
2660 void Spell::update(uint32 difftime)
2662 // update pointers based at it's GUIDs
2663 UpdatePointers();
2665 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2667 cancel();
2668 return;
2671 // check if the player caster has moved before the spell finished
2672 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2673 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2674 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2676 // always cancel for channeled spells
2677 if( m_spellState == SPELL_STATE_CASTING )
2678 cancel();
2679 // don't cancel for melee, autorepeat, triggered and instant spells
2680 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2681 cancel();
2684 switch(m_spellState)
2686 case SPELL_STATE_PREPARING:
2688 if(m_timer)
2690 if(difftime >= m_timer)
2691 m_timer = 0;
2692 else
2693 m_timer -= difftime;
2696 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2697 cast();
2698 } break;
2699 case SPELL_STATE_CASTING:
2701 if(m_timer > 0)
2703 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2705 // check if player has jumped before the channeling finished
2706 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2707 cancel();
2709 // check for incapacitating player states
2710 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2711 cancel();
2713 // check if player has turned if flag is set
2714 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2715 cancel();
2718 // check if there are alive targets left
2719 if (!IsAliveUnitPresentInTargetList())
2721 SendChannelUpdate(0);
2722 finish();
2725 if(difftime >= m_timer)
2726 m_timer = 0;
2727 else
2728 m_timer -= difftime;
2731 if(m_timer == 0)
2733 SendChannelUpdate(0);
2735 // channeled spell processed independently for quest targeting
2736 // cast at creature (or GO) quest objectives update at successful cast channel finished
2737 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2738 if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2740 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
2742 for(std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
2744 TargetInfo* target = &*ihit;
2745 if(!IS_CREATURE_GUID(target->targetGUID))
2746 continue;
2748 Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
2749 if (unit == NULL)
2750 continue;
2752 p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id);
2755 for(std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
2757 GOTargetInfo* target = &*ihit;
2759 GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
2760 if(!go)
2761 continue;
2763 p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
2768 finish();
2770 } break;
2771 default:
2773 }break;
2777 void Spell::finish(bool ok)
2779 if(!m_caster)
2780 return;
2782 if(m_spellState == SPELL_STATE_FINISHED)
2783 return;
2785 m_spellState = SPELL_STATE_FINISHED;
2787 // other code related only to successfully finished spells
2788 if(!ok)
2789 return;
2791 //remove spell mods
2792 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2793 ((Player*)m_caster)->RemoveSpellMods(this);
2795 // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2796 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2797 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2799 if (!(*i)->isAffectedOnSpell(m_spellInfo))
2800 continue;
2801 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2802 if( ihit->missCondition == SPELL_MISS_NONE )
2804 // check m_caster->GetGUID() let load auras at login and speedup most often case
2805 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2806 if (unit && unit->isAlive())
2808 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2809 uint32 auraSpellIdx = (*i)->GetEffIndex();
2810 // Calculate chance at that moment (can be depend for example from combo points)
2811 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2812 if(roll_chance_i(chance))
2813 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2818 // Heal caster for all health leech from all targets
2819 if (m_healthLeech)
2820 m_caster->DealHeal(m_caster, uint32(m_healthLeech), m_spellInfo);
2822 if (IsMeleeAttackResetSpell())
2824 m_caster->resetAttackTimer(BASE_ATTACK);
2825 if(m_caster->haveOffhandWeapon())
2826 m_caster->resetAttackTimer(OFF_ATTACK);
2829 /*if (IsRangedAttackResetSpell())
2830 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2832 // Clear combo at finish state
2833 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2835 // Not drop combopoints if negative spell and if any miss on enemy exist
2836 bool needDrop = true;
2837 if (!IsPositiveSpell(m_spellInfo->Id))
2838 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2839 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2841 needDrop = false;
2842 break;
2844 if (needDrop)
2845 ((Player*)m_caster)->ClearComboPoints();
2848 // potions disabled by client, send event "not in combat" if need
2849 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2850 ((Player*)m_caster)->UpdatePotionCooldown(this);
2852 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2853 if(!m_TriggerSpells.empty())
2854 TriggerSpell();
2856 // Stop Attack for some spells
2857 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2858 m_caster->AttackStop();
2861 void Spell::SendCastResult(SpellCastResult result)
2863 if(result == SPELL_CAST_OK)
2864 return;
2866 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2867 return;
2869 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2870 return;
2872 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2873 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2874 data << uint32(m_spellInfo->Id);
2875 data << uint8(result); // problem
2876 switch (result)
2878 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2879 data << uint32(m_spellInfo->RequiresSpellFocus);
2880 break;
2881 case SPELL_FAILED_REQUIRES_AREA:
2882 // hardcode areas limitation case
2883 switch(m_spellInfo->Id)
2885 case 41617: // Cenarion Mana Salve
2886 case 41619: // Cenarion Healing Salve
2887 data << uint32(3905);
2888 break;
2889 case 41618: // Bottled Nethergon Energy
2890 case 41620: // Bottled Nethergon Vapor
2891 data << uint32(3842);
2892 break;
2893 case 45373: // Bloodberry Elixir
2894 data << uint32(4075);
2895 break;
2896 default: // default case (don't must be)
2897 data << uint32(0);
2898 break;
2900 break;
2901 case SPELL_FAILED_TOTEMS:
2902 if(m_spellInfo->Totem[0])
2903 data << uint32(m_spellInfo->Totem[0]);
2904 if(m_spellInfo->Totem[1])
2905 data << uint32(m_spellInfo->Totem[1]);
2906 break;
2907 case SPELL_FAILED_TOTEM_CATEGORY:
2908 if(m_spellInfo->TotemCategory[0])
2909 data << uint32(m_spellInfo->TotemCategory[0]);
2910 if(m_spellInfo->TotemCategory[1])
2911 data << uint32(m_spellInfo->TotemCategory[1]);
2912 break;
2913 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2914 data << uint32(m_spellInfo->EquippedItemClass);
2915 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2916 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2917 break;
2918 default:
2919 break;
2921 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2924 void Spell::SendSpellStart()
2926 if(!IsNeedSendToClient())
2927 return;
2929 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2931 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2932 if(IsRangedSpell())
2933 castFlags |= CAST_FLAG_AMMO;
2935 if(m_spellInfo->runeCostID)
2936 castFlags |= CAST_FLAG_UNKNOWN10;
2938 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2939 if(m_CastItem)
2940 data.append(m_CastItem->GetPackGUID());
2941 else
2942 data.append(m_caster->GetPackGUID());
2944 data.append(m_caster->GetPackGUID());
2945 data << uint8(m_cast_count); // pending spell cast?
2946 data << uint32(m_spellInfo->Id); // spellId
2947 data << uint32(castFlags); // cast flags
2948 data << uint32(m_timer); // delay?
2950 m_targets.write(&data);
2952 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2953 data << uint32(0);
2955 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2957 uint8 v1 = 0;//m_runesState;
2958 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2959 data << uint8(v1); // runes state before
2960 data << uint8(v2); // runes state after
2961 for(uint8 i = 0; i < MAX_RUNES; ++i)
2963 uint8 m = (1 << i);
2964 if(m & v1) // usable before...
2965 if(!(m & v2)) // ...but on cooldown now...
2966 data << uint8(0); // some unknown byte (time?)
2970 if ( castFlags & CAST_FLAG_AMMO )
2971 WriteAmmoToPacket(&data);
2973 m_caster->SendMessageToSet(&data, true);
2976 void Spell::SendSpellGo()
2978 // not send invisible spell casting
2979 if(!IsNeedSendToClient())
2980 return;
2982 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2984 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2985 if(IsRangedSpell())
2986 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2988 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2990 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2991 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2992 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2995 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2997 if(m_CastItem)
2998 data.append(m_CastItem->GetPackGUID());
2999 else
3000 data.append(m_caster->GetPackGUID());
3002 data.append(m_caster->GetPackGUID());
3003 data << uint8(m_cast_count); // pending spell cast?
3004 data << uint32(m_spellInfo->Id); // spellId
3005 data << uint32(castFlags); // cast flags
3006 data << uint32(getMSTime()); // timestamp
3008 WriteSpellGoTargets(&data);
3010 m_targets.write(&data);
3012 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
3013 data << uint32(0);
3015 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
3017 uint8 v1 = m_runesState;
3018 uint8 v2 = ((Player*)m_caster)->GetRunesState();
3019 data << uint8(v1); // runes state before
3020 data << uint8(v2); // runes state after
3021 for(uint8 i = 0; i < MAX_RUNES; ++i)
3023 uint8 m = (1 << i);
3024 if(m & v1) // usable before...
3025 if(!(m & v2)) // ...but on cooldown now...
3026 data << uint8(0); // some unknown byte (time?)
3030 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
3032 data << float(0);
3033 data << uint32(0);
3036 if ( castFlags & CAST_FLAG_AMMO )
3037 WriteAmmoToPacket(&data);
3039 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
3041 data << uint32(0);
3042 data << uint32(0);
3045 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
3047 data << uint8(0);
3050 m_caster->SendMessageToSet(&data, true);
3053 void Spell::WriteAmmoToPacket( WorldPacket * data )
3055 uint32 ammoInventoryType = 0;
3056 uint32 ammoDisplayID = 0;
3058 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3060 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
3061 if(pItem)
3063 ammoInventoryType = pItem->GetProto()->InventoryType;
3064 if( ammoInventoryType == INVTYPE_THROWN )
3065 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
3066 else
3068 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
3069 if(ammoID)
3071 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
3072 if(pProto)
3074 ammoDisplayID = pProto->DisplayInfoID;
3075 ammoInventoryType = pProto->InventoryType;
3078 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
3080 ammoDisplayID = 5996; // normal arrow
3081 ammoInventoryType = INVTYPE_AMMO;
3086 else
3088 for (uint8 i = 0; i < 3; ++i)
3090 if(uint32 item_id = m_caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i))
3092 if(ItemEntry const * itemEntry = sItemStore.LookupEntry(item_id))
3094 if(itemEntry->Class==ITEM_CLASS_WEAPON)
3096 switch(itemEntry->SubClass)
3098 case ITEM_SUBCLASS_WEAPON_THROWN:
3099 ammoDisplayID = itemEntry->DisplayId;
3100 ammoInventoryType = itemEntry->InventoryType;
3101 break;
3102 case ITEM_SUBCLASS_WEAPON_BOW:
3103 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
3104 ammoDisplayID = 5996; // is this need fixing?
3105 ammoInventoryType = INVTYPE_AMMO;
3106 break;
3107 case ITEM_SUBCLASS_WEAPON_GUN:
3108 ammoDisplayID = 5998; // is this need fixing?
3109 ammoInventoryType = INVTYPE_AMMO;
3110 break;
3113 if(ammoDisplayID)
3114 break;
3121 *data << uint32(ammoDisplayID);
3122 *data << uint32(ammoInventoryType);
3125 void Spell::WriteSpellGoTargets( WorldPacket * data )
3127 // This function also fill data for channeled spells:
3128 // m_needAliveTargetMask req for stop channelig if one target die
3129 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
3130 uint32 miss = 0;
3131 for(std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
3133 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
3135 // possibly SPELL_MISS_IMMUNE2 for this??
3136 ihit->missCondition = SPELL_MISS_IMMUNE2;
3137 ++miss;
3139 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3140 ++hit;
3141 else
3142 ++miss;
3145 *data << (uint8)hit;
3146 for(std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
3148 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3150 *data << uint64(ihit->targetGUID);
3151 m_needAliveTargetMask |=ihit->effectMask;
3155 for(std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
3156 *data << uint64(ighit->targetGUID); // Always hits
3158 *data << (uint8)miss;
3159 for(std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
3161 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3163 *data << uint64(ihit->targetGUID);
3164 *data << uint8(ihit->missCondition);
3165 if( ihit->missCondition == SPELL_MISS_REFLECT )
3166 *data << uint8(ihit->reflectResult);
3169 // Reset m_needAliveTargetMask for non channeled spell
3170 if(!IsChanneledSpell(m_spellInfo))
3171 m_needAliveTargetMask = 0;
3174 void Spell::SendLogExecute()
3176 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3178 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3180 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3181 data.append(m_caster->GetPackGUID());
3182 else
3183 data.append(target->GetPackGUID());
3185 data << uint32(m_spellInfo->Id);
3186 uint32 count1 = 1;
3187 data << uint32(count1); // count1 (effect count?)
3188 for(uint32 i = 0; i < count1; ++i)
3190 data << uint32(m_spellInfo->Effect[0]); // spell effect
3191 uint32 count2 = 1;
3192 data << uint32(count2); // count2 (target count?)
3193 for(uint32 j = 0; j < count2; ++j)
3195 switch(m_spellInfo->Effect[0])
3197 case SPELL_EFFECT_POWER_DRAIN:
3198 if(Unit *unit = m_targets.getUnitTarget())
3199 data.append(unit->GetPackGUID());
3200 else
3201 data << uint8(0);
3202 data << uint32(0);
3203 data << uint32(0);
3204 data << float(0);
3205 break;
3206 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3207 if(Unit *unit = m_targets.getUnitTarget())
3208 data.append(unit->GetPackGUID());
3209 else
3210 data << uint8(0);
3211 data << uint32(0); // count?
3212 break;
3213 case SPELL_EFFECT_INTERRUPT_CAST:
3214 if(Unit *unit = m_targets.getUnitTarget())
3215 data.append(unit->GetPackGUID());
3216 else
3217 data << uint8(0);
3218 data << uint32(0); // spellid
3219 break;
3220 case SPELL_EFFECT_DURABILITY_DAMAGE:
3221 if(Unit *unit = m_targets.getUnitTarget())
3222 data.append(unit->GetPackGUID());
3223 else
3224 data << uint8(0);
3225 data << uint32(0);
3226 data << uint32(0);
3227 break;
3228 case SPELL_EFFECT_OPEN_LOCK:
3229 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3230 if(Item *item = m_targets.getItemTarget())
3231 data.append(item->GetPackGUID());
3232 else
3233 data << uint8(0);
3234 break;
3235 case SPELL_EFFECT_CREATE_ITEM:
3236 case SPELL_EFFECT_CREATE_ITEM_2:
3237 data << uint32(m_spellInfo->EffectItemType[0]);
3238 break;
3239 case SPELL_EFFECT_SUMMON:
3240 case SPELL_EFFECT_TRANS_DOOR:
3241 case SPELL_EFFECT_SUMMON_PET:
3242 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3243 case SPELL_EFFECT_CREATE_HOUSE:
3244 case SPELL_EFFECT_DUEL:
3245 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3246 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3247 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3248 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3249 if(Unit *unit = m_targets.getUnitTarget())
3250 data.append(unit->GetPackGUID());
3251 else if(m_targets.getItemTargetGUID())
3252 data.appendPackGUID(m_targets.getItemTargetGUID());
3253 else if(GameObject *go = m_targets.getGOTarget())
3254 data.append(go->GetPackGUID());
3255 else
3256 data << uint8(0); // guid
3257 break;
3258 case SPELL_EFFECT_FEED_PET:
3259 data << uint32(m_targets.getItemTargetEntry());
3260 break;
3261 case SPELL_EFFECT_DISMISS_PET:
3262 if(Unit *unit = m_targets.getUnitTarget())
3263 data.append(unit->GetPackGUID());
3264 else
3265 data << uint8(0);
3266 break;
3267 case SPELL_EFFECT_RESURRECT:
3268 case SPELL_EFFECT_RESURRECT_NEW:
3269 if(Unit *unit = m_targets.getUnitTarget())
3270 data.append(unit->GetPackGUID());
3271 else
3272 data << uint8(0);
3273 break;
3274 default:
3275 return;
3280 m_caster->SendMessageToSet(&data, true);
3283 void Spell::SendInterrupted(uint8 result)
3285 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3286 data.append(m_caster->GetPackGUID());
3287 data << uint8(m_cast_count);
3288 data << uint32(m_spellInfo->Id);
3289 data << uint8(result);
3290 m_caster->SendMessageToSet(&data, true);
3292 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3293 data.append(m_caster->GetPackGUID());
3294 data << uint8(m_cast_count);
3295 data << uint32(m_spellInfo->Id);
3296 data << uint8(result);
3297 m_caster->SendMessageToSet(&data, true);
3300 void Spell::SendChannelUpdate(uint32 time)
3302 if(time == 0)
3304 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
3305 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
3308 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3309 return;
3311 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3312 data.append(m_caster->GetPackGUID());
3313 data << uint32(time);
3315 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3318 void Spell::SendChannelStart(uint32 duration)
3320 WorldObject* target = NULL;
3322 // select first not resisted target from target list for _0_ effect
3323 if(!m_UniqueTargetInfo.empty())
3325 for(std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
3327 if( (itr->effectMask & (1 << 0)) && itr->reflectResult == SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3329 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3330 break;
3334 else if(!m_UniqueGOTargetInfo.empty())
3336 for(std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
3338 if(itr->effectMask & (1 << 0) )
3340 target = m_caster->GetMap()->GetGameObject(itr->targetGUID);
3341 break;
3346 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3348 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3349 data.append(m_caster->GetPackGUID());
3350 data << uint32(m_spellInfo->Id);
3351 data << uint32(duration);
3353 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3356 m_timer = duration;
3357 if(target)
3358 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3359 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3362 void Spell::SendResurrectRequest(Player* target)
3364 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3365 // However, the packet structure differs slightly
3367 const char* sentName = m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3369 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3370 data << uint64(m_caster->GetGUID());
3371 data << uint32(strlen(sentName) + 1);
3373 data << sentName;
3374 data << uint8(0);
3376 data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1);
3377 target->GetSession()->SendPacket(&data);
3380 void Spell::SendPlaySpellVisual(uint32 SpellID)
3382 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3383 return;
3385 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 8 + 4);
3386 data << uint64(m_caster->GetGUID());
3387 data << uint32(SpellID); // spell visual id?
3388 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3391 void Spell::TakeCastItem()
3393 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3394 return;
3396 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3397 if(m_IsTriggeredSpell)
3398 return;
3400 ItemPrototype const *proto = m_CastItem->GetProto();
3402 if(!proto)
3404 // This code is to avoid a crash
3405 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3406 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3407 return;
3410 bool expendable = false;
3411 bool withoutCharges = false;
3413 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
3415 if (proto->Spells[i].SpellId)
3417 // item has limited charges
3418 if (proto->Spells[i].SpellCharges)
3420 if (proto->Spells[i].SpellCharges < 0)
3421 expendable = true;
3423 int32 charges = m_CastItem->GetSpellCharges(i);
3425 // item has charges left
3426 if (charges)
3428 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3429 if (proto->Stackable == 1)
3430 m_CastItem->SetSpellCharges(i, charges);
3431 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3434 // all charges used
3435 withoutCharges = (charges == 0);
3440 if (expendable && withoutCharges)
3442 uint32 count = 1;
3443 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3445 // prevent crash at access to deleted m_targets.getItemTarget
3446 if(m_CastItem==m_targets.getItemTarget())
3447 m_targets.setItemTarget(NULL);
3449 m_CastItem = NULL;
3453 void Spell::TakePower()
3455 if(m_CastItem || m_triggeredByAuraSpell)
3456 return;
3458 // health as power used
3459 if(m_spellInfo->powerType == POWER_HEALTH)
3461 m_caster->ModifyHealth( -(int32)m_powerCost );
3462 return;
3465 if(m_spellInfo->powerType >= MAX_POWERS)
3467 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3468 return;
3471 Powers powerType = Powers(m_spellInfo->powerType);
3473 if(powerType == POWER_RUNE)
3475 TakeRunePower();
3476 return;
3479 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3481 // Set the five second timer
3482 if (powerType == POWER_MANA && m_powerCost > 0)
3483 m_caster->SetLastManaUse(getMSTime());
3486 SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
3488 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3489 return SPELL_CAST_OK;
3491 Player *plr = (Player*)m_caster;
3493 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3494 return SPELL_CAST_OK;
3496 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3498 if(!src)
3499 return SPELL_CAST_OK;
3501 if(src->NoRuneCost())
3502 return SPELL_CAST_OK;
3504 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3506 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3507 runeCost[i] = src->RuneCost[i];
3509 runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
3511 for(uint32 i = 0; i < MAX_RUNES; ++i)
3513 uint8 rune = plr->GetCurrentRune(i);
3514 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3515 runeCost[rune]--;
3518 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3519 if(runeCost[i] > 0)
3520 runeCost[RUNE_DEATH] += runeCost[i];
3522 if(runeCost[RUNE_DEATH] > MAX_RUNES)
3523 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3525 return SPELL_CAST_OK;
3528 void Spell::TakeRunePower()
3530 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3531 return;
3533 Player *plr = (Player*)m_caster;
3535 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3536 return;
3538 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3540 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3541 return;
3543 m_runesState = plr->GetRunesState(); // store previous state
3545 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3547 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3549 runeCost[i] = src->RuneCost[i];
3552 runeCost[RUNE_DEATH] = 0; // calculated later
3554 for(uint32 i = 0; i < MAX_RUNES; ++i)
3556 uint8 rune = plr->GetCurrentRune(i);
3557 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3559 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3560 runeCost[rune]--;
3564 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3566 if(runeCost[RUNE_DEATH] > 0)
3568 for(uint32 i = 0; i < MAX_RUNES; ++i)
3570 uint8 rune = plr->GetCurrentRune(i);
3571 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3573 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3574 runeCost[rune]--;
3575 plr->ConvertRune(i, plr->GetBaseRune(i));
3576 if(runeCost[RUNE_DEATH] == 0)
3577 break;
3582 // you can gain some runic power when use runes
3583 float rp = src->runePowerGain;;
3584 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3585 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3588 void Spell::TakeReagents()
3590 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3591 return;
3593 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3594 return;
3596 Player* p_caster = (Player*)m_caster;
3597 if (p_caster->CanNoReagentCast(m_spellInfo))
3598 return;
3600 for(uint32 x = 0; x < 8; ++x)
3602 if(m_spellInfo->Reagent[x] <= 0)
3603 continue;
3605 uint32 itemid = m_spellInfo->Reagent[x];
3606 uint32 itemcount = m_spellInfo->ReagentCount[x];
3608 // if CastItem is also spell reagent
3609 if (m_CastItem)
3611 ItemPrototype const *proto = m_CastItem->GetProto();
3612 if( proto && proto->ItemId == itemid )
3614 for(int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
3616 // CastItem will be used up and does not count as reagent
3617 int32 charges = m_CastItem->GetSpellCharges(s);
3618 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3620 ++itemcount;
3621 break;
3625 m_CastItem = NULL;
3629 // if getItemTarget is also spell reagent
3630 if (m_targets.getItemTargetEntry() == itemid)
3631 m_targets.setItemTarget(NULL);
3633 p_caster->DestroyItemCount(itemid, itemcount, true);
3637 void Spell::HandleThreatSpells(uint32 spellId)
3639 if(!m_targets.getUnitTarget() || !spellId)
3640 return;
3642 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3643 return;
3645 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3646 if(!threatSpell)
3647 return;
3649 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3651 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3654 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3656 unitTarget = pUnitTarget;
3657 itemTarget = pItemTarget;
3658 gameObjTarget = pGOTarget;
3660 uint8 eff = m_spellInfo->Effect[i];
3662 damage = int32(CalculateDamage((uint8)i, unitTarget) * DamageMultiplier);
3664 sLog.outDebug( "Spell: Effect : %u", eff);
3666 if(eff<TOTAL_SPELL_EFFECTS)
3668 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3669 (*this.*SpellEffects[eff])(i);
3672 else
3674 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3675 if (m_CastItem)
3676 EffectEnchantItemTmp(i);
3677 else
3679 sLog.outError("SPELL: unknown effect %u spell id %u",
3680 eff, m_spellInfo->Id);
3686 void Spell::TriggerSpell()
3688 for(TriggerSpells::const_iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3690 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3691 spell->prepare(&m_targets); // use original spell original targets
3695 SpellCastResult Spell::CheckCast(bool strict)
3697 // check cooldowns to prevent cheating
3698 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3700 if(m_triggeredByAuraSpell)
3701 return SPELL_FAILED_DONT_REPORT;
3702 else
3703 return SPELL_FAILED_NOT_READY;
3706 // only allow triggered spells if at an ended battleground
3707 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3708 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3709 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3710 return SPELL_FAILED_DONT_REPORT;
3712 // only check at first call, Stealth auras are already removed at second call
3713 // for now, ignore triggered spells
3714 if( strict && !m_IsTriggeredSpell)
3716 bool checkForm = true;
3717 // Ignore form req aura
3718 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3719 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3721 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3722 continue;
3723 checkForm = false;
3724 break;
3726 if (checkForm)
3728 // Cannot be used in this stance/form
3729 SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form);
3730 if(shapeError != SPELL_CAST_OK)
3731 return shapeError;
3733 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3734 return SPELL_FAILED_ONLY_STEALTHED;
3738 // caster state requirements
3739 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3740 return SPELL_FAILED_CASTER_AURASTATE;
3741 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3742 return SPELL_FAILED_CASTER_AURASTATE;
3744 // Caster aura req check if need
3745 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3746 return SPELL_FAILED_CASTER_AURASTATE;
3747 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3748 return SPELL_FAILED_CASTER_AURASTATE;
3750 // cancel autorepeat spells if cast start when moving
3751 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3752 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3754 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3755 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3756 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3757 return SPELL_FAILED_MOVING;
3760 if(Unit *target = m_targets.getUnitTarget())
3762 // target state requirements (not allowed state), apply to self also
3763 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3764 return SPELL_FAILED_TARGET_AURASTATE;
3766 // Target aura req check if need
3767 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3768 return SPELL_FAILED_CASTER_AURASTATE;
3769 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3770 return SPELL_FAILED_CASTER_AURASTATE;
3772 if(target != m_caster)
3774 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3775 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3776 return SPELL_FAILED_TARGET_AURASTATE;
3778 // Not allow casting on flying player
3779 if (target->isInFlight())
3780 return SPELL_FAILED_BAD_TARGETS;
3782 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3783 return SPELL_FAILED_LINE_OF_SIGHT;
3785 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3786 // this case can be triggered if rank not found (too low-level target for first rank)
3787 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3788 for(int i=0;i<3;++i)
3789 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3790 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3791 return SPELL_FAILED_LOWLEVEL;
3793 else if (m_caster->GetTypeId() == TYPEID_PLAYER) // Target - is player caster
3795 // Additional check for some spells
3796 // If 0 spell effect empty - client not send target data (need use selection)
3797 // TODO: check it on next client version
3798 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3799 m_spellInfo->EffectImplicitTargetA[1] == TARGET_CHAIN_DAMAGE)
3801 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3802 m_targets.setUnitTarget(target);
3803 else
3804 return SPELL_FAILED_BAD_TARGETS;
3808 // check pet presents
3809 for(int j = 0; j < 3; ++j)
3811 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3813 target = m_caster->GetPet();
3814 if(!target)
3816 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3817 return SPELL_FAILED_DONT_REPORT;
3818 else
3819 return SPELL_FAILED_NO_PET;
3821 break;
3825 //check creature type
3826 //ignore self casts (including area casts when caster selected as target)
3827 if(target != m_caster)
3829 if(!CheckTargetCreatureType(target))
3831 if(target->GetTypeId() == TYPEID_PLAYER)
3832 return SPELL_FAILED_TARGET_IS_PLAYER;
3833 else
3834 return SPELL_FAILED_BAD_TARGETS;
3838 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3839 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3840 if(m_caster != target && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3842 // check correctness positive/negative cast target (pet cast real check and cheating check)
3843 if(IsPositiveSpell(m_spellInfo->Id))
3845 if(m_caster->IsHostileTo(target))
3846 return SPELL_FAILED_BAD_TARGETS;
3848 else
3850 if(m_caster->IsFriendlyTo(target))
3851 return SPELL_FAILED_BAD_TARGETS;
3855 if(IsPositiveSpell(m_spellInfo->Id))
3856 if(target->IsImmunedToSpell(m_spellInfo))
3857 return SPELL_FAILED_TARGET_AURASTATE;
3859 //Must be behind the target.
3860 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3862 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3863 //Exclusion for Mutilate:Facing Limitation was removed in 2.0.1 and 3.0.3, but they still use the same, old Ex-Flags
3864 if( (m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL) &&
3865 (m_spellInfo->SpellFamilyName != SPELLFAMILY_ROGUE || m_spellInfo->SpellFamilyFlags != 0x0020000000000000LL)
3868 SendInterrupted(2);
3869 return SPELL_FAILED_NOT_BEHIND;
3873 //Target must be facing you.
3874 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3876 SendInterrupted(2);
3877 return SPELL_FAILED_NOT_INFRONT;
3880 // check if target is in combat
3881 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3882 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3885 // Spell casted only on battleground
3886 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER)
3887 if(!((Player*)m_caster)->InBattleGround())
3888 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3890 // do not allow spells to be cast in arenas
3891 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3892 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3893 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3894 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * IN_MILISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3895 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3896 if(mapEntry->IsBattleArena())
3897 return SPELL_FAILED_NOT_IN_ARENA;
3899 // zone check
3900 uint32 zone, area;
3901 m_caster->GetZoneAndAreaId(zone, area);
3903 SpellCastResult locRes= spellmgr.GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),zone,area,
3904 m_caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)m_caster) : NULL);
3905 if(locRes != SPELL_CAST_OK)
3906 return locRes;
3908 // not let players cast spells at mount (and let do it to creatures)
3909 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3910 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3912 if(m_caster->isInFlight())
3913 return SPELL_FAILED_NOT_FLYING;
3914 else
3915 return SPELL_FAILED_NOT_MOUNTED;
3918 // always (except passive spells) check items (focus object can be required for any type casts)
3919 if(!IsPassiveSpell(m_spellInfo->Id))
3921 SpellCastResult castResult = CheckItems();
3922 if(castResult != SPELL_CAST_OK)
3923 return castResult;
3926 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3927 if(m_UniqueTargetInfo.empty()) // skip second CheckCast apply (for delayed spells for example)
3929 for(uint8 j = 0; j < 3; ++j)
3931 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3932 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3933 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3934 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3936 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3937 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3938 if(lower==upper)
3939 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);
3941 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3942 float range = GetSpellMaxRange(srange);
3944 Creature* creatureScriptTarget = NULL;
3945 GameObject* goScriptTarget = NULL;
3947 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3949 switch(i_spellST->second.type)
3951 case SPELL_TARGET_TYPE_GAMEOBJECT:
3953 GameObject* p_GameObject = NULL;
3955 if(i_spellST->second.targetEntry)
3957 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3958 Cell cell(p);
3959 cell.data.Part.reserved = ALL_DISTRICT;
3961 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3962 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
3964 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3965 CellLock<GridReadGuard> cell_lock(cell, p);
3966 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3968 if(p_GameObject)
3970 // remember found target and range, next attempt will find more near target with another entry
3971 creatureScriptTarget = NULL;
3972 goScriptTarget = p_GameObject;
3973 range = go_check.GetLastRange();
3976 else if( focusObject ) // Focus Object
3978 float frange = m_caster->GetDistance(focusObject);
3979 if(range >= frange)
3981 creatureScriptTarget = NULL;
3982 goScriptTarget = focusObject;
3983 range = frange;
3986 break;
3988 case SPELL_TARGET_TYPE_CREATURE:
3989 case SPELL_TARGET_TYPE_DEAD:
3990 default:
3992 Creature *p_Creature = NULL;
3994 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3995 Cell cell(p);
3996 cell.data.Part.reserved = ALL_DISTRICT;
3997 cell.SetNoCreate(); // Really don't know what is that???
3999 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
4000 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
4002 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
4004 CellLock<GridReadGuard> cell_lock(cell, p);
4005 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
4007 if(p_Creature )
4009 creatureScriptTarget = p_Creature;
4010 goScriptTarget = NULL;
4011 range = u_check.GetLastRange();
4013 break;
4018 if(creatureScriptTarget)
4020 // store coordinates for TARGET_SCRIPT_COORDINATES
4021 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
4022 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
4024 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
4026 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
4027 AddUnitTarget(creatureScriptTarget, j);
4029 // store explicit target for TARGET_SCRIPT
4030 else
4031 AddUnitTarget(creatureScriptTarget, j);
4033 else if(goScriptTarget)
4035 // store coordinates for TARGET_SCRIPT_COORDINATES
4036 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
4037 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
4039 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
4041 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
4042 AddGOTarget(goScriptTarget, j);
4044 // store explicit target for TARGET_SCRIPT
4045 else
4046 AddGOTarget(goScriptTarget, j);
4048 //Missing DB Entry or targets for this spellEffect.
4049 else
4051 // not report target not existence for triggered spells
4052 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
4053 return SPELL_FAILED_DONT_REPORT;
4054 else
4055 return SPELL_FAILED_BAD_TARGETS;
4061 if(!m_IsTriggeredSpell)
4063 SpellCastResult castResult = CheckRange(strict);
4064 if(castResult != SPELL_CAST_OK)
4065 return castResult;
4069 SpellCastResult castResult = CheckPower();
4070 if(castResult != SPELL_CAST_OK)
4071 return castResult;
4074 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
4076 SpellCastResult castResult = CheckCasterAuras();
4077 if(castResult != SPELL_CAST_OK)
4078 return castResult;
4081 for (int i = 0; i < 3; ++i)
4083 // for effects of spells that have only one target
4084 switch(m_spellInfo->Effect[i])
4086 case SPELL_EFFECT_DUMMY:
4088 if(m_spellInfo->SpellIconID == 1648) // Execute
4090 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4091 return SPELL_FAILED_BAD_TARGETS;
4093 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
4095 if(m_caster->IsInWater())
4096 return SPELL_FAILED_ONLY_ABOVEWATER;
4098 else if(m_spellInfo->SpellIconID == 156) // Holy Shock
4100 // spell different for friends and enemies
4101 // hart version required facing
4102 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, m_targets.getUnitTarget() ))
4103 return SPELL_FAILED_UNIT_NOT_INFRONT;
4105 break;
4107 case SPELL_EFFECT_SCHOOL_DAMAGE:
4109 // Hammer of Wrath
4110 if(m_spellInfo->SpellVisual[0] == 7250)
4112 if (!m_targets.getUnitTarget())
4113 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4115 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4116 return SPELL_FAILED_BAD_TARGETS;
4118 break;
4120 case SPELL_EFFECT_TAMECREATURE:
4122 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
4123 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4125 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
4126 return SPELL_FAILED_HIGHLEVEL;
4128 // use SMSG_PET_TAME_FAILURE?
4129 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
4130 return SPELL_FAILED_BAD_TARGETS;
4132 if(m_caster->GetPetGUID())
4133 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4135 if(m_caster->GetCharmGUID())
4136 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4138 break;
4140 case SPELL_EFFECT_LEARN_SPELL:
4142 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
4143 break;
4145 Pet* pet = m_caster->GetPet();
4147 if(!pet)
4148 return SPELL_FAILED_NO_PET;
4150 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4152 if(!learn_spellproto)
4153 return SPELL_FAILED_NOT_KNOWN;
4155 if(m_spellInfo->spellLevel > pet->getLevel())
4156 return SPELL_FAILED_LOWLEVEL;
4158 break;
4160 case SPELL_EFFECT_LEARN_PET_SPELL:
4162 Pet* pet = m_caster->GetPet();
4164 if(!pet)
4165 return SPELL_FAILED_NO_PET;
4167 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4169 if(!learn_spellproto)
4170 return SPELL_FAILED_NOT_KNOWN;
4172 if(m_spellInfo->spellLevel > pet->getLevel())
4173 return SPELL_FAILED_LOWLEVEL;
4175 break;
4177 case SPELL_EFFECT_FEED_PET:
4179 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4180 return SPELL_FAILED_BAD_TARGETS;
4182 Item* foodItem = m_targets.getItemTarget();
4183 if(!foodItem)
4184 return SPELL_FAILED_BAD_TARGETS;
4186 Pet* pet = m_caster->GetPet();
4188 if(!pet)
4189 return SPELL_FAILED_NO_PET;
4191 if(!pet->HaveInDiet(foodItem->GetProto()))
4192 return SPELL_FAILED_WRONG_PET_FOOD;
4194 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4195 return SPELL_FAILED_FOOD_LOWLEVEL;
4197 if(m_caster->isInCombat() || pet->isInCombat())
4198 return SPELL_FAILED_AFFECTING_COMBAT;
4200 break;
4202 case SPELL_EFFECT_POWER_BURN:
4203 case SPELL_EFFECT_POWER_DRAIN:
4205 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4206 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4207 if(Unit* target = m_targets.getUnitTarget())
4208 if(target != m_caster && target->getPowerType() != m_spellInfo->EffectMiscValue[i])
4209 return SPELL_FAILED_BAD_TARGETS;
4210 break;
4212 case SPELL_EFFECT_CHARGE:
4214 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4215 return SPELL_FAILED_ROOTED;
4217 break;
4219 case SPELL_EFFECT_SKINNING:
4221 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4222 return SPELL_FAILED_BAD_TARGETS;
4224 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4225 return SPELL_FAILED_TARGET_UNSKINNABLE;
4227 Creature* creature = (Creature*)m_targets.getUnitTarget();
4228 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4230 return SPELL_FAILED_TARGET_NOT_LOOTED;
4233 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4235 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4236 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4237 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5);
4238 if (ReqValue > skillValue)
4239 return SPELL_FAILED_LOW_CASTLEVEL;
4241 // chance for fail at orange skinning attempt
4242 if( (m_selfContainer && (*m_selfContainer) == this) &&
4243 skillValue < sWorld.GetConfigMaxSkillValue() &&
4244 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37) )
4245 return SPELL_FAILED_TRY_AGAIN;
4247 break;
4249 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4250 case SPELL_EFFECT_OPEN_LOCK:
4252 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4253 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4254 break;
4256 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4257 // we need a go target in case of TARGET_GAMEOBJECT
4258 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4259 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4260 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4261 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4262 return SPELL_FAILED_BAD_TARGETS;
4264 // In BattleGround players can use only flags and banners
4265 if( ((Player*)m_caster)->InBattleGround() &&
4266 !((Player*)m_caster)->CanUseBattleGroundObject() )
4267 return SPELL_FAILED_TRY_AGAIN;
4269 // get the lock entry
4270 uint32 lockId = 0;
4271 if (GameObject* go = m_targets.getGOTarget())
4272 lockId = go->GetLockId();
4273 else if(Item* itm = m_targets.getItemTarget())
4274 lockId = itm->GetProto()->LockID;
4276 SkillType skillId = SKILL_NONE;
4277 int32 reqSkillValue = 0;
4278 int32 skillValue = 0;
4280 // check lock compatibility
4281 SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue);
4282 if(res != SPELL_CAST_OK)
4283 return res;
4285 // chance for fail at orange mining/herb/LockPicking gathering attempt
4286 // second check prevent fail at rechecks
4287 if(skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
4289 bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
4291 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4292 if((canFailAtMax || skillValue < sWorld.GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37))
4293 return SPELL_FAILED_TRY_AGAIN;
4295 break;
4297 case SPELL_EFFECT_SUMMON_DEAD_PET:
4299 Creature *pet = m_caster->GetPet();
4300 if(!pet)
4301 return SPELL_FAILED_NO_PET;
4303 if(pet->isAlive())
4304 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4306 break;
4308 // This is generic summon effect
4309 case SPELL_EFFECT_SUMMON:
4311 switch(m_spellInfo->EffectMiscValueB[i])
4313 case SUMMON_TYPE_POSESSED:
4314 case SUMMON_TYPE_POSESSED2:
4315 case SUMMON_TYPE_DEMON:
4316 case SUMMON_TYPE_SUMMON:
4318 if(m_caster->GetPetGUID())
4319 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4321 if(m_caster->GetCharmGUID())
4322 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4323 break;
4326 break;
4328 // Not used for summon?
4329 case SPELL_EFFECT_SUMMON_PHANTASM:
4331 if(m_caster->GetPetGUID())
4332 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4334 if(m_caster->GetCharmGUID())
4335 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4337 break;
4339 case SPELL_EFFECT_SUMMON_PET:
4341 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4344 Pet* pet = ((Player*)m_caster)->GetPet();
4346 if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK)
4348 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4349 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4351 else
4352 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4355 if(m_caster->GetCharmGUID())
4356 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4358 break;
4360 case SPELL_EFFECT_SUMMON_PLAYER:
4362 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4363 return SPELL_FAILED_BAD_TARGETS;
4364 if(!((Player*)m_caster)->GetSelection())
4365 return SPELL_FAILED_BAD_TARGETS;
4367 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4368 if( !target || ((Player*)m_caster) == target || !target->IsInSameRaidWith((Player*)m_caster) )
4369 return SPELL_FAILED_BAD_TARGETS;
4371 // check if our map is dungeon
4372 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4374 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4375 if(!instance)
4376 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4377 if ( instance->levelMin > target->getLevel() )
4378 return SPELL_FAILED_LOWLEVEL;
4379 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4380 return SPELL_FAILED_HIGHLEVEL;
4382 break;
4384 case SPELL_EFFECT_LEAP:
4385 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4387 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4388 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4389 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4390 // teleport a bit above terrain level to avoid falling below it
4391 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4392 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4393 return SPELL_FAILED_TRY_AGAIN;
4395 float caster_pos_z = m_caster->GetPositionZ();
4396 // Control the caster to not climb or drop when +-fz > 8
4397 if(!(fz <= caster_pos_z + 8 && fz >= caster_pos_z - 8))
4398 return SPELL_FAILED_TRY_AGAIN;
4400 // not allow use this effect at battleground until battleground start
4401 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4402 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4403 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4404 return SPELL_FAILED_TRY_AGAIN;
4405 break;
4407 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4409 if (m_targets.getUnitTarget() == m_caster)
4410 return SPELL_FAILED_BAD_TARGETS;
4411 break;
4413 default:break;
4417 for (int i = 0; i < 3; ++i)
4419 switch(m_spellInfo->EffectApplyAuraName[i])
4421 case SPELL_AURA_DUMMY:
4423 //custom check
4424 switch(m_spellInfo->Id)
4426 case 61336:
4427 if(m_caster->GetTypeId() != TYPEID_PLAYER || !((Player*)m_caster)->IsInFeralForm())
4428 return SPELL_FAILED_ONLY_SHAPESHIFT;
4429 break;
4430 default:
4431 break;
4433 break;
4435 case SPELL_AURA_MOD_POSSESS:
4436 case SPELL_AURA_MOD_CHARM:
4438 if(m_caster->GetPetGUID())
4439 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4441 if(m_caster->GetCharmGUID())
4442 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4444 if(m_caster->GetCharmerGUID())
4445 return SPELL_FAILED_CHARMED;
4447 if(!m_targets.getUnitTarget())
4448 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4450 if(m_targets.getUnitTarget()->GetCharmerGUID())
4451 return SPELL_FAILED_CHARMED;
4453 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4454 return SPELL_FAILED_HIGHLEVEL;
4456 break;
4458 case SPELL_AURA_MOUNTED:
4460 if (m_caster->IsInWater())
4461 return SPELL_FAILED_ONLY_ABOVEWATER;
4463 if (m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4464 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4466 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4467 if (m_caster->GetTypeId() == TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4468 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4470 ShapeshiftForm form = m_caster->m_form;
4471 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4472 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4473 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4474 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4475 return SPELL_FAILED_NOT_SHAPESHIFT;
4477 break;
4479 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4481 if(!m_targets.getUnitTarget())
4482 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4484 // can be casted at non-friendly unit or own pet/charm
4485 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4486 return SPELL_FAILED_TARGET_FRIENDLY;
4488 break;
4490 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4491 case SPELL_AURA_FLY:
4493 // not allow cast fly spells at old maps by players (all spells is self target)
4494 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4496 if( !((Player*)m_caster)->IsAllowUseFlyMountsHere() )
4497 return SPELL_FAILED_NOT_HERE;
4500 break;
4502 case SPELL_AURA_PERIODIC_MANA_LEECH:
4504 if (!m_targets.getUnitTarget())
4505 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4507 if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem)
4508 break;
4510 if(m_targets.getUnitTarget()->getPowerType() != POWER_MANA)
4511 return SPELL_FAILED_BAD_TARGETS;
4513 break;
4515 default:
4516 break;
4520 // all ok
4521 return SPELL_CAST_OK;
4524 SpellCastResult Spell::CheckPetCast(Unit* target)
4526 if(!m_caster->isAlive())
4527 return SPELL_FAILED_CASTER_DEAD;
4529 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4530 return SPELL_FAILED_SPELL_IN_PROGRESS;
4531 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4532 return SPELL_FAILED_AFFECTING_COMBAT;
4534 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4536 //dead owner (pets still alive when owners ressed?)
4537 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4538 return SPELL_FAILED_CASTER_DEAD;
4540 if(!target && m_targets.getUnitTarget())
4541 target = m_targets.getUnitTarget();
4543 bool need = false;
4544 for(uint32 i = 0; i < 3; ++i)
4546 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)
4548 need = true;
4549 if(!target)
4550 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4551 break;
4554 if(need)
4555 m_targets.setUnitTarget(target);
4557 Unit* _target = m_targets.getUnitTarget();
4559 if(_target) //for target dead/target not valid
4561 if(!_target->isAlive())
4562 return SPELL_FAILED_BAD_TARGETS;
4564 if(IsPositiveSpell(m_spellInfo->Id))
4566 if(m_caster->IsHostileTo(_target))
4567 return SPELL_FAILED_BAD_TARGETS;
4569 else
4571 bool duelvsplayertar = false;
4572 for(int j = 0; j < 3; ++j)
4574 //TARGET_DUELVSPLAYER is positive AND negative
4575 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4577 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4579 return SPELL_FAILED_BAD_TARGETS;
4583 //cooldown
4584 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4585 return SPELL_FAILED_NOT_READY;
4588 return CheckCast(true);
4591 SpellCastResult Spell::CheckCasterAuras() const
4593 // Flag drop spells totally immuned to caster auras
4594 // FIXME: find more nice check for all totally immuned spells
4595 // AttributesEx3 & 0x10000000?
4596 if(m_spellInfo->Id == 23336 || m_spellInfo->Id == 23334 || m_spellInfo->Id == 34991)
4597 return SPELL_CAST_OK;
4599 uint8 school_immune = 0;
4600 uint32 mechanic_immune = 0;
4601 uint32 dispel_immune = 0;
4603 // Check if the spell grants school or mechanic immunity.
4604 // We use bitmasks so the loop is done only once and not on every aura check below.
4605 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4607 for(int i = 0; i < 3; ++i)
4609 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4610 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4611 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4612 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4613 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4614 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4616 // immune movement impairment and loss of control
4617 if(m_spellInfo->Id == 42292)
4618 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4621 // Check whether the cast should be prevented by any state you might have.
4622 SpellCastResult prevented_reason = SPELL_CAST_OK;
4623 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4624 uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
4625 if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4626 prevented_reason = SPELL_FAILED_STUNNED;
4627 else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4628 prevented_reason = SPELL_FAILED_CONFUSED;
4629 else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4630 prevented_reason = SPELL_FAILED_FLEEING;
4631 else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
4632 prevented_reason = SPELL_FAILED_SILENCED;
4633 else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
4634 prevented_reason = SPELL_FAILED_PACIFIED;
4636 // Attr must make flag drop spell totally immune from all effects
4637 if(prevented_reason != SPELL_CAST_OK)
4639 if(school_immune || mechanic_immune || dispel_immune)
4641 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4642 Unit::AuraMap const& auras = m_caster->GetAuras();
4643 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4645 if(itr->second)
4647 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4648 continue;
4649 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4650 continue;
4651 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4652 continue;
4654 // Make a second check for spell failed so the right SPELL_FAILED message is returned.
4655 // That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4656 switch(itr->second->GetModifier()->m_auraname)
4658 case SPELL_AURA_MOD_STUN:
4659 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4660 return SPELL_FAILED_STUNNED;
4661 break;
4662 case SPELL_AURA_MOD_CONFUSE:
4663 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4664 return SPELL_FAILED_CONFUSED;
4665 break;
4666 case SPELL_AURA_MOD_FEAR:
4667 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4668 return SPELL_FAILED_FLEEING;
4669 break;
4670 case SPELL_AURA_MOD_SILENCE:
4671 case SPELL_AURA_MOD_PACIFY:
4672 case SPELL_AURA_MOD_PACIFY_SILENCE:
4673 if( m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
4674 return SPELL_FAILED_PACIFIED;
4675 else if ( m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
4676 return SPELL_FAILED_SILENCED;
4677 break;
4682 // You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4683 else
4684 return prevented_reason;
4686 return SPELL_CAST_OK;
4689 bool Spell::CanAutoCast(Unit* target)
4691 uint64 targetguid = target->GetGUID();
4693 for(uint32 j = 0; j < 3; ++j)
4695 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4697 if( m_spellInfo->StackAmount <= 1)
4699 if( target->HasAura(m_spellInfo->Id, j) )
4700 return false;
4702 else
4704 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4705 return false;
4708 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4710 if( target->HasAura(m_spellInfo->Id, j) )
4711 return false;
4715 SpellCastResult result = CheckPetCast(target);
4717 if(result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4719 FillTargetMap();
4720 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4721 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4722 if( ihit->targetGUID == targetguid )
4723 return true;
4725 return false; //target invalid
4728 SpellCastResult Spell::CheckRange(bool strict)
4730 float range_mod;
4732 // self cast doesn't need range checking -- also for Starshards fix
4733 if (m_spellInfo->rangeIndex == 1)
4734 return SPELL_CAST_OK;
4736 if (strict) //add radius of caster
4737 range_mod = 1.25;
4738 else //add radius of caster and ~5 yds "give"
4739 range_mod = 6.25;
4741 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4742 float max_range = GetSpellMaxRange(srange) + range_mod;
4743 float min_range = GetSpellMinRange(srange);
4745 if(Player* modOwner = m_caster->GetSpellModOwner())
4746 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4748 Unit *target = m_targets.getUnitTarget();
4750 if(target && target != m_caster)
4752 // distance from target in checks
4753 float dist = m_caster->GetCombatDistance(target);
4755 if(dist > max_range)
4756 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4757 if(dist < min_range)
4758 return SPELL_FAILED_TOO_CLOSE;
4759 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4760 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4761 return SPELL_FAILED_UNIT_NOT_INFRONT;
4764 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4766 if(!m_caster->IsWithinDist3d(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ, max_range))
4767 return SPELL_FAILED_OUT_OF_RANGE;
4768 if(m_caster->IsWithinDist3d(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ, min_range))
4769 return SPELL_FAILED_TOO_CLOSE;
4772 return SPELL_CAST_OK;
4775 int32 Spell::CalculatePowerCost()
4777 // item cast not used power
4778 if(m_CastItem)
4779 return 0;
4781 // Spell drain all exist power on cast (Only paladin lay of Hands)
4782 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4784 // If power type - health drain all
4785 if (m_spellInfo->powerType == POWER_HEALTH)
4786 return m_caster->GetHealth();
4787 // Else drain all power
4788 if (m_spellInfo->powerType < MAX_POWERS)
4789 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4790 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4791 return 0;
4794 // Base powerCost
4795 int32 powerCost = m_spellInfo->manaCost;
4796 // PCT cost from total amount
4797 if (m_spellInfo->ManaCostPercentage)
4799 switch (m_spellInfo->powerType)
4801 // health as power used
4802 case POWER_HEALTH:
4803 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4804 break;
4805 case POWER_MANA:
4806 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4807 break;
4808 case POWER_RAGE:
4809 case POWER_FOCUS:
4810 case POWER_ENERGY:
4811 case POWER_HAPPINESS:
4812 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4813 break;
4814 case POWER_RUNE:
4815 case POWER_RUNIC_POWER:
4816 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4817 break;
4818 default:
4819 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4820 return 0;
4823 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4824 // Flat mod from caster auras by spell school
4825 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4826 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4827 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4828 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4829 // Apply cost mod by spell
4830 if(Player* modOwner = m_caster->GetSpellModOwner())
4831 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4833 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4834 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4836 // PCT mod from user auras by school
4837 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4838 if (powerCost < 0)
4839 powerCost = 0;
4840 return powerCost;
4843 SpellCastResult Spell::CheckPower()
4845 // item cast not used power
4846 if(m_CastItem)
4847 return SPELL_CAST_OK;
4849 // health as power used - need check health amount
4850 if(m_spellInfo->powerType == POWER_HEALTH)
4852 if(m_caster->GetHealth() <= m_powerCost)
4853 return SPELL_FAILED_CASTER_AURASTATE;
4854 return SPELL_CAST_OK;
4856 // Check valid power type
4857 if( m_spellInfo->powerType >= MAX_POWERS )
4859 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4860 return SPELL_FAILED_UNKNOWN;
4863 SpellCastResult failReason = CheckRuneCost(m_spellInfo->runeCostID);
4864 if(failReason != SPELL_CAST_OK)
4865 return failReason;
4867 // Check power amount
4868 Powers powerType = Powers(m_spellInfo->powerType);
4869 if(m_caster->GetPower(powerType) < m_powerCost)
4870 return SPELL_FAILED_NO_POWER;
4871 else
4872 return SPELL_CAST_OK;
4875 SpellCastResult Spell::CheckItems()
4877 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4878 return SPELL_CAST_OK;
4880 Player* p_caster = (Player*)m_caster;
4882 // cast item checks
4883 if(m_CastItem)
4885 uint32 itemid = m_CastItem->GetEntry();
4886 if( !p_caster->HasItemCount(itemid, 1) )
4887 return SPELL_FAILED_ITEM_NOT_READY;
4889 ItemPrototype const *proto = m_CastItem->GetProto();
4890 if(!proto)
4891 return SPELL_FAILED_ITEM_NOT_READY;
4893 for (int i = 0; i < 5; ++i)
4894 if (proto->Spells[i].SpellCharges)
4895 if(m_CastItem->GetSpellCharges(i) == 0)
4896 return SPELL_FAILED_NO_CHARGES_REMAIN;
4898 // consumable cast item checks
4899 if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4901 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4902 SpellCastResult failReason = SPELL_CAST_OK;
4903 for (int i = 0; i < 3; ++i)
4905 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4906 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4907 continue;
4909 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4911 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4913 failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4914 continue;
4916 else
4918 failReason = SPELL_CAST_OK;
4919 break;
4923 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4924 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4926 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4928 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4929 continue;
4932 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4933 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4935 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4936 continue;
4938 else
4940 failReason = SPELL_CAST_OK;
4941 break;
4945 if (failReason != SPELL_CAST_OK)
4946 return failReason;
4950 // check target item
4951 if(m_targets.getItemTargetGUID())
4953 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4954 return SPELL_FAILED_BAD_TARGETS;
4956 if(!m_targets.getItemTarget())
4957 return SPELL_FAILED_ITEM_GONE;
4959 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4960 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4962 // if not item target then required item must be equipped
4963 else
4965 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4966 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4969 // check spell focus object
4970 if(m_spellInfo->RequiresSpellFocus)
4972 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4973 Cell cell(p);
4974 cell.data.Part.reserved = ALL_DISTRICT;
4976 GameObject* ok = NULL;
4977 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4978 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(m_caster, ok, go_check);
4980 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4981 CellLock<GridReadGuard> cell_lock(cell, p);
4982 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4984 if(!ok)
4985 return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4987 focusObject = ok; // game object found in range
4990 // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
4991 if (!m_IsTriggeredSpell && !p_caster->CanNoReagentCast(m_spellInfo))
4993 for(uint32 i = 0; i < 8; ++i)
4995 if(m_spellInfo->Reagent[i] <= 0)
4996 continue;
4998 uint32 itemid = m_spellInfo->Reagent[i];
4999 uint32 itemcount = m_spellInfo->ReagentCount[i];
5001 // if CastItem is also spell reagent
5002 if( m_CastItem && m_CastItem->GetEntry() == itemid )
5004 ItemPrototype const *proto = m_CastItem->GetProto();
5005 if(!proto)
5006 return SPELL_FAILED_ITEM_NOT_READY;
5007 for(int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
5009 // CastItem will be used up and does not count as reagent
5010 int32 charges = m_CastItem->GetSpellCharges(s);
5011 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
5013 ++itemcount;
5014 break;
5018 if( !p_caster->HasItemCount(itemid, itemcount) )
5019 return SPELL_FAILED_ITEM_NOT_READY; //0x54
5023 // check totem-item requirements (items presence in inventory)
5024 uint32 totems = 2;
5025 for(int i = 0; i < 2 ; ++i)
5027 if(m_spellInfo->Totem[i] != 0)
5029 if( p_caster->HasItemCount(m_spellInfo->Totem[i], 1) )
5031 totems -= 1;
5032 continue;
5034 }else
5035 totems -= 1;
5037 if(totems != 0)
5038 return SPELL_FAILED_TOTEMS; //0x7C
5040 // Check items for TotemCategory (items presence in inventory)
5041 uint32 TotemCategory = 2;
5042 for(int i= 0; i < 2; ++i)
5044 if(m_spellInfo->TotemCategory[i] != 0)
5046 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
5048 TotemCategory -= 1;
5049 continue;
5052 else
5053 TotemCategory -= 1;
5055 if(TotemCategory != 0)
5056 return SPELL_FAILED_TOTEM_CATEGORY; //0x7B
5058 // special checks for spell effects
5059 for(int i = 0; i < 3; ++i)
5061 switch (m_spellInfo->Effect[i])
5063 case SPELL_EFFECT_CREATE_ITEM:
5065 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
5067 ItemPosCountVec dest;
5068 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
5069 if (msg != EQUIP_ERR_OK )
5071 p_caster->SendEquipError( msg, NULL, NULL );
5072 return SPELL_FAILED_DONT_REPORT;
5075 break;
5077 case SPELL_EFFECT_ENCHANT_ITEM:
5078 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
5080 Item* targetItem = m_targets.getItemTarget();
5081 if(!targetItem)
5082 return SPELL_FAILED_ITEM_NOT_FOUND;
5084 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5085 return SPELL_FAILED_LOWLEVEL;
5086 // Not allow enchant in trade slot for some enchant type
5087 if( targetItem->GetOwner() != m_caster )
5089 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5090 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5091 if(!pEnchant)
5092 return SPELL_FAILED_ERROR;
5093 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5094 return SPELL_FAILED_NOT_TRADEABLE;
5096 break;
5098 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5100 Item *item = m_targets.getItemTarget();
5101 if(!item)
5102 return SPELL_FAILED_ITEM_NOT_FOUND;
5103 // Not allow enchant in trade slot for some enchant type
5104 if( item->GetOwner() != m_caster )
5106 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5107 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5108 if(!pEnchant)
5109 return SPELL_FAILED_ERROR;
5110 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5111 return SPELL_FAILED_NOT_TRADEABLE;
5113 break;
5115 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5116 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5117 break;
5118 case SPELL_EFFECT_DISENCHANT:
5120 if(!m_targets.getItemTarget())
5121 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5123 // prevent disenchanting in trade slot
5124 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5125 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5127 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5128 if(!itemProto)
5129 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5131 uint32 item_quality = itemProto->Quality;
5132 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5133 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5134 if (item_disenchantskilllevel == uint32(-1))
5135 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5136 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5137 return SPELL_FAILED_LOW_CASTLEVEL;
5138 if(item_quality > 4 || item_quality < 2)
5139 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5140 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5141 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5142 if (!itemProto->DisenchantID)
5143 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5144 break;
5146 case SPELL_EFFECT_PROSPECTING:
5148 if(!m_targets.getItemTarget())
5149 return SPELL_FAILED_CANT_BE_PROSPECTED;
5150 //ensure item is a prospectable ore
5151 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5152 return SPELL_FAILED_CANT_BE_PROSPECTED;
5153 //prevent prospecting in trade slot
5154 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5155 return SPELL_FAILED_CANT_BE_PROSPECTED;
5156 //Check for enough skill in jewelcrafting
5157 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5158 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5159 return SPELL_FAILED_LOW_CASTLEVEL;
5160 //make sure the player has the required ores in inventory
5161 if(m_targets.getItemTarget()->GetCount() < 5)
5162 return SPELL_FAILED_NEED_MORE_ITEMS;
5164 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5165 return SPELL_FAILED_CANT_BE_PROSPECTED;
5167 break;
5169 case SPELL_EFFECT_MILLING:
5171 if(!m_targets.getItemTarget())
5172 return SPELL_FAILED_CANT_BE_MILLED;
5173 //ensure item is a millable herb
5174 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5175 return SPELL_FAILED_CANT_BE_MILLED;
5176 //prevent milling in trade slot
5177 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5178 return SPELL_FAILED_CANT_BE_MILLED;
5179 //Check for enough skill in inscription
5180 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5181 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5182 return SPELL_FAILED_LOW_CASTLEVEL;
5183 //make sure the player has the required herbs in inventory
5184 if(m_targets.getItemTarget()->GetCount() < 5)
5185 return SPELL_FAILED_NEED_MORE_ITEMS;
5187 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5188 return SPELL_FAILED_CANT_BE_MILLED;
5190 break;
5192 case SPELL_EFFECT_WEAPON_DAMAGE:
5193 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5195 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5196 if( m_attackType != RANGED_ATTACK )
5197 break;
5198 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5199 if(!pItem || pItem->IsBroken())
5200 return SPELL_FAILED_EQUIPPED_ITEM;
5202 switch(pItem->GetProto()->SubClass)
5204 case ITEM_SUBCLASS_WEAPON_THROWN:
5206 uint32 ammo = pItem->GetEntry();
5207 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5208 return SPELL_FAILED_NO_AMMO;
5209 }; break;
5210 case ITEM_SUBCLASS_WEAPON_GUN:
5211 case ITEM_SUBCLASS_WEAPON_BOW:
5212 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5214 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5215 if(!ammo)
5217 // Requires No Ammo
5218 if(m_caster->GetDummyAura(46699))
5219 break; // skip other checks
5221 return SPELL_FAILED_NO_AMMO;
5224 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5225 if(!ammoProto)
5226 return SPELL_FAILED_NO_AMMO;
5228 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5229 return SPELL_FAILED_NO_AMMO;
5231 // check ammo ws. weapon compatibility
5232 switch(pItem->GetProto()->SubClass)
5234 case ITEM_SUBCLASS_WEAPON_BOW:
5235 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5236 if(ammoProto->SubClass != ITEM_SUBCLASS_ARROW)
5237 return SPELL_FAILED_NO_AMMO;
5238 break;
5239 case ITEM_SUBCLASS_WEAPON_GUN:
5240 if(ammoProto->SubClass != ITEM_SUBCLASS_BULLET)
5241 return SPELL_FAILED_NO_AMMO;
5242 break;
5243 default:
5244 return SPELL_FAILED_NO_AMMO;
5247 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5248 return SPELL_FAILED_NO_AMMO;
5249 }; break;
5250 case ITEM_SUBCLASS_WEAPON_WAND:
5251 break;
5252 default:
5253 break;
5255 break;
5257 default:break;
5261 return SPELL_CAST_OK;
5264 void Spell::Delayed()
5266 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5267 return;
5269 if (m_spellState == SPELL_STATE_DELAYED)
5270 return; // spell is active and can't be time-backed
5272 if(isDelayableNoMore()) // Spells may only be delayed twice
5273 return;
5275 // spells not loosing casting time ( slam, dynamites, bombs.. )
5276 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5277 return;
5279 //check pushback reduce
5280 int32 delaytime = 500; // spellcasting delay is normally 500ms
5281 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5282 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5283 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5284 if(delayReduce >= 100)
5285 return;
5287 delaytime = delaytime * (100 - delayReduce) / 100;
5289 if(int32(m_timer) + delaytime > m_casttime)
5291 delaytime = m_casttime - m_timer;
5292 m_timer = m_casttime;
5294 else
5295 m_timer += delaytime;
5297 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime);
5299 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5300 data.append(m_caster->GetPackGUID());
5301 data << uint32(delaytime);
5303 m_caster->SendMessageToSet(&data, true);
5306 void Spell::DelayedChannel()
5308 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5309 return;
5311 if(isDelayableNoMore()) // Spells may only be delayed twice
5312 return;
5314 //check pushback reduce
5315 int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
5316 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5317 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5318 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5319 if(delayReduce >= 100)
5320 return;
5322 delaytime = delaytime * (100 - delayReduce) / 100;
5324 if(int32(m_timer) < delaytime)
5326 delaytime = m_timer;
5327 m_timer = 0;
5329 else
5330 m_timer -= delaytime;
5332 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5334 for(std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
5336 if ((*ihit).missCondition == SPELL_MISS_NONE)
5338 Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5339 if (unit)
5341 for (int j = 0; j < 3; ++j)
5342 if( ihit->effectMask & (1 << j) )
5343 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5349 for(int j = 0; j < 3; ++j)
5351 // partially interrupt persistent area auras
5352 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5353 if(dynObj)
5354 dynObj->Delay(delaytime);
5357 SendChannelUpdate(m_timer);
5360 void Spell::UpdatePointers()
5362 if(m_originalCasterGUID==m_caster->GetGUID())
5363 m_originalCaster = m_caster;
5364 else
5366 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5367 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5370 m_targets.Update(m_caster);
5373 bool Spell::IsAffectedByAura(Aura *aura)
5375 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5378 bool Spell::CheckTargetCreatureType(Unit* target) const
5380 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5382 // Curse of Doom : not find another way to fix spell target check :/
5383 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5385 // not allow cast at player
5386 if(target->GetTypeId()==TYPEID_PLAYER)
5387 return false;
5389 spellCreatureTargetMask = 0x7FF;
5392 // Dismiss Pet and Taming Lesson skipped
5393 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5394 spellCreatureTargetMask = 0;
5396 if (spellCreatureTargetMask)
5398 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5400 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5402 return true;
5405 CurrentSpellTypes Spell::GetCurrentContainer()
5407 if (IsNextMeleeSwingSpell())
5408 return(CURRENT_MELEE_SPELL);
5409 else if (IsAutoRepeat())
5410 return(CURRENT_AUTOREPEAT_SPELL);
5411 else if (IsChanneledSpell(m_spellInfo))
5412 return(CURRENT_CHANNELED_SPELL);
5413 else
5414 return(CURRENT_GENERIC_SPELL);
5417 bool Spell::CheckTarget( Unit* target, uint32 eff )
5419 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5420 if(m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SELF )
5422 if (!CheckTargetCreatureType(target))
5423 return false;
5426 // Check Aura spell req (need for AoE spells)
5427 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5428 return false;
5429 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5430 return false;
5432 // Check targets for not_selectable unit flag and remove
5433 // A player can cast spells on his pet (or other controlled unit) though in any state
5434 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5436 // any unattackable target skipped
5437 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5438 return false;
5440 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5441 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5442 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5443 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5444 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5445 return false;
5448 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5449 if( target != m_caster && target->GetTypeId() == TYPEID_PLAYER)
5451 if(((Player*)target)->GetVisibility() == VISIBILITY_OFF)
5452 return false;
5454 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5455 return false;
5458 //Check targets for LOS visibility (except spells without range limitations )
5459 switch(m_spellInfo->Effect[eff])
5461 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5462 break;
5463 case SPELL_EFFECT_DUMMY:
5464 if(m_spellInfo->Id != 20577) // Cannibalize
5465 break;
5466 //fall through
5467 case SPELL_EFFECT_RESURRECT_NEW:
5468 // player far away, maybe his corpse near?
5469 if(target != m_caster && !target->IsWithinLOSInMap(m_caster))
5471 if(!m_targets.getCorpseTargetGUID())
5472 return false;
5474 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
5475 if(!corpse)
5476 return false;
5478 if(target->GetGUID() != corpse->GetOwnerGUID())
5479 return false;
5481 if(!corpse->IsWithinLOSInMap(m_caster))
5482 return false;
5485 // all ok by some way or another, skip normal check
5486 break;
5487 default: // normal case
5488 // Get GO cast coordinates if original caster -> GO
5489 WorldObject *caster = NULL;
5490 if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
5491 caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
5492 if (!caster)
5493 caster = m_caster;
5494 if(target != m_caster && !target->IsWithinLOSInMap(caster))
5495 return false;
5496 break;
5499 return true;
5502 bool Spell::IsNeedSendToClient() const
5504 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5505 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5508 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5510 for(std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
5511 if(itr->effectMask & (1 << effect))
5512 return true;
5514 for(std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
5515 if(itr->effectMask & (1 << effect))
5516 return true;
5518 for(std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr)
5519 if(itr->effectMask & (1 << effect))
5520 return true;
5522 return false;
5525 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5527 m_Spell = spell;
5530 SpellEvent::~SpellEvent()
5532 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5533 m_Spell->cancel();
5535 if (m_Spell->IsDeletable())
5537 delete m_Spell;
5539 else
5541 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5542 (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id);
5546 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5548 // update spell if it is not finished
5549 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5550 m_Spell->update(p_time);
5552 // check spell state to process
5553 switch (m_Spell->getState())
5555 case SPELL_STATE_FINISHED:
5557 // spell was finished, check deletable state
5558 if (m_Spell->IsDeletable())
5560 // check, if we do have unfinished triggered spells
5561 return true; // spell is deletable, finish event
5563 // event will be re-added automatically at the end of routine)
5564 } break;
5566 case SPELL_STATE_CASTING:
5568 // this spell is in channeled state, process it on the next update
5569 // event will be re-added automatically at the end of routine)
5570 } break;
5572 case SPELL_STATE_DELAYED:
5574 // first, check, if we have just started
5575 if (m_Spell->GetDelayStart() != 0)
5577 // no, we aren't, do the typical update
5578 // check, if we have channeled spell on our hands
5579 if (IsChanneledSpell(m_Spell->m_spellInfo))
5581 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5582 // check, if we have casting anything else except this channeled spell and autorepeat
5583 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5585 // another non-melee non-delayed spell is casted now, abort
5586 m_Spell->cancel();
5588 else
5590 // do the action (pass spell to channeling state)
5591 m_Spell->handle_immediate();
5593 // event will be re-added automatically at the end of routine)
5595 else
5597 // run the spell handler and think about what we can do next
5598 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5599 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5600 if (n_offset)
5602 // re-add us to the queue
5603 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5604 return false; // event not complete
5606 // event complete
5607 // finish update event will be re-added automatically at the end of routine)
5610 else
5612 // delaying had just started, record the moment
5613 m_Spell->SetDelayStart(e_time);
5614 // re-plan the event for the delay moment
5615 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5616 return false; // event not complete
5618 } break;
5620 default:
5622 // all other states
5623 // event will be re-added automatically at the end of routine)
5624 } break;
5627 // spell processing not complete, plan event on the next update interval
5628 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5629 return false; // event not complete
5632 void SpellEvent::Abort(uint64 /*e_time*/)
5634 // oops, the spell we try to do is aborted
5635 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5636 m_Spell->cancel();
5639 bool SpellEvent::IsDeletable() const
5641 return m_Spell->IsDeletable();
5644 SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
5646 if(!lockId) // possible case for GO and maybe for items.
5647 return SPELL_CAST_OK;
5649 // Get LockInfo
5650 LockEntry const *lockInfo = sLockStore.LookupEntry(lockId);
5652 if (!lockInfo)
5653 return SPELL_FAILED_BAD_TARGETS;
5655 bool reqKey = false; // some locks not have reqs
5657 for(int j = 0; j < 8; ++j)
5659 switch(lockInfo->Type[j])
5661 // check key item (many fit cases can be)
5662 case LOCK_KEY_ITEM:
5663 if(lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[j])
5664 return SPELL_CAST_OK;
5665 reqKey = true;
5666 break;
5667 // check key skill (only single first fit case can be)
5668 case LOCK_KEY_SKILL:
5670 reqKey = true;
5672 // wrong locktype, skip
5673 if(uint32(m_spellInfo->EffectMiscValue[effIndex]) != lockInfo->Index[j])
5674 continue;
5676 skillId = SkillByLockType(LockType(lockInfo->Index[j]));
5678 if ( skillId != SKILL_NONE )
5680 // skill bonus provided by casting spell (mostly item spells)
5681 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
5682 uint32 spellSkillBonus = uint32(m_currentBasePoints[effIndex]+1);
5683 reqSkillValue = lockInfo->Skill[j];
5685 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
5686 skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
5687 0 : ((Player*)m_caster)->GetSkillValue(skillId);
5689 skillValue += spellSkillBonus;
5691 if (skillValue < reqSkillValue)
5692 return SPELL_FAILED_LOW_CASTLEVEL;
5695 return SPELL_CAST_OK;
5700 if(reqKey)
5701 return SPELL_FAILED_BAD_TARGETS;
5703 return SPELL_CAST_OK;
5706 void Spell::FillAreaTargets( UnitList& TagUnitMap, float x, float y, float radius, SpellNotifyPushType pushType, SpellTargets spellTargets )
5708 CellPair p(MaNGOS::ComputeCellPair(x, y));
5709 Cell cell(p);
5710 cell.data.Part.reserved = ALL_DISTRICT;
5711 cell.SetNoCreate();
5712 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, pushType, spellTargets);
5713 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
5714 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
5715 CellLock<GridReadGuard> cell_lock(cell, p);
5716 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
5717 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());