From f09b5a6bea89da1b73a0beb05b977feba3285562 Mon Sep 17 00:00:00 2001 From: QAston Date: Tue, 21 Feb 2012 20:03:27 +0100 Subject: Core/Db/Conditions: -Drop condition CONDITION_SPELL_SCRIPT_TARGET, use other condition types instead -Change CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET to CONDITION_SOURCE_TYPE_SPELL_IMPLICIT_TARGET: --allow using this condition for more spell implicit target types (not just ENTRY) --SourceGroup value for this src type is now effMask and it's now required Core/Spells: Unify the way implicit targets are handled, fully implement some partially implemented target types, fix some minor bugs found on the way, general improvements and cleanup. --- src/server/game/Spells/Spell.cpp | 3816 +++++++++++++++++++------------------- 1 file changed, 1914 insertions(+), 1902 deletions(-) (limited to 'src/server/game/Spells/Spell.cpp') diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index 53356772ff6..207ab2b663d 100755 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -592,19 +592,6 @@ Spell::~Spell() CheckEffectExecuteData(); } -template -WorldObject* Spell::FindCorpseUsing() -{ - // non-standard target selection - float max_range = m_spellInfo->GetMaxRange(false); - - WorldObject* result = NULL; - T u_check(m_caster, max_range); - Trinity::WorldObjectSearcher searcher(m_caster, result, u_check); - m_caster->GetMap()->VisitFirstFound(m_caster->GetPositionX(), m_caster->GetPositionY(), max_range, searcher); - return result; -} - void Spell::InitExplicitTargets(SpellCastTargets const& targets) { m_targets = targets; @@ -707,7 +694,8 @@ void Spell::SelectSpellTargets() { // select targets for cast phase SelectExplicitTargets(); - uint32 processedTargets = 0; + + uint32 processedAreaEffectsMask = 0; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { // not call for empty effect. @@ -715,9 +703,6 @@ void Spell::SelectSpellTargets() if (!m_spellInfo->Effects[i].IsEffect()) continue; - if (processedTargets & (1 << i)) - continue; - // set expected type of implicit targets to be sent to client uint32 implicitTargetMask = GetTargetFlagMask(m_spellInfo->Effects[i].TargetA.GetObjectType()) | GetTargetFlagMask(m_spellInfo->Effects[i].TargetB.GetObjectType()); if (implicitTargetMask & TARGET_FLAG_UNIT) @@ -725,13 +710,8 @@ void Spell::SelectSpellTargets() if (implicitTargetMask & (TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_GAMEOBJECT_ITEM)) m_targets.SetTargetFlag(TARGET_FLAG_GAMEOBJECT); - uint32 targetA = m_spellInfo->Effects[i].TargetA.GetTarget(); - uint32 targetB = m_spellInfo->Effects[i].TargetB.GetTarget(); - - if (targetA) - processedTargets |= SelectEffectTargets(i, m_spellInfo->Effects[i].TargetA); - if (targetB) - processedTargets |= SelectEffectTargets(i, m_spellInfo->Effects[i].TargetB); + SelectEffectImplicitTargets(SpellEffIndex(i), m_spellInfo->Effects[i].TargetA, processedAreaEffectsMask); + SelectEffectImplicitTargets(SpellEffIndex(i), m_spellInfo->Effects[i].TargetB, processedAreaEffectsMask); // Select targets of effect based on effect type // those are used when no valid target could be added for spell effect based on spell target type @@ -793,2074 +773,2101 @@ void Spell::SelectSpellTargets() } } -void Spell::SelectEffectTypeImplicitTargets(uint8 effIndex) +void Spell::SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32& processedEffectMask) { - // special case for SPELL_EFFECT_SUMMON_RAF_FRIEND and SPELL_EFFECT_SUMMON_PLAYER - // TODO: this is a workaround - target shouldn't be stored in target map for those spells - switch (m_spellInfo->Effects[effIndex].Effect) + if (!targetType.GetTarget()) + return; + + uint32 effectMask = 1 << effIndex; + // set the same target list for all effects + // some spells appear to need this, however this requires more research + switch (targetType.GetSelectionCategory()) { - case SPELL_EFFECT_SUMMON_RAF_FRIEND: - case SPELL_EFFECT_SUMMON_PLAYER: - if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->GetSelection()) + case TARGET_SELECT_CATEGORY_NEARBY: + case TARGET_SELECT_CATEGORY_CONE: + case TARGET_SELECT_CATEGORY_AREA: + // targets for effect already selected + if (effectMask & processedEffectMask) + return; + // choose which targets we can select at once + for (uint32 j = effIndex + 1; j < MAX_SPELL_EFFECTS; ++j) + if (GetSpellInfo()->Effects[effIndex].TargetA.GetTarget() == GetSpellInfo()->Effects[j].TargetA.GetTarget() && + GetSpellInfo()->Effects[effIndex].TargetB.GetTarget() == GetSpellInfo()->Effects[j].TargetB.GetTarget() && + GetSpellInfo()->Effects[effIndex].ImplicitTargetConditions == GetSpellInfo()->Effects[j].ImplicitTargetConditions && + GetSpellInfo()->Effects[effIndex].CalcRadius(m_caster) == GetSpellInfo()->Effects[j].CalcRadius(m_caster)) + effectMask |= 1 << j; + processedEffectMask |= effectMask; + } + + switch(targetType.GetSelectionCategory()) + { + case TARGET_SELECT_CATEGORY_CHANNEL: + SelectImplicitChannelTargets(effIndex, targetType); + break; + case TARGET_SELECT_CATEGORY_NEARBY: + SelectImplicitNearbyTargets(effIndex, targetType, effectMask); + break; + case TARGET_SELECT_CATEGORY_CONE: + SelectImplicitConeTargets(effIndex, targetType, effectMask); + break; + case TARGET_SELECT_CATEGORY_AREA: + SelectImplicitAreaTargets(effIndex, targetType, effectMask); + break; + case TARGET_SELECT_CATEGORY_DEFAULT: + switch (targetType.GetObjectType()) { - Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetSelection()); - if (target) - AddUnitTarget(target, 1 << effIndex, false); + case TARGET_OBJECT_TYPE_SRC: + switch(targetType.GetReferenceType()) + { + case TARGET_REFERENCE_TYPE_CASTER: + m_targets.SetSrc(*m_caster); + break; + default: + ASSERT("Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_SRC"); + break; + } + break; + case TARGET_OBJECT_TYPE_DEST: + switch(targetType.GetReferenceType()) + { + case TARGET_REFERENCE_TYPE_CASTER: + SelectImplicitCasterDestTargets(effIndex, targetType); + break; + case TARGET_REFERENCE_TYPE_TARGET: + SelectImplicitCasterDestTargets(effIndex, targetType); + break; + case TARGET_REFERENCE_TYPE_DEST: + SelectImplicitDestDestTargets(effIndex, targetType); + break; + default: + ASSERT("Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_DEST"); + break; + } + break; + default: + switch(targetType.GetReferenceType()) + { + case TARGET_REFERENCE_TYPE_CASTER: + SelectImplicitCasterObjectTargets(effIndex, targetType); + break; + case TARGET_REFERENCE_TYPE_TARGET: + SelectImplicitTargetObjectTargets(effIndex, targetType); + break; + default: + ASSERT("Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT"); + break; + } + break; } - return; + break; + case TARGET_SELECT_CATEGORY_NYI: + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: target type %u, found in spellID %u, effect %u is not implemented yet!", m_spellInfo->Id, effIndex, targetType.GetTarget()); + break; default: + ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target category"); break; } +} - // select spell implicit targets based on effect type - if (!m_spellInfo->Effects[effIndex].GetImplicitTargetType()) +void Spell::SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) +{ + if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) + { + ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target reference type"); return; + } - uint32 targetMask = m_spellInfo->Effects[effIndex].GetMissingTargetMask(); - - if (!targetMask) + Spell* channeledSpell = m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL); + if (!channeledSpell) + { + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::SelectImplicitChannelTargets: cannot find channel spell for spell ID %u, effect %u", m_spellInfo->Id, effIndex); return; - - switch (m_spellInfo->Effects[effIndex].GetImplicitTargetType()) + } + switch (targetType.GetType()) { - // add explicit object target or self to the target map - case EFFECT_IMPLICIT_TARGET_EXPLICIT: - // player which not released his spirit is Unit, but target flag for it is TARGET_FLAG_CORPSE_MASK - if (targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK)) - { - if (Unit* unitTarget = m_targets.GetUnitTarget()) - AddUnitTarget(unitTarget, 1 << effIndex, false); - else if (targetMask & TARGET_FLAG_CORPSE_MASK) - { - if (Corpse* corpseTarget = m_targets.GetCorpseTarget()) - { - // TODO: this is a workaround - corpses should be added to spell target map too, but we can't do that so we add owner instead - if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) - AddUnitTarget(owner, 1 << effIndex, false); - } - } - else //if (targetMask & TARGET_FLAG_UNIT_MASK) - { - AddUnitTarget(m_caster, 1 << effIndex, false); - } - } - if (targetMask & TARGET_FLAG_ITEM_MASK) - { - if (Item* itemTarget = m_targets.GetItemTarget()) - AddItemTarget(itemTarget, 1 << effIndex); - } - if (targetMask & TARGET_FLAG_GAMEOBJECT_MASK) - { - if (GameObject* gObjTarget = m_targets.GetGOTarget()) - AddGOTarget(gObjTarget, 1 << effIndex); - } + case TARGET_UNIT_CHANNEL_TARGET: + // unit target may be no longer avalible - teleported out of map for example + if (Unit* target = Unit::GetUnit(*m_caster, channeledSpell->m_targets.GetUnitTargetGUID())) + AddUnitTarget(target, 1 << effIndex); + else + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: cannot find channel spell target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); break; - // add self to the target map - case EFFECT_IMPLICIT_TARGET_CASTER: - if (targetMask & TARGET_FLAG_UNIT_MASK) - AddUnitTarget(m_caster, 1 << effIndex, false); + case TARGET_DEST_CHANNEL_TARGET: + if (channeledSpell->m_targets.HasDst()) + m_targets.SetDst(channeledSpell->m_targets); + else if (WorldObject* target = ObjectAccessor::GetWorldObject(*m_caster, channeledSpell->m_targets.GetObjectTargetGUID())) + m_targets.SetDst(*target); + else + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: cannot find channel spell destination for spell ID %u, effect %u", m_spellInfo->Id, effIndex); + break; + case TARGET_DEST_CHANNEL_CASTER: + m_targets.SetDst(*channeledSpell->GetCaster()); break; default: + ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target type"); break; } } -void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/) +void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { - //========================================================================================== - // Now fill data for trigger system, need know: - // can spell trigger another or not (m_canTrigger) - // Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_procEx) - //========================================================================================== + if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) + { + ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target reference type"); + return; + } - m_procVictim = m_procAttacker = 0; - // Get data for type of attack and fill base info for trigger - switch (m_spellInfo->DmgClass) + float range; + switch (targetType.GetCheckType()) { - case SPELL_DAMAGE_CLASS_MELEE: - m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS; - if (m_attackType == OFF_ATTACK) - m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK; - else - m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK; - m_procVictim = PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS; + case TARGET_CHECK_ENEMY: + range = m_spellInfo->GetMaxRange(false, m_caster, this); break; - case SPELL_DAMAGE_CLASS_RANGED: - // Auto attack - if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) - { - m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; - m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; - } - else // Ranged spell attack - { - m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS; - m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS; - } + case TARGET_CHECK_ALLY: + case TARGET_CHECK_PARTY: + case TARGET_CHECK_RAID: + case TARGET_CHECK_RAID_CLASS: + range = m_spellInfo->GetMaxRange(true, m_caster, this); + break; + case TARGET_CHECK_ENTRY: + case TARGET_CHECK_DEFAULT: + range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive(), m_caster, this); break; default: - if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && - m_spellInfo->EquippedItemSubClassMask & (1<AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) // Wands auto attack - { - m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; - m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; - } - // For other spells trigger procflags are set in Spell::DoAllEffectOnTarget - // Because spell positivity is dependant on target + ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented selection check type"); + break; } - m_procEx = PROC_EX_NONE; - - // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection - if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && - (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow - m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc - m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap - m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION; + ConditionList* condList = m_spellInfo->Effects[effIndex].ImplicitTargetConditions; - /* Effects which are result of aura proc from triggered spell cannot proc - to prevent chain proc of these spells */ + // handle emergency case - try to use other provided targets if no conditions provided + if (targetType.GetCheckType() == TARGET_CHECK_ENTRY && !condList || condList->empty()) + { + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::SelectImplicitNearbyTargets: no conditions entry for target with TARGET_CHECK_ENTRY of spell ID %u, effect %u - selecting default targets", m_spellInfo->Id, effIndex); + switch (targetType.GetObjectType()) + { + case TARGET_OBJECT_TYPE_GOBJ: + if (m_spellInfo->RequiresSpellFocus) + { + if (focusObject) + AddGOTarget(focusObject, effMask); + return; + } + break; + case TARGET_OBJECT_TYPE_DEST: + if (m_spellInfo->RequiresSpellFocus) + { + if (focusObject) + m_targets.SetDst(*focusObject); + return; + } + break; + default: + break; + } + } - // Hellfire Effect - trigger as DOT - if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040) + WorldObject* target = SearchNearbyTarget(range, targetType.GetObjectType(), targetType.GetCheckType(), condList); + if (!target) { - m_procAttacker = PROC_FLAG_DONE_PERIODIC; - m_procVictim = PROC_FLAG_TAKEN_PERIODIC; + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::SelectImplicitNearbyTargets: cannot find nearby target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); + return; } - // Ranged autorepeat attack is set as triggered spell - ignore it - if (!(m_procAttacker & PROC_FLAG_DONE_RANGED_AUTO_ATTACK)) + switch (targetType.GetObjectType()) { - if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS && - (m_spellInfo->AttributesEx2 & SPELL_ATTR2_TRIGGERED_CAN_TRIGGER_PROC || - m_spellInfo->AttributesEx3 & SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_PROC_2)) - m_procEx |= PROC_EX_INTERNAL_CANT_PROC; - else if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) - m_procEx |= PROC_EX_INTERNAL_TRIGGERED; + case TARGET_OBJECT_TYPE_UNIT: + if (Unit* unitTarget = target->ToUnit()) + AddUnitTarget(unitTarget, effMask, false); + break; + case TARGET_OBJECT_TYPE_GOBJ: + if (GameObject* gobjTarget = target->ToGameObject()) + AddGOTarget(gobjTarget, effMask); + break; + case TARGET_OBJECT_TYPE_DEST: + m_targets.SetDst(*target); + break; + default: + ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target object type"); + break; } - // Totem casts require spellfamilymask defined in spell_proc_event to proc - if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isTotem() && m_caster->IsControlledByPlayer()) - m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY; -} -void Spell::CleanupTargetList() -{ - m_UniqueTargetInfo.clear(); - m_UniqueGOTargetInfo.clear(); - m_UniqueItemInfo.clear(); - m_delayMoment = 0; + SelectImplicitChainTargets(effIndex, targetType, target, effMask); } -void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= true*/) +void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { - for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) - if (!m_spellInfo->Effects[effIndex].IsEffect() || !CheckEffectTarget(target, effIndex)) - effectMask &= ~(1 << effIndex); - - // no effects left - if (!effectMask) + if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) + { + ASSERT(false && "Spell::SelectImplicitConeTargets: received not implemented target reference type"); return; + } + std::list targets; + SpellTargetObjectTypes objectType = targetType.GetObjectType(); + SpellTargetCheckTypes selectionType = targetType.GetCheckType(); + ConditionList* condList = m_spellInfo->Effects[effIndex].ImplicitTargetConditions; + float coneAngle = M_PI/2; + float radius = m_spellInfo->Effects[effIndex].CalcRadius(m_caster) * m_spellValue->RadiusMod; - if (checkIfValid) - if (m_spellInfo->CheckTarget(m_caster, target, true) != SPELL_CAST_OK) - return; + if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList)) + { + Trinity::WorldObjectSpellConeTargetCheck check(coneAngle, radius, m_caster, m_spellInfo, selectionType, condList); + Trinity::WorldObjectListSearcher searcher(m_caster, targets, check, containerTypeMask); + SearchTargets > (searcher, containerTypeMask, m_caster, m_caster, radius); - // Check for effect immune skip if immuned - for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) - if (target->IsImmunedToSpellEffect(m_spellInfo, effIndex)) - effectMask &= ~(1 << effIndex); + if (!targets.empty()) + { + // Other special target selection goes here + if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) + { + Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); + for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) + if ((*j)->IsAffectedOnSpell(m_spellInfo)) + maxTargets += (*j)->GetAmount(); - uint64 targetGUID = target->GetGUID(); + Trinity::RandomResizeList(targets, maxTargets); + } - // Lookup target in already in list - for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + // for compability with older code - add only unit and go targets + // TODO: remove this + std::list unitTargets; + std::list gObjTargets; + + for (std::list::iterator itr = targets.begin(); itr != targets.end(); ++itr) + { + if (Unit* unitTarget = (*itr)->ToUnit()) + unitTargets.push_back(unitTarget); + else if (GameObject* gObjTarget = (*itr)->ToGameObject()) + gObjTargets.push_back(gObjTarget); + } + + CallScriptAfterUnitTargetSelectHandlers(unitTargets, effIndex); + + for (std::list::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr) + AddUnitTarget(*itr, effMask, false); + + for (std::list::iterator itr = gObjTargets.begin(); itr != gObjTargets.end(); ++itr) + AddGOTarget(*itr, effMask); + } + } +} + +void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) +{ + Unit* referer = NULL; + switch (targetType.GetReferenceType()) { - if (targetGUID == ihit->targetGUID) // Found in list + case TARGET_REFERENCE_TYPE_SRC: + case TARGET_REFERENCE_TYPE_DEST: + case TARGET_REFERENCE_TYPE_CASTER: + referer = m_caster; + break; + case TARGET_REFERENCE_TYPE_TARGET: + referer = m_targets.GetUnitTarget(); + break; + case TARGET_REFERENCE_TYPE_LAST: { - ihit->effectMask |= effectMask; // Immune effects removed from mask - ihit->scaleAura = false; - if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != target) + // find last added target for this effect + for (std::list::reverse_iterator ihit = m_UniqueTargetInfo.rbegin(); ihit != m_UniqueTargetInfo.rend(); ++ihit) { - SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); - if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel) - ihit->scaleAura = true; + if (ihit->effectMask & (1<targetGUID); + break; + } } - return; + break; } + default: + ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); + return; } + if (!referer) + return; - // This is new target calculate data for him + Position const* center = NULL; + switch (targetType.GetReferenceType()) + { + case TARGET_REFERENCE_TYPE_SRC: + center = m_targets.GetSrc(); + break; + case TARGET_REFERENCE_TYPE_DEST: + center = m_targets.GetDst(); + break; + case TARGET_REFERENCE_TYPE_CASTER: + case TARGET_REFERENCE_TYPE_TARGET: + case TARGET_REFERENCE_TYPE_LAST: + center = referer; + break; + default: + ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); + return; + } + std::list targets; + float radius = m_spellInfo->Effects[effIndex].CalcRadius(m_caster) * m_spellValue->RadiusMod; + SearchAreaTargets(targets, radius, center, referer, targetType.GetObjectType(), targetType.GetCheckType(), m_spellInfo->Effects[effIndex].ImplicitTargetConditions); - // Get spell hit result on target - TargetInfo targetInfo; - targetInfo.targetGUID = targetGUID; // Store target GUID - targetInfo.effectMask = effectMask; // Store all effects not immune - targetInfo.processed = false; // Effects not apply on target - targetInfo.alive = target->isAlive(); - targetInfo.damage = 0; - targetInfo.crit = false; - targetInfo.scaleAura = false; - if (m_auraScaleMask && targetInfo.effectMask == m_auraScaleMask && m_caster != target) + // Custom entries + // TODO: remove those + switch (m_spellInfo->Id) { - SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); - if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel) - targetInfo.scaleAura = true; - } + case 46584: // Raise Dead + { + if (Player* playerCaster = m_caster->ToPlayer()) + { + for (std::list::iterator itr = targets.begin(); itr != targets.end(); ++itr) + { + switch ((*itr)->GetTypeId()) + { + case TYPEID_UNIT: + case TYPEID_PLAYER: + { + Unit* unitTarget = (*itr)->ToUnit(); + if (unitTarget->isAlive() || !playerCaster->isHonorOrXPTarget(unitTarget) + || ((unitTarget->GetCreatureTypeMask() & (1 << (CREATURE_TYPE_HUMANOID-1))) == 0) + || (unitTarget->GetDisplayId() != unitTarget->GetNativeDisplayId())) + break; + AddUnitTarget(unitTarget, effMask, false); + // no break; + } + case TYPEID_CORPSE: // wont work until corpses are allowed in target lists, but at least will send dest in packet + m_targets.SetDst(*(*itr)); + return; // nothing more to do here + default: + break; + } + } + } + return; // don't add targets to target map + } + // Corpse Explosion + case 49158: + case 51325: + case 51326: + case 51327: + case 51328: + // check if our target is not valid (spell can target ghoul or dead unit) + if (!(m_targets.GetUnitTarget() && m_targets.GetUnitTarget()->GetDisplayId() == m_targets.GetUnitTarget()->GetNativeDisplayId() && + ((m_targets.GetUnitTarget()->GetEntry() == 26125 && m_targets.GetUnitTarget()->GetOwnerGUID() == m_caster->GetGUID()) + || m_targets.GetUnitTarget()->isDead()))) + { + // remove existing targets + CleanupTargetList(); - // Calculate hit result - if (m_originalCaster) + for (std::list::iterator itr = targets.begin(); itr != targets.end(); ++itr) + { + switch ((*itr)->GetTypeId()) + { + case TYPEID_UNIT: + case TYPEID_PLAYER: + if (!(*itr)->ToUnit()->isDead()) + break; + AddUnitTarget((*itr)->ToUnit(), 1 << effIndex, false); + return; + default: + break; + } + } + if (m_caster->GetTypeId() == TYPEID_PLAYER) + m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true); + SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW); + finish(false); + } + return; + default: + break; + } + std::list unitTargets; + std::list gObjTargets; + // for compability with older code - add only unit and go targets + // TODO: remove this + for (std::list::iterator itr = targets.begin(); itr != targets.end(); ++itr) { - targetInfo.missCondition = m_originalCaster->SpellHitResult(target, m_spellInfo, m_canReflect); - if (m_skipCheck && targetInfo.missCondition != SPELL_MISS_IMMUNE) - targetInfo.missCondition = SPELL_MISS_NONE; + if (Unit* unitTarget = (*itr)->ToUnit()) + unitTargets.push_back(unitTarget); + else if (GameObject* gObjTarget = (*itr)->ToGameObject()) + gObjTargets.push_back(gObjTarget); } - else - targetInfo.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE; - // Spell have speed - need calculate incoming time - // Incoming time is zero for self casts. At least I think so. - if (m_spellInfo->Speed > 0.0f && m_caster != target) + if (!unitTargets.empty()) { - // calculate spell incoming interval - // TODO: this is a hack - float dist = m_caster->GetDistance(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()); + // Special target selection for smart heals and energizes + uint32 maxSize = 0; + int32 power = -1; + switch (m_spellInfo->SpellFamilyName) + { + case SPELLFAMILY_GENERIC: + switch (m_spellInfo->Id) + { + case 52759: // Ancestral Awakening + case 71610: // Echoes of Light (Althor's Abacus normal version) + case 71641: // Echoes of Light (Althor's Abacus heroic version) + maxSize = 1; + power = POWER_HEALTH; + break; + case 54968: // Glyph of Holy Light + maxSize = m_spellInfo->MaxAffectedTargets; + power = POWER_HEALTH; + break; + case 57669: // Replenishment + // In arenas Replenishment may only affect the caster + if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->InArena()) + { + unitTargets.clear(); + unitTargets.push_back(m_caster); + break; + } + maxSize = 10; + power = POWER_MANA; + break; + default: + break; + } + break; + case SPELLFAMILY_PRIEST: + if (m_spellInfo->SpellFamilyFlags[0] == 0x10000000) // Circle of Healing + { + maxSize = m_caster->HasAura(55675) ? 6 : 5; // Glyph of Circle of Healing + power = POWER_HEALTH; + } + else if (m_spellInfo->Id == 64844) // Divine Hymn + { + maxSize = 3; + power = POWER_HEALTH; + } + else if (m_spellInfo->Id == 64904) // Hymn of Hope + { + maxSize = 3; + power = POWER_MANA; + } + else + break; - if (dist < 5.0f) - dist = 5.0f; - targetInfo.timeDelay = (uint64) floor(dist / m_spellInfo->Speed * 1000.0f); + // Remove targets outside caster's raid + for (std::list::iterator itr = unitTargets.begin() ; itr != unitTargets.end();) + { + if (!(*itr)->IsInRaidWith(m_caster)) + itr = unitTargets.erase(itr); + else + ++itr; + } + break; + case SPELLFAMILY_DRUID: + if (m_spellInfo->SpellFamilyFlags[1] == 0x04000000) // Wild Growth + { + maxSize = m_caster->HasAura(62970) ? 6 : 5; // Glyph of Wild Growth + power = POWER_HEALTH; + } + else if (m_spellInfo->SpellFamilyFlags[2] == 0x0100) // Starfall + { + // Remove targets not in LoS or in stealth + for (std::list::iterator itr = unitTargets.begin() ; itr != unitTargets.end();) + { + if ((*itr)->HasStealthAura() || (*itr)->HasInvisibilityAura() || !(*itr)->IsWithinLOSInMap(m_caster)) + itr = unitTargets.erase(itr); + else + ++itr; + } + break; + } + else + break; - // Calculate minimum incoming time - if (m_delayMoment == 0 || m_delayMoment > targetInfo.timeDelay) - m_delayMoment = targetInfo.timeDelay; - } - else - targetInfo.timeDelay = 0LL; + // Remove targets outside caster's raid + for (std::list::iterator itr = unitTargets.begin() ; itr != unitTargets.end();) + if (!(*itr)->IsInRaidWith(m_caster)) + itr = unitTargets.erase(itr); + else + ++itr; + break; + default: + break; + } - // If target reflect spell back to caster - if (targetInfo.missCondition == SPELL_MISS_REFLECT) - { - // Calculate reflected spell result on caster - targetInfo.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect); + if (maxSize && power != -1) + { + if (Powers(power) == POWER_HEALTH) + { + if (unitTargets.size() > maxSize) + { + unitTargets.sort(Trinity::HealthPctOrderPred()); + unitTargets.resize(maxSize); + } + } + else + { + for (std::list::iterator itr = unitTargets.begin() ; itr != unitTargets.end();) + if ((*itr)->getPowerType() != (Powers)power) + itr = unitTargets.erase(itr); + else + ++itr; - if (targetInfo.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell - targetInfo.reflectResult = SPELL_MISS_PARRY; + if (unitTargets.size() > maxSize) + { + unitTargets.sort(Trinity::PowerPctOrderPred((Powers)power)); + unitTargets.resize(maxSize); + } + } + } - // Increase time interval for reflected spells by 1.5 - targetInfo.timeDelay += targetInfo.timeDelay >> 1; + // Other special target selection goes here + if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) + { + Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); + for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) + if ((*j)->IsAffectedOnSpell(m_spellInfo)) + maxTargets += (*j)->GetAmount(); + + if (m_spellInfo->Id == 5246) //Intimidating Shout + unitTargets.remove(m_targets.GetUnitTarget()); + Trinity::RandomResizeList(unitTargets, maxTargets); + } + + CallScriptAfterUnitTargetSelectHandlers(unitTargets, effIndex); + + for (std::list::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr) + AddUnitTarget(*itr, effMask, false); } - else - targetInfo.reflectResult = SPELL_MISS_NONE; - // Add target to list - m_UniqueTargetInfo.push_back(targetInfo); + if (!gObjTargets.empty()) + { + if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) + { + Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); + for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) + if ((*j)->IsAffectedOnSpell(m_spellInfo)) + maxTargets += (*j)->GetAmount(); + + Trinity::RandomResizeList(gObjTargets, maxTargets); + } + for (std::list::iterator itr = gObjTargets.begin(); itr != gObjTargets.end(); ++itr) + AddGOTarget(*itr, effMask); + } } -void Spell::AddGOTarget(GameObject* go, uint32 effectMask) +void Spell::SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { - for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) + switch(targetType.GetType()) { - if (!m_spellInfo->Effects[effIndex].IsEffect()) - effectMask &= ~(1 << effIndex); - else - { - switch (m_spellInfo->Effects[effIndex].Effect) + case TARGET_DEST_CASTER: + m_targets.SetDst(*m_caster); + return; + case TARGET_DEST_HOME: + if (Player* playerCaster = m_caster->ToPlayer()) + m_targets.SetDst(playerCaster->m_homebindX, playerCaster->m_homebindY, playerCaster->m_homebindZ, playerCaster->GetOrientation(), playerCaster->m_homebindMapId); + return; + case TARGET_DEST_DB: + if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id)) { - case SPELL_EFFECT_GAMEOBJECT_DAMAGE: - case SPELL_EFFECT_GAMEOBJECT_REPAIR: - case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE: - if (go->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) - effectMask &= ~(1 << effIndex); - break; - default: - break; + // TODO: fix this check + if (m_spellInfo->HasEffect(SPELL_EFFECT_TELEPORT_UNITS)) + m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId); + else if (st->target_mapId == m_caster->GetMapId()) + m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation); + } + else + { + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id); + WorldObject* target = m_targets.GetObjectTarget(); + m_targets.SetDst(target ? *target : *m_caster); } + return; + case TARGET_DEST_CASTER_FISHING: + { + float min_dis = m_spellInfo->GetMinRange(true); + float max_dis = m_spellInfo->GetMaxRange(true); + float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; + float x, y, z, angle; + angle = (float)rand_norm() * static_cast(M_PI * 35.0f / 180.0f) - static_cast(M_PI * 17.5f / 180.0f); + m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, angle); + m_targets.SetDst(x, y, z, m_caster->GetOrientation()); + return; } } - if (!effectMask) - return; + float dist; + float angle = targetType.CalcDirectionAngle(); + float objSize = m_caster->GetObjectSize(); + if (targetType.GetType() == TARGET_DEST_CASTER_SUMMON) + dist = PET_FOLLOW_DIST; + else + dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); - uint64 targetGUID = go->GetGUID(); + if (dist < objSize) + dist = objSize; + else if (targetType.GetType() == TARGET_DEST_CASTER_RANDOM) + dist = objSize + (dist - objSize) * (float)rand_norm(); - // Lookup target in already in list - for (std::list::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) + Position pos; + if (targetType.GetType() == TARGET_DEST_CASTER_FRONT_LEAP) + m_caster->GetFirstCollisionPosition(pos, dist, angle); + else + m_caster->GetNearPosition(pos, dist, angle); + m_targets.SetDst(*m_caster); + m_targets.ModDst(pos); +} + +void Spell::SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) +{ + WorldObject* target = m_targets.GetObjectTarget(); + switch(targetType.GetTarget()) { - if (targetGUID == ihit->targetGUID) // Found in list - { - ihit->effectMask |= effectMask; // Add only effect mask + case TARGET_DEST_TARGET_ENEMY: + case TARGET_DEST_TARGET_ANY: + m_targets.SetDst(*target); return; - } } - // This is new target calculate data for him + float angle = targetType.CalcDirectionAngle(); + float objSize = target->GetObjectSize(); + float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); + if (dist < objSize) + dist = objSize; + else if (targetType.GetType() == TARGET_DEST_TARGET_RANDOM) + dist = objSize + (dist - objSize) * (float)rand_norm(); - GOTargetInfo target; - target.targetGUID = targetGUID; - target.effectMask = effectMask; - target.processed = false; // Effects not apply on target + Position pos; + target->GetNearPosition(pos, dist, angle); + m_targets.SetDst(*target); + m_targets.ModDst(pos); +} - // Spell have speed - need calculate incoming time - if (m_spellInfo->Speed > 0.0f) +void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) +{ + switch(targetType.GetTarget()) { - // calculate spell incoming interval - float dist = m_caster->GetDistance(go->GetPositionX(), go->GetPositionY(), go->GetPositionZ()); - if (dist < 5.0f) - dist = 5.0f; - target.timeDelay = uint64(floor(dist / m_spellInfo->Speed * 1000.0f)); - if (m_delayMoment == 0 || m_delayMoment > target.timeDelay) - m_delayMoment = target.timeDelay; + case TARGET_DEST_DYNOBJ_ENEMY: + case TARGET_DEST_DYNOBJ_ALLY: + case TARGET_DEST_DYNOBJ_NONE: + case TARGET_DEST_DEST: + return; + case TARGET_DEST_TRAJ: + SelectImplicitTrajTargets(); + return; } - else - target.timeDelay = 0LL; - // Add target to list - m_UniqueGOTargetInfo.push_back(target); + float angle = targetType.CalcDirectionAngle(); + float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); + if (targetType.GetTarget() == TARGET_DEST_DEST_RANDOM) + dist *= (float)rand_norm(); + + Position pos = *m_targets.GetDst(); + m_caster->MovePosition(pos, dist, angle); + m_targets.ModDst(pos); } -void Spell::AddGOTarget(uint64 goGUID, uint32 effectMask) +void Spell::SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { - if (GameObject* go = m_caster->GetMap()->GetGameObject(goGUID)) - AddGOTarget(go, effectMask); + switch(targetType.GetTarget()) + { + case TARGET_UNIT_CASTER: + AddUnitTarget(m_caster, 1 << effIndex, false); + break; + case TARGET_UNIT_MASTER: + if (Unit* owner = m_caster->GetCharmerOrOwner()) + AddUnitTarget(owner, 1 << effIndex); + break; + case TARGET_UNIT_PET: + if (Guardian* pet = m_caster->GetGuardianPet()) + AddUnitTarget(pet, 1 << effIndex); + break; + case TARGET_UNIT_SUMMONER: + if (m_caster->isSummon()) + if (Unit* unit = m_caster->ToTempSummon()->GetSummoner()) + AddUnitTarget(unit, 1 << effIndex); + break; + case TARGET_UNIT_VEHICLE: + if (Unit *vehicle = m_caster->GetVehicleBase()) + AddUnitTarget(vehicle, 1 << effIndex); + break; + case TARGET_UNIT_PASSENGER_0: + case TARGET_UNIT_PASSENGER_1: + case TARGET_UNIT_PASSENGER_2: + case TARGET_UNIT_PASSENGER_3: + case TARGET_UNIT_PASSENGER_4: + case TARGET_UNIT_PASSENGER_5: + case TARGET_UNIT_PASSENGER_6: + case TARGET_UNIT_PASSENGER_7: + if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsVehicle()) + if (Unit *unit = m_caster->GetVehicleKit()->GetPassenger(targetType.GetTarget() - TARGET_UNIT_PASSENGER_0)) + AddUnitTarget(unit, 1 << effIndex); + break; + } } -void Spell::AddItemTarget(Item* item, uint32 effectMask) +void Spell::SelectImplicitTargetObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { - for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) - if (!m_spellInfo->Effects[effIndex].IsEffect()) - effectMask &= ~(1 << effIndex); + ASSERT(m_targets.GetObjectTarget() && "Spell::SelectImplicitTargetObjectTargets - no explicit object target available!"); + if (Unit* unit = m_targets.GetUnitTarget()) + AddUnitTarget(unit, 1 << effIndex); + else if (GameObject* gobj = m_targets.GetGOTarget()) + AddGOTarget(gobj, 1 << effIndex); + else + AddItemTarget(m_targets.GetItemTarget(), effIndex); - // no effects left - if (!effectMask) - return; + if (WorldObject* target = m_targets.GetObjectTarget()) + SelectImplicitChainTargets(effIndex, targetType, target, 1 << effIndex); +} - // Lookup target in already in list - for (std::list::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) +void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, WorldObject* target, uint32 effMask) +{ + uint32 maxTargets = m_spellInfo->Effects[effIndex].ChainTarget; + if (Player* modOwner = m_caster->GetSpellModOwner()) + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this); + + if (maxTargets > 1) { - if (item == ihit->item) // Found in list - { - ihit->effectMask |= effectMask; // Add only effect mask - return; - } - } + // mark damage multipliers as used + for (uint32 k = effIndex; k < MAX_SPELL_EFFECTS; ++k) + if (effMask & (1 << k)) + m_damageMultipliers[k] = 1.0f; + m_applyMultiplierMask |= effMask; - // This is new target add data + std::list targets; + SearchChainTargets(targets, maxTargets - 1, target, targetType.GetObjectType(), targetType.GetCheckType() + , m_spellInfo->Effects[effIndex].ImplicitTargetConditions, targetType.GetType() == TARGET_UNIT_TARGET_CHAINHEAL_ALLY); - ItemTargetInfo target; - target.item = item; - target.effectMask = effectMask; + // for backward compability + std::list unitTargets; + for (std::list::iterator itr = targets.begin(); itr != targets.end(); ++itr) + if (Unit* unitTarget = (*itr)->ToUnit()) + unitTargets.push_back(unitTarget); - m_UniqueItemInfo.push_back(target); + CallScriptAfterUnitTargetSelectHandlers(unitTargets, effIndex); + + for (std::list::iterator itr = unitTargets.begin(); itr != unitTargets.end(); ++itr) + AddUnitTarget(*itr, effMask, false); + } } -void Spell::DoAllEffectOnTarget(TargetInfo* target) +float tangent(float x) { - if (!target || target->processed) - return; - - target->processed = true; // Target checked in apply effects procedure - - // Get mask of effects for target - uint8 mask = target->effectMask; - - Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID); - if (!unit) - { - uint8 farMask = 0; - // create far target mask - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - if (m_spellInfo->Effects[i].IsFarUnitTargetEffect()) - if ((1 << i) & mask) - farMask |= (1 << i); + x = tan(x); + //if (x < std::numeric_limits::max() && x > -std::numeric_limits::max()) return x; + //if (x >= std::numeric_limits::max()) return std::numeric_limits::max(); + //if (x <= -std::numeric_limits::max()) return -std::numeric_limits::max(); + if (x < 100000.0f && x > -100000.0f) return x; + if (x >= 100000.0f) return 100000.0f; + if (x <= 100000.0f) return -100000.0f; + return 0.0f; +} - if (!farMask) - return; - // find unit in world - unit = ObjectAccessor::FindUnit(target->targetGUID); - if (!unit) - return; +#define DEBUG_TRAJ(a) //a - // do far effects on the unit - // can't use default call because of threading, do stuff as fast as possible - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - if (farMask & (1 << i)) - HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_HIT_TARGET); +void Spell::SelectImplicitTrajTargets() +{ + if (!m_targets.HasTraj()) return; - } - if (unit->isAlive() != target->alive) + float dist2d = m_targets.GetDist2d(); + if (!dist2d) return; - if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsPositive() && (getMSTime() - target->timeDelay) <= unit->m_lastSanctuaryTime) - return; // No missinfo in that case - - // Get original caster (if exist) and calculate damage/healing from him data - Unit* caster = m_originalCaster ? m_originalCaster : m_caster; + float srcToDestDelta = m_targets.GetDst()->m_positionZ - m_targets.GetSrc()->m_positionZ; - // Skip if m_originalCaster not avaiable - if (!caster) + std::list targets; + Trinity::WorldObjectSpellTrajTargetCheck check(dist2d, m_targets.GetSrc(), m_caster, m_spellInfo); + Trinity::WorldObjectListSearcher searcher(m_caster, targets, check, GRID_MAP_TYPE_MASK_ALL); + SearchTargets > (searcher, GRID_MAP_TYPE_MASK_ALL, m_caster, m_targets.GetSrc(), dist2d); + if (targets.empty()) return; - SpellMissInfo missInfo = target->missCondition; - - // Need init unitTarget by default unit (can changed in code on reflect) - // Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem) - unitTarget = unit; - - // Reset damage/healing counter - m_damage = target->damage; - m_healing = -target->damage; - - // Fill base trigger info - uint32 procAttacker = m_procAttacker; - uint32 procVictim = m_procVictim; - uint32 procEx = m_procEx; + targets.sort(Trinity::ObjectDistanceOrderPred(m_caster)); - m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied + float b = tangent(m_targets.GetElevation()); + float a = (srcToDestDelta - dist2d * b) / (dist2d * dist2d); + if (a > -0.0001f) + a = 0; + DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: a %f b %f", a, b);) - //Spells with this flag cannot trigger if effect is casted on self - bool canEffectTrigger = !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && CanExecuteTriggersOnHit(mask); - Unit* spellHitTarget = NULL; + float bestDist = m_spellInfo->GetMaxRange(false); - if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target - spellHitTarget = unit; - else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit) + std::list::const_iterator itr = targets.begin(); + for (; itr != targets.end(); ++itr) { - if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him - { - spellHitTarget = m_caster; - if (m_caster->GetTypeId() == TYPEID_UNIT) - m_caster->ToCreature()->LowerPlayerDamageReq(target->damage); - } - } + if (Unit* unitTarget = (*itr)->ToUnit()) + if (m_caster == *itr || m_caster->IsOnVehicle(unitTarget) || (unitTarget)->GetVehicle())//(*itr)->IsOnVehicle(m_caster)) + continue; - if (spellHitTarget) - { - SpellMissInfo missInfo2 = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura); - if (missInfo2 != SPELL_MISS_NONE) - { - if (missInfo2 != SPELL_MISS_MISS) - m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo2); - m_damage = 0; - spellHitTarget = NULL; - } - } + const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3) + // TODO: all calculation should be based on src instead of m_caster + const float objDist2d = m_targets.GetSrc()->GetExactDist2d(*itr) * cos(m_targets.GetSrc()->GetRelativeAngle(*itr)); + const float dz = (*itr)->GetPositionZ() - m_targets.GetSrc()->m_positionZ; - // Do not take combo points on dodge and miss - if (missInfo != SPELL_MISS_NONE && m_needComboPoints && - m_targets.GetUnitTargetGUID() == target->targetGUID) - { - m_needComboPoints = false; - // Restore spell mods for a miss/dodge/parry Cold Blood - // TODO: check how broad this rule should be - if (m_caster->GetTypeId() == TYPEID_PLAYER && (missInfo == SPELL_MISS_MISS || - missInfo == SPELL_MISS_DODGE || missInfo == SPELL_MISS_PARRY)) - m_caster->ToPlayer()->RestoreSpellMods(this, 14177); - } + DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);) - // Trigger info was not filled in spell::preparedatafortriggersystem - we do it now - if (canEffectTrigger && !procAttacker && !procVictim) - { - bool positive = true; - if (m_damage > 0) - positive = false; - else if (!m_healing) - { - for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) - // If at least one effect negative spell is negative hit - if (mask & (1<IsPositiveEffect(i)) - { - positive = false; - break; - } - } - switch (m_spellInfo->DmgClass) + float dist = objDist2d - size; + float height = dist * (a * dist + b); + DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);) + if (dist < bestDist && height < dz + size && height > dz - size) { - case SPELL_DAMAGE_CLASS_MAGIC: - if (positive) - { - procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS; - procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS; - } - else - { - procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; - procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG; - } - break; - case SPELL_DAMAGE_CLASS_NONE: - if (positive) - { - procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS; - procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS; - } - else - { - procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; - procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG; - } + bestDist = dist > 0 ? dist : 0; break; } - } - CallScriptOnHitHandlers(); - // All calculated do it! - // Do healing and triggers - if (m_healing > 0) - { - bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask); - uint32 addhealth = m_healing; - if (crit) - { - procEx |= PROC_EX_CRITICAL_HIT; - addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL); +#define CHECK_DIST {\ + DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\ + if (dist > bestDist)\ + continue;\ + if (dist < objDist2d + size && dist > objDist2d - size)\ + {\ + bestDist = dist;\ + break;\ + }\ } - else - procEx |= PROC_EX_NORMAL_HIT; - - // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) - if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) - caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell); - int32 gain = caster->HealBySpell(unitTarget, m_spellInfo, addhealth, crit); - unitTarget->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo); - m_healing = gain; - } - // Do damage and triggers - else if (m_damage > 0) - { - // Fill base damage struct (unitTarget - is real spell target) - SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); - - // Add bonuses and fill damageInfo struct - caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit); - caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); + if (!a) + { + height = dz - size; + dist = height / b; + CHECK_DIST; - // Send log damage message to client - caster->SendSpellNonMeleeDamageLog(&damageInfo); + height = dz + size; + dist = height / b; + CHECK_DIST; - procEx |= createProcExtendMask(&damageInfo, missInfo); - procVictim |= PROC_FLAG_TAKEN_DAMAGE; + continue; + } - // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) - if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) + height = dz - size; + float sqrt1 = b * b + 4 * a * height; + if (sqrt1 > 0) { - caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell); - if (caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 && - (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) - caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx); + sqrt1 = sqrt(sqrt1); + dist = (sqrt1 - b) / (2 * a); + CHECK_DIST; } - caster->DealSpellDamage(&damageInfo, true); - - // Haunt - if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[1] & 0x40000 && m_spellAura && m_spellAura->GetEffect(1)) + height = dz + size; + float sqrt2 = b * b + 4 * a * height; + if (sqrt2 > 0) { - AuraEffect* aurEff = m_spellAura->GetEffect(1); - aurEff->SetAmount(CalculatePctU(aurEff->GetAmount(), damageInfo.damage)); + sqrt2 = sqrt(sqrt2); + dist = (sqrt2 - b) / (2 * a); + CHECK_DIST; + + dist = (-sqrt2 - b) / (2 * a); + CHECK_DIST; } - m_damage = damageInfo.damage; - } - // Passive spell hits/misses or active spells only misses (only triggers) - else - { - // Fill base damage struct (unitTarget - is real spell target) - SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); - procEx |= createProcExtendMask(&damageInfo, missInfo); - // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) - if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) - caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell); - // Failed Pickpocket, reveal rogue - if (missInfo == SPELL_MISS_RESIST && m_spellInfo->AttributesCu & SPELL_ATTR0_CU_PICKPOCKET && unitTarget->GetTypeId() == TYPEID_UNIT) + if (sqrt1 > 0) { - m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); - if (unitTarget->ToCreature()->IsAIEnabled) - unitTarget->ToCreature()->AI()->AttackStart(m_caster); + dist = (-sqrt1 - b) / (2 * a); + CHECK_DIST; } } - if (missInfo != SPELL_MISS_EVADE && m_caster && !m_caster->IsFriendlyTo(unit) && !m_spellInfo->IsPositive()) + if (m_targets.GetSrc()->GetExactDist2d(m_targets.GetDst()) > bestDist) { - m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)); + float x = m_targets.GetSrc()->m_positionX + cos(m_caster->GetOrientation()) * bestDist; + float y = m_targets.GetSrc()->m_positionY + sin(m_caster->GetOrientation()) * bestDist; + float z = m_targets.GetSrc()->m_positionZ + bestDist * (a * bestDist + b); - if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) - if (!unit->IsStandState()) - unit->SetStandState(UNIT_STAND_STATE_STAND); - } - - if (spellHitTarget) - { - //AI functions - if (spellHitTarget->GetTypeId() == TYPEID_UNIT) + if (itr != targets.end()) { - if (spellHitTarget->ToCreature()->IsAIEnabled) - spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo); + float distSq = (*itr)->GetExactDistSq(x, y, z); + float sizeSq = (*itr)->GetObjectSize(); + sizeSq *= sizeSq; + DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) + if (distSq > sizeSq) + { + float factor = 1 - sqrt(sizeSq / distSq); + x += factor * ((*itr)->GetPositionX() - x); + y += factor * ((*itr)->GetPositionY() - y); + z += factor * ((*itr)->GetPositionZ() - z); - // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) - // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm...) - if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !spellHitTarget->ToCreature()->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) - if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) - p->CastedCreatureOrGO(spellHitTarget->GetEntry(), spellHitTarget->GetGUID(), m_spellInfo->Id); + distSq = (*itr)->GetExactDistSq(x, y, z); + DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) + } } - if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled) - m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo); - - // Needs to be called after dealing damage/healing to not remove breaking on damage auras - DoTriggersOnSpellHit(spellHitTarget, mask); - - // if target is fallged for pvp also flag caster if a player - if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER) - m_caster->ToPlayer()->UpdatePvP(true); - - CallScriptAfterHitHandlers(); + Position trajDst; + trajDst.Relocate(x, y, z, m_caster->GetOrientation()); + m_targets.ModDst(trajDst); } } -SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleAura) +void Spell::SelectEffectTypeImplicitTargets(uint8 effIndex) { - if (!unit || !effectMask) - return SPELL_MISS_EVADE; + // special case for SPELL_EFFECT_SUMMON_RAF_FRIEND and SPELL_EFFECT_SUMMON_PLAYER + // TODO: this is a workaround - target shouldn't be stored in target map for those spells + switch (m_spellInfo->Effects[effIndex].Effect) + { + case SPELL_EFFECT_SUMMON_RAF_FRIEND: + case SPELL_EFFECT_SUMMON_PLAYER: + if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->GetSelection()) + { + Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetSelection()); + if (target) + AddUnitTarget(target, 1 << effIndex, false); + } + return; + default: + break; + } - // For delayed spells immunity may be applied between missile launch and hit - check immunity for that case - // disable effects to which unit is immune - for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) - if (effectMask & (1 << effectNumber) && unit->IsImmunedToSpellEffect(m_spellInfo, effectNumber)) - effectMask &= ~(1 << effectNumber); - if (!effectMask || (m_spellInfo->Speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo)))) - return SPELL_MISS_IMMUNE; + // select spell implicit targets based on effect type + if (!m_spellInfo->Effects[effIndex].GetImplicitTargetType()) + return; - PrepareScriptHitHandlers(); - CallScriptBeforeHitHandlers(); + uint32 targetMask = m_spellInfo->Effects[effIndex].GetMissingTargetMask(); - if (unit->GetTypeId() == TYPEID_PLAYER) + if (!targetMask) + return; + + switch (m_spellInfo->Effects[effIndex].GetImplicitTargetType()) { - unit->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id); - unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, m_caster); - unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id); + // add explicit object target or self to the target map + case EFFECT_IMPLICIT_TARGET_EXPLICIT: + // player which not released his spirit is Unit, but target flag for it is TARGET_FLAG_CORPSE_MASK + if (targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK)) + { + if (Unit* unitTarget = m_targets.GetUnitTarget()) + AddUnitTarget(unitTarget, 1 << effIndex, false); + else if (targetMask & TARGET_FLAG_CORPSE_MASK) + { + if (Corpse* corpseTarget = m_targets.GetCorpseTarget()) + { + // TODO: this is a workaround - corpses should be added to spell target map too, but we can't do that so we add owner instead + if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) + AddUnitTarget(owner, 1 << effIndex, false); + } + } + else //if (targetMask & TARGET_FLAG_UNIT_MASK) + { + AddUnitTarget(m_caster, 1 << effIndex, false); + } + } + if (targetMask & TARGET_FLAG_ITEM_MASK) + { + if (Item* itemTarget = m_targets.GetItemTarget()) + AddItemTarget(itemTarget, 1 << effIndex); + } + if (targetMask & TARGET_FLAG_GAMEOBJECT_MASK) + { + if (GameObject* gObjTarget = m_targets.GetGOTarget()) + AddGOTarget(gObjTarget, 1 << effIndex); + } + break; + // add self to the target map + case EFFECT_IMPLICIT_TARGET_CASTER: + if (targetMask & TARGET_FLAG_UNIT_MASK) + AddUnitTarget(m_caster, 1 << effIndex, false); + break; + default: + break; } +} - if (m_caster->GetTypeId() == TYPEID_PLAYER) +uint32 Spell::GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionList* condList) +{ + // this function selects which containers need to be searched for spell target + uint32 retMask = GRID_MAP_TYPE_MASK_ALL; + + // filter searchers based on searched object type + switch (objType) { - m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id); - m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit); + case TARGET_OBJECT_TYPE_UNIT: + case TARGET_OBJECT_TYPE_UNIT_AND_DEST: + case TARGET_OBJECT_TYPE_CORPSE: + case TARGET_OBJECT_TYPE_CORPSE_ENEMY: + case TARGET_OBJECT_TYPE_CORPSE_ALLY: + retMask &= GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_CREATURE; + break; + case TARGET_OBJECT_TYPE_GOBJ: + case TARGET_OBJECT_TYPE_GOBJ_ITEM: + retMask &= GRID_MAP_TYPE_MASK_GAMEOBJECT; + break; } + if (!(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_DEAD)) + retMask &= ~GRID_MAP_TYPE_MASK_CORPSE; + if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_PLAYERS) + retMask &= GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_PLAYER; + if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_GHOSTS) + retMask &= GRID_MAP_TYPE_MASK_PLAYER; - if (m_caster != unit) + if (condList) + retMask &= sConditionMgr->GetSearcherTypeMaskForConditionList(*condList); + return retMask; +} + +template +void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius) +{ + if (!containerMask) + return; + + // search world and grid for possible targets + bool searchInGrid = containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_GAMEOBJECT); + bool searchInWorld = containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE); + if (searchInGrid || searchInWorld) { - // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells - if (m_spellInfo->Speed > 0.0f && unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID()) - return SPELL_MISS_EVADE; + float x,y; + x = pos->GetPositionX(); + y = pos->GetPositionY(); - if (m_caster->_IsValidAttackTarget(unit, m_spellInfo)) + CellCoord p(Trinity::ComputeCellCoord(x, y)); + Cell cell(p); + cell.SetNoCreate(); + + Map& map = *(referer->GetMap()); + + if (searchInWorld) { - unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL); - //TODO: This is a hack. But we do not know what types of stealth should be interrupted by CC - if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) && unit->IsControlledByPlayer()) - unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); + TypeContainerVisitor world_object_notifier(searcher); + cell.Visit(p, world_object_notifier, map, radius, x, y); } - else if (m_caster->IsFriendlyTo(unit)) + if (searchInGrid) { - // for delayed spells ignore negative spells (after duel end) for friendly targets - // TODO: this cause soul transfer bugged - if (m_spellInfo->Speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->IsPositive()) - return SPELL_MISS_EVADE; - - // assisting case, healing and resurrection - if (unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER)) - { - m_caster->SetContestedPvP(); - if (m_caster->GetTypeId() == TYPEID_PLAYER) - m_caster->ToPlayer()->UpdatePvP(true); - } - if (unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)) - { - m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit); - unit->getHostileRefManager().threatAssist(m_caster, 0.0f); - } + TypeContainerVisitor grid_object_notifier(searcher); + cell.Visit(p, grid_object_notifier, map, radius, x , y); } } +} - // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add - m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo, m_triggeredByAuraSpell); - if (m_diminishGroup) +WorldObject* Spell::SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList) +{ + WorldObject* target = NULL; + uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); + if (!containerTypeMask) + return NULL; + Trinity::WorldObjectSpellNearbyTargetCheck check(range, m_caster, m_spellInfo, selectionType, condList); + Trinity::WorldObjectLastSearcher searcher(m_caster, target, check, containerTypeMask); + SearchTargets > (searcher, containerTypeMask, m_caster, m_caster, range); + return target; +} + +void Spell::SearchAreaTargets(std::list& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList) +{ + uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); + if (!containerTypeMask) + return; + Trinity::WorldObjectSpellAreaTargetCheck check(range, position, m_caster, referer, m_spellInfo, selectionType, condList); + Trinity::WorldObjectListSearcher searcher(m_caster, targets, check, containerTypeMask); + SearchTargets > (searcher, containerTypeMask, m_caster, m_caster, range); +} + +void Spell::SearchChainTargets(std::list& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, ConditionList* condList, bool isChainHeal) +{ + // max dist for jump target selection + float jumpRadius = 0.0f; + switch (m_spellInfo->DmgClass) { - m_diminishLevel = unit->GetDiminishing(m_diminishGroup); - DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup); - // Increase Diminishing on unit, current informations for actually casts will use values above - if ((type == DRTYPE_PLAYER && unit->GetCharmerOrOwnerPlayerOrPlayerItself()) || type == DRTYPE_ALL) - unit->IncrDiminishing(m_diminishGroup); + case SPELL_DAMAGE_CLASS_RANGED: + // 7.5y for multi shot + jumpRadius = 7.5f; + break; + case SPELL_DAMAGE_CLASS_MELEE: + // 5y for swipe, cleave and similar + jumpRadius = 5.0f; + break; + case SPELL_DAMAGE_CLASS_NONE: + case SPELL_DAMAGE_CLASS_MAGIC: + // 12.5y for chain heal spell since 3.2 patch + if (isChainHeal) + jumpRadius = 12.5f; + // 10y as default for magic chain spells + else + jumpRadius = 10.0f; + break; } - uint8 aura_effmask = 0; - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - if (effectMask & (1 << i) && m_spellInfo->Effects[i].IsUnitOwnedAuraEffect()) - aura_effmask |= 1 << i; + // chain lightning/heal spells and similar - allow to jump at larger distance and go out of los + bool isBouncingFar = (m_spellInfo->AttributesEx4 & SPELL_ATTR4_AREA_TARGET_CHAIN + || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE + || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC); - if (aura_effmask) + // max dist which spell can reach + float searchRadius = jumpRadius; + if (isBouncingFar) + searchRadius *= chainTargets; + + std::list tempTargets; + SearchAreaTargets(tempTargets, searchRadius, target, m_caster, objectType, selectType, condList); + tempTargets.remove(target); + + // remove targets which are always invalid for chain spells + // for some spells allow only chain targets in front of caster (swipe for example) + if (!isBouncingFar) { - // Select rank for aura with level requirements only in specific cases - // Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target - SpellInfo const* aurSpellInfo = m_spellInfo; - int32 basePoints[3]; - if (scaleAura) + for (std::list::iterator itr = tempTargets.begin(); itr != tempTargets.end();) { - aurSpellInfo = m_spellInfo->GetAuraRankForLevel(unitTarget->getLevel()); - ASSERT(aurSpellInfo); - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + std::list::iterator checkItr = itr++; + if (!m_caster->HasInArc(static_cast(M_PI), *checkItr)) + tempTargets.erase(checkItr); + } + } + + while (chainTargets) + { + // try to get unit for next chain jump + std::list::iterator foundItr = tempTargets.end(); + // get unit with highest hp deficit in dist + if (isChainHeal) + { + uint32 maxHPDeficit = 0; + for (std::list::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr) { - basePoints[i] = aurSpellInfo->Effects[i].BasePoints; - if (m_spellInfo->Effects[i].Effect != aurSpellInfo->Effects[i].Effect) + if (Unit* unitTarget = (*itr)->ToUnit()) { - aurSpellInfo = m_spellInfo; - break; + uint32 deficit = unitTarget->GetMaxHealth() - unitTarget->GetHealth(); + if ((deficit > maxHPDeficit || foundItr == tempTargets.end()) && target->IsWithinDist(unitTarget, jumpRadius) && target->IsWithinLOSInMap(unitTarget)) + { + foundItr = itr; + maxHPDeficit = deficit; + } } } } - - if (m_originalCaster) + // get closest object + else { - bool refresh = false; - m_spellAura = Aura::TryRefreshStackOrCreate(aurSpellInfo, effectMask, unit, - m_originalCaster, (aurSpellInfo == m_spellInfo)? &m_spellValue->EffectBasePoints[0] : &basePoints[0], m_CastItem, 0, &refresh); - if (m_spellAura) + for (std::list::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr) { - // Set aura stack amount to desired value - if (m_spellValue->AuraStackAmount > 1) + if (foundItr == tempTargets.end()) { - if (!refresh) - m_spellAura->SetStackAmount(m_spellValue->AuraStackAmount); - else - m_spellAura->ModStackAmount(m_spellValue->AuraStackAmount); + if ((!isBouncingFar || target->IsWithinDist(*itr, jumpRadius)) && target->IsWithinLOSInMap(*itr)) + foundItr = itr; } + else if (target->GetDistanceOrder(*itr, *foundItr) && target->IsWithinLOSInMap(*itr)) + foundItr = itr; + } + } + // not found any valid target - chain ends + if (foundItr == tempTargets.end()) + break; + target = *foundItr; + tempTargets.erase(foundItr); + targets.push_back(target); + --chainTargets; + } +} - // Now Reduce spell duration using data received at spell hit - int32 duration = m_spellAura->GetMaxDuration(); - int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup, aurSpellInfo); - float diminishMod = unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel, limitduration); +void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/) +{ + //========================================================================================== + // Now fill data for trigger system, need know: + // can spell trigger another or not (m_canTrigger) + // Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_procEx) + //========================================================================================== - // unit is immune to aura if it was diminished to 0 duration - if (diminishMod == 0.0f) - { - m_spellAura->Remove(); - bool found = false; - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - if (effectMask & (1 << i) && m_spellInfo->Effects[i].Effect != SPELL_EFFECT_APPLY_AURA) - found = true; - if (!found) - return SPELL_MISS_IMMUNE; - } - else - { - ((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup); + m_procVictim = m_procAttacker = 0; + // Get data for type of attack and fill base info for trigger + switch (m_spellInfo->DmgClass) + { + case SPELL_DAMAGE_CLASS_MELEE: + m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS; + if (m_attackType == OFF_ATTACK) + m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK; + else + m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK; + m_procVictim = PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS; + break; + case SPELL_DAMAGE_CLASS_RANGED: + // Auto attack + if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) + { + m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; + m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; + } + else // Ranged spell attack + { + m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS; + m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS; + } + break; + default: + if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && + m_spellInfo->EquippedItemSubClassMask & (1<AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) // Wands auto attack + { + m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; + m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; + } + // For other spells trigger procflags are set in Spell::DoAllEffectOnTarget + // Because spell positivity is dependant on target + } + m_procEx = PROC_EX_NONE; - bool positive = m_spellAura->GetSpellInfo()->IsPositive(); - if (AuraApplication* aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID())) - positive = aurApp->IsPositive(); + // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection + if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && + (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow + m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc + m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap - duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive, effectMask); + m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION; - // Haste modifies duration of channeled spells - if (m_spellInfo->IsChanneled()) - { - if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) - m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this); - } - // and duration of auras affected by SPELL_AURA_PERIODIC_HASTE - else if (m_originalCaster->HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, aurSpellInfo) || m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) - duration = int32(duration * m_originalCaster->GetFloatValue(UNIT_MOD_CAST_SPEED)); + /* Effects which are result of aura proc from triggered spell cannot proc + to prevent chain proc of these spells */ - if (duration != m_spellAura->GetMaxDuration()) - { - m_spellAura->SetMaxDuration(duration); - m_spellAura->SetDuration(duration); - } - m_spellAura->_RegisterForTargets(); - } - } - } + // Hellfire Effect - trigger as DOT + if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040) + { + m_procAttacker = PROC_FLAG_DONE_PERIODIC; + m_procVictim = PROC_FLAG_TAKEN_PERIODIC; } - for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) - if (effectMask & (1 << effectNumber)) - HandleEffects(unit, NULL, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + // Ranged autorepeat attack is set as triggered spell - ignore it + if (!(m_procAttacker & PROC_FLAG_DONE_RANGED_AUTO_ATTACK)) + { + if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS && + (m_spellInfo->AttributesEx2 & SPELL_ATTR2_TRIGGERED_CAN_TRIGGER_PROC || + m_spellInfo->AttributesEx3 & SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_PROC_2)) + m_procEx |= PROC_EX_INTERNAL_CANT_PROC; + else if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) + m_procEx |= PROC_EX_INTERNAL_TRIGGERED; + } + // Totem casts require spellfamilymask defined in spell_proc_event to proc + if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isTotem() && m_caster->IsControlledByPlayer()) + m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY; +} - return SPELL_MISS_NONE; +void Spell::CleanupTargetList() +{ + m_UniqueTargetInfo.clear(); + m_UniqueGOTargetInfo.clear(); + m_UniqueItemInfo.clear(); + m_delayMoment = 0; } -void Spell::DoTriggersOnSpellHit(Unit* unit, uint8 effMask) +void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= true*/) { - // Apply additional spell effects to target - // TODO: move this code to scripts - if (m_preCastSpell) - { - // Paladin immunity shields - if (m_preCastSpell == 61988) - { - // Cast Forbearance - m_caster->CastSpell(unit, 25771, true); - // Cast Avenging Wrath Marker - unit->CastSpell(unit, 61987, true); - } + for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) + if (!m_spellInfo->Effects[effIndex].IsEffect() || !CheckEffectTarget(target, effIndex)) + effectMask &= ~(1 << effIndex); - // Avenging Wrath - if (m_preCastSpell == 61987) - // Cast the serverside immunity shield marker - m_caster->CastSpell(unit, 61988, true); + // no effects left + if (!effectMask) + return; - if (sSpellMgr->GetSpellInfo(m_preCastSpell)) - // Blizz seems to just apply aura without bothering to cast - m_caster->AddAura(m_preCastSpell, unit); - } + if (checkIfValid) + if (m_spellInfo->CheckTarget(m_caster, target, true) != SPELL_CAST_OK) + return; - // handle SPELL_AURA_ADD_TARGET_TRIGGER auras - // this is executed after spell proc spells on target hit - // spells are triggered for each hit spell target - // info confirmed with retail sniffs of permafrost and shadow weaving - if (!m_hitTriggerSpells.empty()) + // Check for effect immune skip if immuned + for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) + if (target->IsImmunedToSpellEffect(m_spellInfo, effIndex)) + effectMask &= ~(1 << effIndex); + + uint64 targetGUID = target->GetGUID(); + + // Lookup target in already in list + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { - int _duration = 0; - for (HitTriggerSpells::const_iterator i = m_hitTriggerSpells.begin(); i != m_hitTriggerSpells.end(); ++i) + if (targetGUID == ihit->targetGUID) // Found in list { - if (CanExecuteTriggersOnHit(effMask, i->first) && roll_chance_i(i->second)) + ihit->effectMask |= effectMask; // Immune effects removed from mask + ihit->scaleAura = false; + if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != target) { - m_caster->CastSpell(unit, i->first, true); - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->first->Id); - - // SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration - // set duration of current aura to the triggered spell - if (i->first->GetDuration() == -1) - { - if (Aura* triggeredAur = unit->GetAura(i->first->Id, m_caster->GetGUID())) - { - // get duration from aura-only once - if (!_duration) - { - Aura* aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID()); - _duration = aur ? aur->GetDuration() : -1; - } - triggeredAur->SetDuration(_duration); - } - } + SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); + if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel) + ihit->scaleAura = true; } + return; } } - // trigger linked auras remove/apply - // TODO: remove/cleanup this, as this table is not documented and people are doing stupid things with it - if (std::vector const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT)) - for (std::vector::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i) - if (*i < 0) - unit->RemoveAurasDueToSpell(-(*i)); - else - unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID()); -} + // This is new target calculate data for him -void Spell::DoAllEffectOnTarget(GOTargetInfo* target) -{ - if (target->processed) // Check target - return; - target->processed = true; // Target checked in apply effects procedure + // Get spell hit result on target + TargetInfo targetInfo; + targetInfo.targetGUID = targetGUID; // Store target GUID + targetInfo.effectMask = effectMask; // Store all effects not immune + targetInfo.processed = false; // Effects not apply on target + targetInfo.alive = target->isAlive(); + targetInfo.damage = 0; + targetInfo.crit = false; + targetInfo.scaleAura = false; + if (m_auraScaleMask && targetInfo.effectMask == m_auraScaleMask && m_caster != target) + { + SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); + if (uint32(target->getLevel() + 10) >= auraSpell->SpellLevel) + targetInfo.scaleAura = true; + } - uint32 effectMask = target->effectMask; - if (!effectMask) - return; + // Calculate hit result + if (m_originalCaster) + { + targetInfo.missCondition = m_originalCaster->SpellHitResult(target, m_spellInfo, m_canReflect); + if (m_skipCheck && targetInfo.missCondition != SPELL_MISS_IMMUNE) + targetInfo.missCondition = SPELL_MISS_NONE; + } + else + targetInfo.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE; - GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID); - if (!go) - return; + // Spell have speed - need calculate incoming time + // Incoming time is zero for self casts. At least I think so. + if (m_spellInfo->Speed > 0.0f && m_caster != target) + { + // calculate spell incoming interval + // TODO: this is a hack + float dist = m_caster->GetDistance(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()); - PrepareScriptHitHandlers(); - CallScriptBeforeHitHandlers(); + if (dist < 5.0f) + dist = 5.0f; + targetInfo.timeDelay = (uint64) floor(dist / m_spellInfo->Speed * 1000.0f); - for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) - if (effectMask & (1 << effectNumber)) - HandleEffects(NULL, NULL, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + // Calculate minimum incoming time + if (m_delayMoment == 0 || m_delayMoment > targetInfo.timeDelay) + m_delayMoment = targetInfo.timeDelay; + } + else + targetInfo.timeDelay = 0LL; - CallScriptOnHitHandlers(); + // If target reflect spell back to caster + if (targetInfo.missCondition == SPELL_MISS_REFLECT) + { + // Calculate reflected spell result on caster + targetInfo.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect); - // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) - // ignore autorepeat/melee casts for speed (not exist quest for spells (hm...) - if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) - if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) - p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id); - CallScriptAfterHitHandlers(); -} + if (targetInfo.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell + targetInfo.reflectResult = SPELL_MISS_PARRY; -void Spell::DoAllEffectOnTarget(ItemTargetInfo* target) -{ - uint32 effectMask = target->effectMask; - if (!target->item || !effectMask) - return; - - PrepareScriptHitHandlers(); - CallScriptBeforeHitHandlers(); - - for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) - if (effectMask & (1 << effectNumber)) - HandleEffects(NULL, target->item, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); - - CallScriptOnHitHandlers(); + // Increase time interval for reflected spells by 1.5 + targetInfo.timeDelay += targetInfo.timeDelay >> 1; + } + else + targetInfo.reflectResult = SPELL_MISS_NONE; - CallScriptAfterHitHandlers(); + // Add target to list + m_UniqueTargetInfo.push_back(targetInfo); } -bool Spell::UpdateChanneledTargetList() +void Spell::AddGOTarget(GameObject* go, uint32 effectMask) { - // Not need check return true - if (m_channelTargetEffectMask == 0) - return true; - - uint8 channelTargetEffectMask = m_channelTargetEffectMask; - uint8 channelAuraMask = 0; - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA) - channelAuraMask |= 1<GetMaxRange(m_spellInfo->IsPositive()); - if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); - } - - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { - if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask)) + if (!m_spellInfo->Effects[effIndex].IsEffect()) + effectMask &= ~(1 << effIndex); + else { - Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); - - if (!unit) - continue; - - if (IsValidDeadOrAliveTarget(unit)) + switch (m_spellInfo->Effects[effIndex].Effect) { - if (channelAuraMask & ihit->effectMask) - { - if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) - { - if (m_caster != unit && !m_caster->IsWithinDistInMap(unit, range)) - { - ihit->effectMask &= ~aurApp->GetEffectMask(); - unit->RemoveAura(aurApp); - continue; - } - } - else // aura is dispelled - continue; - } - - channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target + case SPELL_EFFECT_GAMEOBJECT_DAMAGE: + case SPELL_EFFECT_GAMEOBJECT_REPAIR: + case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE: + if (go->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) + effectMask &= ~(1 << effIndex); + break; + default: + break; } } } - // is all effects from m_needAliveTargetMask have alive targets - return channelTargetEffectMask == 0; -} + if (!effectMask) + return; -// Helper for Chain Healing -// Spell target first -// Raidmates then descending by injury suffered (MaxHealth - Health) -// Other players/mobs then descending by injury suffered (MaxHealth - Health) -struct ChainHealingOrder : public std::binary_function -{ - const Unit* MainTarget; - ChainHealingOrder(Unit const* Target) : MainTarget(Target) {}; - // functor for operator ">" - bool operator()(Unit const* _Left, Unit const* _Right) const - { - return (ChainHealingHash(_Left) < ChainHealingHash(_Right)); - } + uint64 targetGUID = go->GetGUID(); - int32 ChainHealingHash(Unit const* Target) const + // Lookup target in already in list + for (std::list::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) { - if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER && Target->ToPlayer()->IsInSameRaidWith(MainTarget->ToPlayer())) + if (targetGUID == ihit->targetGUID) // Found in list { - if (Target->IsFullHealth()) - return 40000; - else - return 20000 - Target->GetMaxHealth() + Target->GetHealth(); + ihit->effectMask |= effectMask; // Add only effect mask + return; } - else - return 40000 - Target->GetMaxHealth() + Target->GetHealth(); } -}; -void Spell::SearchChainTarget(std::list &TagUnitMap, float max_range, uint32 num, SpellTargets TargetType) -{ - Unit* cur = m_targets.GetUnitTarget(); - if (!cur) - return; + // This is new target calculate data for him - //FIXME: This very like horrible hack and wrong for most spells - if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE) - max_range += num * CHAIN_SPELL_JUMP_RADIUS; + GOTargetInfo target; + target.targetGUID = targetGUID; + target.effectMask = effectMask; + target.processed = false; // Effects not apply on target - std::list tempUnitMap; - if (TargetType == SPELL_TARGETS_CHAINHEAL) + // Spell have speed - need calculate incoming time + if (m_spellInfo->Speed > 0.0f) { - SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, SPELL_TARGETS_ALLY); - tempUnitMap.sort(ChainHealingOrder(m_caster)); + // calculate spell incoming interval + float dist = m_caster->GetDistance(go->GetPositionX(), go->GetPositionY(), go->GetPositionZ()); + if (dist < 5.0f) + dist = 5.0f; + target.timeDelay = uint64(floor(dist / m_spellInfo->Speed * 1000.0f)); + if (m_delayMoment == 0 || m_delayMoment > target.timeDelay) + m_delayMoment = target.timeDelay; } else - SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, TargetType); - tempUnitMap.remove(cur); - - while (num) - { - TagUnitMap.push_back(cur); - --num; - - if (tempUnitMap.empty()) - break; - - std::list::iterator next; - - if (TargetType == SPELL_TARGETS_CHAINHEAL) - { - next = tempUnitMap.begin(); - while (cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS || !cur->IsWithinLOSInMap(*next)) - { - ++next; - if (next == tempUnitMap.end()) - return; - } - } - else - { - tempUnitMap.sort(Trinity::ObjectDistanceOrderPred(cur)); - next = tempUnitMap.begin(); - - if (cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS) // Don't search beyond the max jump radius - break; + target.timeDelay = 0LL; - // Check if (*next) is a valid chain target. If not, don't add to TagUnitMap, and repeat loop. - // If you want to add any conditions to exclude a target from TagUnitMap, add condition in this while () loop. - while ((m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE - && !m_caster->isInFrontInMap(*next, max_range)) - || !m_caster->canSeeOrDetect(*next) - || !cur->IsWithinLOSInMap(*next) - || (*next)->GetCreatureType() == CREATURE_TYPE_CRITTER - || ((GetSpellInfo()->AttributesEx6 & SPELL_ATTR6_CANT_TARGET_CROWD_CONTROLLED) && !(*next)->CanFreeMove())) - { - ++next; - if (next == tempUnitMap.end() || cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS) // Don't search beyond the max jump radius - return; - } - } + // Add target to list + m_UniqueGOTargetInfo.push_back(target); +} - cur = *next; - tempUnitMap.erase(next); - } +void Spell::AddGOTarget(uint64 goGUID, uint32 effectMask) +{ + if (GameObject* go = m_caster->GetMap()->GetGameObject(goGUID)) + AddGOTarget(go, effectMask); } -void Spell::SearchAreaTarget(std::list &TagUnitMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry) +void Spell::AddItemTarget(Item* item, uint32 effectMask) { - if (TargetType == SPELL_TARGETS_GO) + for (uint32 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) + if (!m_spellInfo->Effects[effIndex].IsEffect()) + effectMask &= ~(1 << effIndex); + + // no effects left + if (!effectMask) return; - Position const* pos; - switch (type) + // Lookup target in already in list + for (std::list::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) { - case PUSH_DST_CENTER: - CheckDst(); - pos = m_targets.GetDst(); - break; - case PUSH_SRC_CENTER: - CheckSrc(); - pos = m_targets.GetSrc(); - break; - case PUSH_CHAIN: + if (item == ihit->item) // Found in list { - Unit* target = m_targets.GetUnitTarget(); - if (!target) - { - sLog->outError("SPELL: cannot find unit target for spell ID %u\n", m_spellInfo->Id); - return; - } - pos = target; - break; + ihit->effectMask |= effectMask; // Add only effect mask + return; } - default: - pos = m_caster; - break; } - Trinity::SpellNotifierCreatureAndPlayer notifier(m_caster, TagUnitMap, radius, type, TargetType, pos, entry, m_spellInfo); - if ((m_spellInfo->AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_PLAYERS) || (TargetType == SPELL_TARGETS_ENTRY && !entry)) - m_caster->GetMap()->VisitWorld(pos->m_positionX, pos->m_positionY, radius, notifier); - else - m_caster->GetMap()->VisitAll(pos->m_positionX, pos->m_positionY, radius, notifier); + // This is new target add data + + ItemTargetInfo target; + target.item = item; + target.effectMask = effectMask; + + m_UniqueItemInfo.push_back(target); } -void Spell::SearchGOAreaTarget(std::list &TagGOMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry) +void Spell::DoAllEffectOnTarget(TargetInfo* target) { - if (TargetType != SPELL_TARGETS_GO) + if (!target || target->processed) return; - Position const* pos; - switch (type) - { - case PUSH_DST_CENTER: - CheckDst(); - pos = m_targets.GetDst(); - break; - case PUSH_SRC_CENTER: - CheckSrc(); - pos = m_targets.GetSrc(); - break; - default: - pos = m_caster; - break; - } + target->processed = true; // Target checked in apply effects procedure - Trinity::GameObjectInRangeCheck check(pos->m_positionX, pos->m_positionY, pos->m_positionZ, radius, entry); - Trinity::GameObjectListSearcher searcher(m_caster, TagGOMap, check); - m_caster->GetMap()->VisitGrid(pos->m_positionX, pos->m_positionY, radius, searcher); -} + // Get mask of effects for target + uint8 mask = target->effectMask; -WorldObject* Spell::SearchNearbyTarget(float range, SpellTargets TargetType, SpellEffIndex effIndex) -{ - switch (TargetType) + Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID); + if (!unit) { - case SPELL_TARGETS_ENTRY: - { - ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id); - if (conditions.empty()) - { - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) (caster Entry: %u) does not have record in `conditions` for spell script target (ConditionSourceType 13)", m_spellInfo->Id, m_caster->GetEntry()); - if (m_spellInfo->IsPositive()) - return SearchNearbyTarget(range, SPELL_TARGETS_ALLY, effIndex); - else - return SearchNearbyTarget(range, SPELL_TARGETS_ENEMY, effIndex); - } - - Creature* creatureScriptTarget = NULL; - GameObject* goScriptTarget = NULL; + uint8 farMask = 0; + // create far target mask + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + if (m_spellInfo->Effects[i].IsFarUnitTargetEffect()) + if ((1 << i) & mask) + farMask |= (1 << i); - for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST) - { - if ((*i_spellST)->ConditionType != CONDITION_SPELL_SCRIPT_TARGET) - continue; - if ((*i_spellST)->ConditionValue3 && !((*i_spellST)->ConditionValue3 & (1 << uint32(effIndex)))) - continue; - switch ((*i_spellST)->ConditionValue1) - { - case SPELL_TARGET_TYPE_CONTROLLED: - for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr) - if ((*itr)->GetEntry() == (*i_spellST)->ConditionValue2 && (*itr)->IsWithinDistInMap(m_caster, range)) - { - goScriptTarget = NULL; - creatureScriptTarget = (*itr)->ToCreature(); - range = m_caster->GetDistance(creatureScriptTarget); - } - break; - case SPELL_TARGET_TYPE_GAMEOBJECT: - if ((*i_spellST)->ConditionValue2) - { - if (GameObject* go = m_caster->FindNearestGameObject((*i_spellST)->ConditionValue2, range)) - { - // remember found target and range, next attempt will find more near target with another entry - goScriptTarget = go; - creatureScriptTarget = NULL; - range = m_caster->GetDistance(goScriptTarget); - } - } - else if (focusObject) //Focus Object - { - float frange = m_caster->GetDistance(focusObject); - if (range >= frange) - { - creatureScriptTarget = NULL; - goScriptTarget = focusObject; - range = frange; - } - } - break; - case SPELL_TARGET_TYPE_CREATURE: - if (m_targets.GetUnitTarget() && m_targets.GetUnitTarget()->GetEntry() == (*i_spellST)->ConditionValue2) - return m_targets.GetUnitTarget(); - case SPELL_TARGET_TYPE_DEAD: - default: - if (Creature* cre = m_caster->FindNearestCreature((*i_spellST)->ConditionValue2, range, (*i_spellST)->ConditionValue1 != SPELL_TARGET_TYPE_DEAD)) - { - creatureScriptTarget = cre; - goScriptTarget = NULL; - range = m_caster->GetDistance(creatureScriptTarget); - } - break; - } - } + if (!farMask) + return; + // find unit in world + unit = ObjectAccessor::FindUnit(target->targetGUID); + if (!unit) + return; - if (creatureScriptTarget) - return creatureScriptTarget; - else - return goScriptTarget; - } - default: - case SPELL_TARGETS_ENEMY: - { - Unit* target = NULL; - Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range); - Trinity::UnitLastSearcher searcher(m_caster, target, u_check); - m_caster->VisitNearbyObject(range, searcher); - return target; - } - case SPELL_TARGETS_ALLY: - { - Unit* target = NULL; - Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range); - Trinity::UnitLastSearcher searcher(m_caster, target, u_check); - m_caster->VisitNearbyObject(range, searcher); - return target; - } + // do far effects on the unit + // can't use default call because of threading, do stuff as fast as possible + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + if (farMask & (1 << i)) + HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_HIT_TARGET); + return; } -} -uint32 Spell::SelectEffectTargets(uint32 i, SpellImplicitTargetInfo const& cur) -{ - SpellNotifyPushType pushType = PUSH_NONE; - Player* modOwner = NULL; - if (m_originalCaster) - modOwner = m_originalCaster->GetSpellModOwner(); + if (unit->isAlive() != target->alive) + return; - uint32 effectMask = 1 << i; - // ENTRY targets may have different selection lists, skip those for now until we can compare lists easily and quickly - if (GetSpellInfo()->Effects[i].TargetA.GetSelectionCheckType() != TARGET_SELECT_CHECK_ENTRY && - GetSpellInfo()->Effects[i].TargetB.GetSelectionCheckType() != TARGET_SELECT_CHECK_ENTRY) - for (uint32 j = i + 1; j < MAX_SPELL_EFFECTS; ++j) - if (GetSpellInfo()->Effects[i].TargetA.GetTarget() == GetSpellInfo()->Effects[j].TargetA.GetTarget() && - GetSpellInfo()->Effects[i].TargetB.GetTarget() == GetSpellInfo()->Effects[j].TargetB.GetTarget() && - GetSpellInfo()->Effects[i].CalcRadius(m_caster) == GetSpellInfo()->Effects[j].CalcRadius(m_caster)) - effectMask |= 1 << j; + if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsPositive() && (getMSTime() - target->timeDelay) <= unit->m_lastSanctuaryTime) + return; // No missinfo in that case - switch (cur.GetType()) - { - case TARGET_TYPE_UNIT_CASTER: - { - switch (cur.GetTarget()) - { - case TARGET_UNIT_CASTER: - AddUnitTarget(m_caster, effectMask, false); - break; - case TARGET_DEST_CASTER_FISHING: - { - float min_dis = m_spellInfo->GetMinRange(true); - float max_dis = m_spellInfo->GetMaxRange(true); - float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; - float x, y, z, angle; - angle = (float)rand_norm() * static_cast(M_PI * 35.0f / 180.0f) - static_cast(M_PI * 17.5f / 180.0f); - m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, angle); - m_targets.SetDst(x, y, z, m_caster->GetOrientation()); - break; - } - case TARGET_UNIT_MASTER: - if (Unit* owner = m_caster->GetCharmerOrOwner()) - AddUnitTarget(owner, effectMask); - break; - case TARGET_UNIT_PET: - if (Guardian* pet = m_caster->GetGuardianPet()) - AddUnitTarget(pet, effectMask); - break; - case TARGET_UNIT_SUMMONER: - if (m_caster->isSummon()) - if (Unit* unit = m_caster->ToTempSummon()->GetSummoner()) - AddUnitTarget(unit, effectMask); - break; - case TARGET_UNIT_CASTER_AREA_PARTY: - case TARGET_UNIT_CASTER_AREA_RAID: - pushType = PUSH_CASTER_CENTER; - break; - case TARGET_UNIT_VEHICLE: - if (Unit* vehicle = m_caster->GetVehicleBase()) - AddUnitTarget(vehicle, effectMask); - break; - case TARGET_UNIT_PASSENGER_0: - case TARGET_UNIT_PASSENGER_1: - case TARGET_UNIT_PASSENGER_2: - case TARGET_UNIT_PASSENGER_3: - case TARGET_UNIT_PASSENGER_4: - case TARGET_UNIT_PASSENGER_5: - case TARGET_UNIT_PASSENGER_6: - case TARGET_UNIT_PASSENGER_7: - if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsVehicle()) - if (Unit* unit = m_caster->GetVehicleKit()->GetPassenger(cur.GetTarget() - TARGET_UNIT_PASSENGER_0)) - AddUnitTarget(unit, effectMask); - break; - default: - break; - } - break; - } - - case TARGET_TYPE_UNIT_TARGET: - { - Unit* target = m_targets.GetUnitTarget(); - if (!target) - { - sLog->outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id); - break; - } - - switch (cur.GetTarget()) - { - case TARGET_UNIT_TARGET_ENEMY: - case TARGET_UNIT_TARGET_ANY: - pushType = PUSH_CHAIN; - break; - case TARGET_UNIT_TARGET_CHAINHEAL_ALLY: - pushType = PUSH_CHAIN; - break; - case TARGET_UNIT_TARGET_ALLY: - AddUnitTarget(target, effectMask, false); - break; - case TARGET_UNIT_TARGET_RAID: - case TARGET_UNIT_TARGET_PARTY: - case TARGET_UNIT_TARGET_MINIPET: - AddUnitTarget(target, effectMask, false); - break; - case TARGET_UNIT_TARGET_PASSENGER: - AddUnitTarget(target, effectMask, false); - break; - case TARGET_UNIT_LASTTARGET_AREA_PARTY: - case TARGET_UNIT_TARGET_AREA_RAID_CLASS: - pushType = PUSH_CASTER_CENTER; // not real - break; - default: - break; - } - break; - } - - case TARGET_TYPE_UNIT_NEARBY: - { - WorldObject* target = NULL; - float range; + // Get original caster (if exist) and calculate damage/healing from him data + Unit* caster = m_originalCaster ? m_originalCaster : m_caster; - switch (cur.GetTarget()) - { - case TARGET_UNIT_NEARBY_ENEMY: - range = m_spellInfo->GetMaxRange(false); - if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); - target = SearchNearbyTarget(range, SPELL_TARGETS_ENEMY, SpellEffIndex(i)); - break; - case TARGET_UNIT_NEARBY_ALLY: - case TARGET_UNIT_NEARBY_PARTY: // TODO: fix party/raid targets - case TARGET_UNIT_NEARBY_RAID: - range = m_spellInfo->GetMaxRange(true); - if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); - target = SearchNearbyTarget(range, SPELL_TARGETS_ALLY, SpellEffIndex(i)); - break; - case TARGET_UNIT_NEARBY_ENTRY: - case TARGET_GAMEOBJECT_NEARBY_ENTRY: - range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive()); - if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); - target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY, SpellEffIndex(i)); - break; - default: - break; - } + // Skip if m_originalCaster not avaiable + if (!caster) + return; - if (!target) - return 0; - else if (target->GetTypeId() == TYPEID_GAMEOBJECT) - AddGOTarget((GameObject*)target, effectMask); - else - { - pushType = PUSH_CHAIN; + SpellMissInfo missInfo = target->missCondition; - if (m_targets.GetUnitTarget() != target) - m_targets.SetUnitTarget((Unit*)target); - } + // Need init unitTarget by default unit (can changed in code on reflect) + // Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem) + unitTarget = unit; - break; - } + // Reset damage/healing counter + m_damage = target->damage; + m_healing = -target->damage; - case TARGET_TYPE_AREA_SRC: - pushType = PUSH_SRC_CENTER; - break; + // Fill base trigger info + uint32 procAttacker = m_procAttacker; + uint32 procVictim = m_procVictim; + uint32 procEx = m_procEx; - case TARGET_TYPE_AREA_DST: - pushType = PUSH_DST_CENTER; - break; + m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied - case TARGET_TYPE_AREA_CONE: - if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_BACK) - pushType = PUSH_IN_BACK; - else if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_LINE) - pushType = PUSH_IN_LINE; - else - pushType = PUSH_IN_FRONT; - break; + //Spells with this flag cannot trigger if effect is casted on self + bool canEffectTrigger = !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && CanExecuteTriggersOnHit(mask); + Unit* spellHitTarget = NULL; - case TARGET_TYPE_DEST_CASTER: //4+8+2 + if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target + spellHitTarget = unit; + else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit) + { + if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him { - if (cur.GetTarget() == TARGET_SRC_CASTER) - { - m_targets.SetSrc(*m_caster); - break; - } - else if (cur.GetTarget() == TARGET_DEST_CASTER) - { - m_targets.SetDst(*m_caster); - break; - } - - float angle, dist; - - float objSize = m_caster->GetObjectSize(); - if (cur.GetTarget() == TARGET_DEST_CASTER_SUMMON) - dist = 0.0f; - else - dist = m_spellInfo->Effects[i].CalcRadius(m_caster); - if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, dist, this); - if (dist < objSize) - dist = objSize; - else if (cur.GetTarget() == TARGET_DEST_CASTER_RANDOM) - dist = objSize + (dist - objSize) * (float)rand_norm(); - - switch (cur.GetTarget()) - { - case TARGET_DEST_CASTER_FRONT_LEFT: angle = static_cast(-M_PI/4); break; - case TARGET_DEST_CASTER_BACK_LEFT: angle = static_cast(-3*M_PI/4); break; - case TARGET_DEST_CASTER_BACK_RIGHT: angle = static_cast(3*M_PI/4); break; - case TARGET_DEST_CASTER_FRONT_RIGHT:angle = static_cast(M_PI/4); break; - case TARGET_DEST_CASTER_SUMMON: - case TARGET_DEST_CASTER_FRONT_LEAP: - case TARGET_DEST_CASTER_FRONT: angle = 0.0f; break; - case TARGET_DEST_CASTER_BACK: angle = static_cast(M_PI); break; - case TARGET_DEST_CASTER_RIGHT: angle = static_cast(-M_PI/2); break; - case TARGET_DEST_CASTER_LEFT: angle = static_cast(M_PI/2); break; - default: angle = (float)rand_norm()*static_cast(2*M_PI); break; - } - - Position pos; - if (cur.GetTarget() == TARGET_DEST_CASTER_FRONT_LEAP) - m_caster->GetFirstCollisionPosition(pos, dist, angle); - else - m_caster->GetNearPosition(pos, dist, angle); - m_targets.SetDst(*m_caster); - m_targets.ModDst(pos); - break; + spellHitTarget = m_caster; + if (m_caster->GetTypeId() == TYPEID_UNIT) + m_caster->ToCreature()->LowerPlayerDamageReq(target->damage); } + } - case TARGET_TYPE_DEST_TARGET: //2+8+2 + if (spellHitTarget) + { + SpellMissInfo missInfo2 = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura); + if (missInfo2 != SPELL_MISS_NONE) { - Unit* target = m_targets.GetUnitTarget(); - if (!target) - { - sLog->outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id); - break; - } - - if (cur.GetTarget() == TARGET_DEST_TARGET_ENEMY || cur.GetTarget() == TARGET_DEST_TARGET_ANY) - { - m_targets.SetDst(*target); - break; - } - - float angle, dist; - - float objSize = target->GetObjectSize(); - dist = m_spellInfo->Effects[i].CalcRadius(m_caster); - if (dist < objSize) - dist = objSize; - else if (cur.GetTarget() == TARGET_DEST_TARGET_RANDOM) - dist = objSize + (dist - objSize) * (float)rand_norm(); - - switch (cur.GetTarget()) - { - case TARGET_DEST_TARGET_FRONT: angle = 0.0f; break; - case TARGET_DEST_TARGET_BACK: angle = static_cast(M_PI); break; - case TARGET_DEST_TARGET_RIGHT: angle = static_cast(M_PI/2); break; - case TARGET_DEST_TARGET_LEFT: angle = static_cast(-M_PI/2); break; - case TARGET_DEST_TARGET_FRONT_LEFT: angle = static_cast(-M_PI/4); break; - case TARGET_DEST_TARGET_BACK_LEFT: angle = static_cast(-3*M_PI/4); break; - case TARGET_DEST_TARGET_BACK_RIGHT: angle = static_cast(3*M_PI/4); break; - case TARGET_DEST_TARGET_FRONT_RIGHT:angle = static_cast(M_PI/4); break; - default: angle = (float)rand_norm()*static_cast(2*M_PI); break; - } - - Position pos; - target->GetNearPosition(pos, dist, angle); - m_targets.SetDst(*target); - m_targets.ModDst(pos); - break; + if (missInfo2 != SPELL_MISS_MISS) + m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo2); + m_damage = 0; + spellHitTarget = NULL; } + } - case TARGET_TYPE_DEST_DEST: //5+8+1 - { - if (!m_targets.HasDst()) - { - sLog->outError("SPELL: no destination for spell ID %u", m_spellInfo->Id); - break; - } - - float angle; - switch (cur.GetTarget()) - { - case TARGET_DEST_DYNOBJ_ENEMY: - case TARGET_DEST_DYNOBJ_ALLY: - case TARGET_DEST_DYNOBJ_NONE: - case TARGET_DEST_DEST: - return effectMask; - case TARGET_DEST_TRAJ: - SelectTrajTargets(); - return effectMask; - case TARGET_DEST_DEST_FRONT: angle = 0.0f; break; - case TARGET_DEST_DEST_BACK: angle = static_cast(M_PI); break; - case TARGET_DEST_DEST_RIGHT: angle = static_cast(M_PI/2); break; - case TARGET_DEST_DEST_LEFT: angle = static_cast(-M_PI/2); break; - case TARGET_DEST_DEST_FRONT_LEFT: angle = static_cast(-M_PI/4); break; - case TARGET_DEST_DEST_BACK_LEFT: angle = static_cast(-3*M_PI/4); break; - case TARGET_DEST_DEST_BACK_RIGHT: angle = static_cast(3*M_PI/4); break; - case TARGET_DEST_DEST_FRONT_RIGHT:angle = static_cast(M_PI/4); break; - default: angle = (float)rand_norm()*static_cast(2*M_PI); break; - } - - float dist = m_spellInfo->Effects[i].CalcRadius(m_caster); - if (cur.GetTarget() == TARGET_DEST_DEST_RANDOM || cur.GetTarget() == TARGET_DEST_DEST_RADIUS) - dist *= (float)rand_norm(); - - // must has dst, no need to set flag - Position pos = *m_targets.GetDst(); - m_caster->MovePosition(pos, dist, angle); - m_targets.ModDst(pos); - break; - } + // Do not take combo points on dodge and miss + if (missInfo != SPELL_MISS_NONE && m_needComboPoints && + m_targets.GetUnitTargetGUID() == target->targetGUID) + { + m_needComboPoints = false; + // Restore spell mods for a miss/dodge/parry Cold Blood + // TODO: check how broad this rule should be + if (m_caster->GetTypeId() == TYPEID_PLAYER && (missInfo == SPELL_MISS_MISS || + missInfo == SPELL_MISS_DODGE || missInfo == SPELL_MISS_PARRY)) + m_caster->ToPlayer()->RestoreSpellMods(this, 14177); + } - case TARGET_TYPE_DEST_SPECIAL: + // Trigger info was not filled in spell::preparedatafortriggersystem - we do it now + if (canEffectTrigger && !procAttacker && !procVictim) + { + bool positive = true; + if (m_damage > 0) + positive = false; + else if (!m_healing) { - switch (cur.GetTarget()) - { - case TARGET_DEST_DB: - if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id)) - { - //TODO: fix this check - if (m_spellInfo->Effects[0].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[1].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[2].Effect == SPELL_EFFECT_TELEPORT_UNITS) - m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId); - else if (st->target_mapId == m_caster->GetMapId()) - m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation); - } - else - { - sLog->outError("SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id); - Unit* target = NULL; - if (uint64 guid = m_caster->GetUInt64Value(UNIT_FIELD_TARGET)) - target = ObjectAccessor::GetUnit(*m_caster, guid); - m_targets.SetDst(target ? *target : *m_caster); - } - break; - case TARGET_DEST_HOME: - if (m_caster->GetTypeId() == TYPEID_PLAYER) - m_targets.SetDst(m_caster->ToPlayer()->m_homebindX, m_caster->ToPlayer()->m_homebindY, m_caster->ToPlayer()->m_homebindZ, m_caster->ToPlayer()->GetOrientation(), m_caster->ToPlayer()->m_homebindMapId); - break; - case TARGET_DEST_NEARBY_ENTRY: + for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) + // If at least one effect negative spell is negative hit + if (mask & (1<IsPositiveEffect(i)) { - float range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive()); - if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); - - if (WorldObject* target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY, SpellEffIndex(i))) - m_targets.SetDst(*target); + positive = false; break; } - default: - break; - } - break; } - - case TARGET_TYPE_CHANNEL: + switch (m_spellInfo->DmgClass) { - if (!m_originalCaster || !m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) - { - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: no current channeled spell for spell ID %u - spell triggering this spell was interrupted.", m_spellInfo->Id); - break; - } - - switch (cur.GetTarget()) - { - case TARGET_UNIT_CHANNEL_TARGET: - // unit target may be no longer avalible - teleported out of map for example - if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.GetUnitTargetGUID())) - AddUnitTarget(target, effectMask); - else - sLog->outError("SPELL: cannot find channel spell target for spell ID %u", m_spellInfo->Id); - break; - case TARGET_DEST_CHANNEL_TARGET: - if (m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.HasDst()) - m_targets.SetDst(m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets); - else if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.GetUnitTargetGUID())) - m_targets.SetDst(*target); - else - sLog->outError("SPELL: cannot find channel spell destination for spell ID %u", m_spellInfo->Id); - break; - case TARGET_DEST_CHANNEL_CASTER: - m_targets.SetDst(*m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->GetCaster()); - break; - default: - break; - } + case SPELL_DAMAGE_CLASS_MAGIC: + if (positive) + { + procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS; + procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS; + } + else + { + procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; + procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG; + } break; - } - - default: - { - switch (cur.GetTarget()) - { - case TARGET_GAMEOBJECT_TARGET: - if (m_targets.GetGOTarget()) - AddGOTarget(m_targets.GetGOTarget(), effectMask); - break; - case TARGET_GAMEOBJECT_ITEM_TARGET: - if (m_targets.GetGOTargetGUID()) - AddGOTarget(m_targets.GetGOTarget(), effectMask); - else if (m_targets.GetItemTarget()) - AddItemTarget(m_targets.GetItemTarget(), effectMask); - break; - default: - sLog->outError("SPELL (caster[type: %u; guidlow: %u], spell: %u): unhandled spell target (%u)", - m_caster->GetTypeId(), m_caster->GetGUIDLow(), m_spellInfo->Id, cur.GetTarget()); - break; - } + case SPELL_DAMAGE_CLASS_NONE: + if (positive) + { + procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS; + procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS; + } + else + { + procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; + procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG; + } break; } } + CallScriptOnHitHandlers(); - if (pushType == PUSH_CHAIN) // Chain + // All calculated do it! + // Do healing and triggers + if (m_healing > 0) { - Unit* target = m_targets.GetUnitTarget(); - if (!target) + bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask); + uint32 addhealth = m_healing; + if (crit) { - sLog->outError("SPELL: no chain unit target for spell ID %u", m_spellInfo->Id); - return 0; + procEx |= PROC_EX_CRITICAL_HIT; + addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL); } + else + procEx |= PROC_EX_NORMAL_HIT; - //Chain: 2, 6, 22, 25, 45, 77 - uint32 maxTargets = m_spellInfo->Effects[i].ChainTarget; - if (modOwner) - modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this); + // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) + if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) + caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell); - if (maxTargets > 1) - { - //otherwise, this multiplier is used for something else - for (uint32 k = i; k < MAX_SPELL_EFFECTS; ++k) - if (effectMask & (1 << k)) - m_damageMultipliers[k] = 1.0f; - m_applyMultiplierMask |= effectMask; + int32 gain = caster->HealBySpell(unitTarget, m_spellInfo, addhealth, crit); + unitTarget->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo); + m_healing = gain; + } + // Do damage and triggers + else if (m_damage > 0) + { + // Fill base damage struct (unitTarget - is real spell target) + SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); - float range; - std::list unitList; + // Add bonuses and fill damageInfo struct + caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit); + caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); - switch (cur.GetTarget()) - { - case TARGET_UNIT_NEARBY_ENEMY: - case TARGET_UNIT_TARGET_ENEMY: - case TARGET_UNIT_NEARBY_ENTRY: // fix me - range = m_spellInfo->GetMaxRange(false); - if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); - SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_ENEMY); - break; - case TARGET_UNIT_TARGET_CHAINHEAL_ALLY: - case TARGET_UNIT_NEARBY_ALLY: // fix me - case TARGET_UNIT_NEARBY_PARTY: - case TARGET_UNIT_NEARBY_RAID: - range = m_spellInfo->GetMaxRange(true); - if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); - SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_CHAINHEAL); - break; - default: - break; - } + // Send log damage message to client + caster->SendSpellNonMeleeDamageLog(&damageInfo); - CallScriptAfterUnitTargetSelectHandlers(unitList, SpellEffIndex(i)); + procEx |= createProcExtendMask(&damageInfo, missInfo); + procVictim |= PROC_FLAG_TAKEN_DAMAGE; - for (std::list::iterator itr = unitList.begin(); itr != unitList.end(); ++itr) - AddUnitTarget(*itr, effectMask, false); - } - else - AddUnitTarget(target, effectMask, false); + // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) + if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) + { + caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell); + if (caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 && + (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) + caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx); + } + + caster->DealSpellDamage(&damageInfo, true); + + // Haunt + if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[1] & 0x40000 && m_spellAura && m_spellAura->GetEffect(1)) + { + AuraEffect* aurEff = m_spellAura->GetEffect(1); + aurEff->SetAmount(CalculatePctU(aurEff->GetAmount(), damageInfo.damage)); + } + m_damage = damageInfo.damage; } - else if (pushType) + // Passive spell hits/misses or active spells only misses (only triggers) + else { - float radius; - SpellTargets targetType; - switch (cur.GetTarget()) + // Fill base damage struct (unitTarget - is real spell target) + SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); + procEx |= createProcExtendMask(&damageInfo, missInfo); + // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) + if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) + caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell); + + // Failed Pickpocket, reveal rogue + if (missInfo == SPELL_MISS_RESIST && m_spellInfo->AttributesCu & SPELL_ATTR0_CU_PICKPOCKET && unitTarget->GetTypeId() == TYPEID_UNIT) { - case TARGET_UNIT_SRC_AREA_ENEMY: - case TARGET_UNIT_DEST_AREA_ENEMY: - case TARGET_UNIT_CONE_ENEMY_24: - case TARGET_UNIT_CONE_ENEMY_54: - case TARGET_UNIT_CONE_ENEMY_104: - radius = m_spellInfo->Effects[i].CalcRadius(); - targetType = SPELL_TARGETS_ENEMY; - break; - case TARGET_UNIT_SRC_AREA_ALLY: - case TARGET_UNIT_DEST_AREA_ALLY: - case TARGET_UNIT_CONE_ALLY: - radius = m_spellInfo->Effects[i].CalcRadius(); - targetType = SPELL_TARGETS_ALLY; - break; - case TARGET_UNIT_DEST_AREA_ENTRY: - case TARGET_UNIT_SRC_AREA_ENTRY: - case TARGET_UNIT_CONE_ENTRY: // fix me - radius = m_spellInfo->Effects[i].CalcRadius(); - targetType = SPELL_TARGETS_ENTRY; - break; - case TARGET_GAMEOBJECT_SRC_AREA: - case TARGET_GAMEOBJECT_DEST_AREA: - case TARGET_GAMEOBJECT_CONE: - radius = m_spellInfo->Effects[i].CalcRadius(); - targetType = SPELL_TARGETS_GO; - break; - default: - radius = m_spellInfo->Effects[i].CalcRadius(); - targetType = SPELL_TARGETS_NONE; - break; + m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); + if (unitTarget->ToCreature()->IsAIEnabled) + unitTarget->ToCreature()->AI()->AttackStart(m_caster); + } + } + + if (missInfo != SPELL_MISS_EVADE && m_caster && !m_caster->IsFriendlyTo(unit) && !m_spellInfo->IsPositive()) + { + m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)); + + if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) + if (!unit->IsStandState()) + unit->SetStandState(UNIT_STAND_STATE_STAND); + } + + if (spellHitTarget) + { + //AI functions + if (spellHitTarget->GetTypeId() == TYPEID_UNIT) + { + if (spellHitTarget->ToCreature()->IsAIEnabled) + spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo); + + // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) + // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm...) + if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !spellHitTarget->ToCreature()->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) + if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) + p->CastedCreatureOrGO(spellHitTarget->GetEntry(), spellHitTarget->GetGUID(), m_spellInfo->Id); } - if (modOwner) - modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius, this); - radius *= m_spellValue->RadiusMod; + if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled) + m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo); + + // Needs to be called after dealing damage/healing to not remove breaking on damage auras + DoTriggersOnSpellHit(spellHitTarget, mask); + + // if target is fallged for pvp also flag caster if a player + if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER) + m_caster->ToPlayer()->UpdatePvP(true); + + CallScriptAfterHitHandlers(); + } +} + +SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleAura) +{ + if (!unit || !effectMask) + return SPELL_MISS_EVADE; - std::list unitList; - std::list gobjectList; - switch (targetType) + // For delayed spells immunity may be applied between missile launch and hit - check immunity for that case + // disable effects to which unit is immune + for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) + if (effectMask & (1 << effectNumber) && unit->IsImmunedToSpellEffect(m_spellInfo, effectNumber)) + effectMask &= ~(1 << effectNumber); + if (!effectMask || (m_spellInfo->Speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo)))) + return SPELL_MISS_IMMUNE; + + PrepareScriptHitHandlers(); + CallScriptBeforeHitHandlers(); + + if (unit->GetTypeId() == TYPEID_PLAYER) + { + unit->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id); + unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, m_caster); + unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id); + } + + if (m_caster->GetTypeId() == TYPEID_PLAYER) + { + m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id); + m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit); + } + + if (m_caster != unit) + { + // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells + if (m_spellInfo->Speed > 0.0f && unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID()) + return SPELL_MISS_EVADE; + + if (m_caster->_IsValidAttackTarget(unit, m_spellInfo)) + { + unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL); + //TODO: This is a hack. But we do not know what types of stealth should be interrupted by CC + if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) && unit->IsControlledByPlayer()) + unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); + } + else if (m_caster->IsFriendlyTo(unit)) { - case SPELL_TARGETS_ENTRY: + // for delayed spells ignore negative spells (after duel end) for friendly targets + // TODO: this cause soul transfer bugged + if (m_spellInfo->Speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->IsPositive()) + return SPELL_MISS_EVADE; + + // assisting case, healing and resurrection + if (unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER)) { - ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id); - if (!conditions.empty()) - { - for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST) - { - if ((*i_spellST)->ConditionType != CONDITION_SPELL_SCRIPT_TARGET) - continue; - if ((*i_spellST)->ConditionValue3 && !((*i_spellST)->ConditionValue3 & effectMask)) - continue; - if ((*i_spellST)->ConditionValue1 == SPELL_TARGET_TYPE_CREATURE) - SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, (*i_spellST)->ConditionValue2); - else if ((*i_spellST)->ConditionValue1 == SPELL_TARGET_TYPE_CONTROLLED) - { - for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr) - if ((*itr)->GetEntry() == (*i_spellST)->ConditionValue2 && - (*itr)->IsInMap(m_caster)) // For 60243 and 52173 need skip radius check or use range (no radius entry for effect) - unitList.push_back(*itr); - } - } - } - else - { - // Custom entries - // TODO: move these to sql - switch (m_spellInfo->Id) - { - case 46584: // Raise Dead - { - if (WorldObject* result = FindCorpseUsing()) - { - switch (result->GetTypeId()) - { - case TYPEID_UNIT: - case TYPEID_PLAYER: - unitList.push_back(result->ToUnit()); - // no break; - case TYPEID_CORPSE: // wont work until corpses are allowed in target lists, but at least will send dest in packet - m_targets.SetDst(*result); - break; - default: - break; - } - } - break; - } - // Corpse Explosion - case 49158: - case 51325: - case 51326: - case 51327: - case 51328: - // Search for ghoul if our ghoul or dead body not valid unit target - if (!(m_targets.GetUnitTarget() && ((m_targets.GetUnitTarget()->GetEntry() == 26125 && m_targets.GetUnitTarget()->GetOwnerGUID() == m_caster->GetGUID()) - || (m_targets.GetUnitTarget()->getDeathState() == CORPSE - && m_targets.GetUnitTarget()->GetTypeId() == TYPEID_UNIT - && !(m_targets.GetUnitTarget()->GetCreatureTypeMask() & CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL) - && m_targets.GetUnitTarget()->GetDisplayId() == m_targets.GetUnitTarget()->GetNativeDisplayId())))) - { - CleanupTargetList(); - - WorldObject* result = FindCorpseUsing(); - - if (result) - { - switch (result->GetTypeId()) - { - case TYPEID_UNIT: - case TYPEID_PLAYER: - m_targets.SetUnitTarget((Unit*)result); - break; - default: - break; - } - } - else - { - if (m_caster->GetTypeId() == TYPEID_PLAYER) - m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true); - SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW); - finish(false); - } - } - break; + m_caster->SetContestedPvP(); + if (m_caster->GetTypeId() == TYPEID_PLAYER) + m_caster->ToPlayer()->UpdatePvP(true); + } + if (unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)) + { + m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit); + unit->getHostileRefManager().threatAssist(m_caster, 0.0f); + } + } + } - default: - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) (caster Entry: %u) does not have type CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET record in `conditions` table.", m_spellInfo->Id, m_caster->GetEntry()); + // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add + m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo, m_triggeredByAuraSpell); + if (m_diminishGroup) + { + m_diminishLevel = unit->GetDiminishing(m_diminishGroup); + DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup); + // Increase Diminishing on unit, current informations for actually casts will use values above + if ((type == DRTYPE_PLAYER && unit->GetCharmerOrOwnerPlayerOrPlayerItself()) || type == DRTYPE_ALL) + unit->IncrDiminishing(m_diminishGroup); + } - if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_TELEPORT_UNITS) - SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, 0); - else if (m_spellInfo->IsPositiveEffect(i)) - SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ALLY); - else - SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENEMY); - } + uint8 aura_effmask = 0; + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + if (effectMask & (1 << i) && m_spellInfo->Effects[i].IsUnitOwnedAuraEffect()) + aura_effmask |= 1 << i; + + if (aura_effmask) + { + // Select rank for aura with level requirements only in specific cases + // Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target + SpellInfo const* aurSpellInfo = m_spellInfo; + int32 basePoints[3]; + if (scaleAura) + { + aurSpellInfo = m_spellInfo->GetAuraRankForLevel(unitTarget->getLevel()); + ASSERT(aurSpellInfo); + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + basePoints[i] = aurSpellInfo->Effects[i].BasePoints; + if (m_spellInfo->Effects[i].Effect != aurSpellInfo->Effects[i].Effect) + { + aurSpellInfo = m_spellInfo; + break; } - break; } - case SPELL_TARGETS_GO: + } + + if (m_originalCaster) + { + bool refresh = false; + m_spellAura = Aura::TryRefreshStackOrCreate(aurSpellInfo, effectMask, unit, + m_originalCaster, (aurSpellInfo == m_spellInfo)? &m_spellValue->EffectBasePoints[0] : &basePoints[0], m_CastItem, 0, &refresh); + if (m_spellAura) { - ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id); - if (!conditions.empty()) + // Set aura stack amount to desired value + if (m_spellValue->AuraStackAmount > 1) { - for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST) - { - if ((*i_spellST)->ConditionType != CONDITION_SPELL_SCRIPT_TARGET) - continue; - if ((*i_spellST)->ConditionValue3 && !((*i_spellST)->ConditionValue3 & effectMask)) - continue; - if ((*i_spellST)->ConditionValue1 == SPELL_TARGET_TYPE_GAMEOBJECT) - SearchGOAreaTarget(gobjectList, radius, pushType, SPELL_TARGETS_GO, (*i_spellST)->ConditionValue2); - } + if (!refresh) + m_spellAura->SetStackAmount(m_spellValue->AuraStackAmount); + else + m_spellAura->ModStackAmount(m_spellValue->AuraStackAmount); } - else + + // Now Reduce spell duration using data received at spell hit + int32 duration = m_spellAura->GetMaxDuration(); + int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup, aurSpellInfo); + float diminishMod = unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel, limitduration); + + // unit is immune to aura if it was diminished to 0 duration + if (diminishMod == 0.0f) { - if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_ACTIVATE_OBJECT) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) (caster Entry: %u) with SPELL_EFFECT_ACTIVATE_OBJECT does not have type CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET record in `conditions` table.", m_spellInfo->Id, m_caster->GetEntry()); - SearchGOAreaTarget(gobjectList, radius, pushType, SPELL_TARGETS_GO); + m_spellAura->Remove(); + bool found = false; + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + if (effectMask & (1 << i) && m_spellInfo->Effects[i].Effect != SPELL_EFFECT_APPLY_AURA) + found = true; + if (!found) + return SPELL_MISS_IMMUNE; } - break; - } - case SPELL_TARGETS_ALLY: - case SPELL_TARGETS_ENEMY: - case SPELL_TARGETS_CHAINHEAL: - case SPELL_TARGETS_ANY: - SearchAreaTarget(unitList, radius, pushType, targetType); - break; - default: - switch (cur.GetTarget()) + else { - case TARGET_UNIT_SRC_AREA_PARTY: - case TARGET_UNIT_DEST_AREA_PARTY: - m_caster->GetPartyMemberInDist(unitList, radius); //fix me - break; - case TARGET_UNIT_LASTTARGET_AREA_PARTY: - m_targets.GetUnitTarget()->GetPartyMemberInDist(unitList, radius); - break; - case TARGET_UNIT_CASTER_AREA_PARTY: - m_caster->GetPartyMemberInDist(unitList, radius); - break; - case TARGET_UNIT_CASTER_AREA_RAID: - m_caster->GetRaidMember(unitList, radius); - break; - case TARGET_UNIT_TARGET_AREA_RAID_CLASS: + ((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup); + + bool positive = m_spellAura->GetSpellInfo()->IsPositive(); + if (AuraApplication* aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID())) + positive = aurApp->IsPositive(); + + duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive, effectMask); + + // Haste modifies duration of channeled spells + if (m_spellInfo->IsChanneled()) { - Player* targetPlayer = m_targets.GetUnitTarget() && m_targets.GetUnitTarget()->GetTypeId() == TYPEID_PLAYER - ? (Player*)m_targets.GetUnitTarget() : NULL; + if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) + m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this); + } + // and duration of auras affected by SPELL_AURA_PERIODIC_HASTE + else if (m_originalCaster->HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, aurSpellInfo) || m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) + duration = int32(duration * m_originalCaster->GetFloatValue(UNIT_MOD_CAST_SPEED)); - Group* group = targetPlayer ? targetPlayer->GetGroup() : NULL; - if (group) - { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) - { - Player* Target = itr->getSource(); - - // IsHostileTo check duel and controlled by enemy - if (Target && targetPlayer->IsWithinDistInMap(Target, radius) && targetPlayer->getClass() == Target->getClass() && !m_caster->IsHostileTo(Target)) - AddUnitTarget(Target, effectMask); - } - } - else if (m_targets.GetUnitTarget()) - AddUnitTarget(m_targets.GetUnitTarget(), effectMask); - break; + if (duration != m_spellAura->GetMaxDuration()) + { + m_spellAura->SetMaxDuration(duration); + m_spellAura->SetDuration(duration); } - default: - break; + m_spellAura->_RegisterForTargets(); } - break; } + } + } - if (!unitList.empty()) + for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) + if (effectMask & (1 << effectNumber)) + HandleEffects(unit, NULL, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + + return SPELL_MISS_NONE; +} + +void Spell::DoTriggersOnSpellHit(Unit* unit, uint8 effMask) +{ + // Apply additional spell effects to target + // TODO: move this code to scripts + if (m_preCastSpell) + { + // Paladin immunity shields + if (m_preCastSpell == 61988) { - // Special target selection for smart heals and energizes - uint32 maxSize = 0; - int32 power = -1; - switch (m_spellInfo->SpellFamilyName) - { - case SPELLFAMILY_GENERIC: - switch (m_spellInfo->Id) - { - case 52759: // Ancestral Awakening - case 71610: // Echoes of Light (Althor's Abacus normal version) - case 71641: // Echoes of Light (Althor's Abacus heroic version) - maxSize = 1; - power = POWER_HEALTH; - break; - case 54968: // Glyph of Holy Light - maxSize = m_spellInfo->MaxAffectedTargets; - power = POWER_HEALTH; - break; - case 57669: // Replenishment - // In arenas Replenishment may only affect the caster - if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->InArena()) - { - unitList.clear(); - unitList.push_back(m_caster); - break; - } - maxSize = 10; - power = POWER_MANA; - break; - default: - break; - } - break; - case SPELLFAMILY_PRIEST: - if (m_spellInfo->SpellFamilyFlags[0] == 0x10000000) // Circle of Healing - { - maxSize = m_caster->HasAura(55675) ? 6 : 5; // Glyph of Circle of Healing - power = POWER_HEALTH; - } - else if (m_spellInfo->Id == 64844) // Divine Hymn - { - maxSize = 3; - power = POWER_HEALTH; - } - else if (m_spellInfo->Id == 64904) // Hymn of Hope - { - maxSize = 3; - power = POWER_MANA; - } - else - break; + // Cast Forbearance + m_caster->CastSpell(unit, 25771, true); + // Cast Avenging Wrath Marker + unit->CastSpell(unit, 61987, true); + } - // Remove targets outside caster's raid - for (std::list::iterator itr = unitList.begin() ; itr != unitList.end();) - { - if (!(*itr)->IsInRaidWith(m_caster)) - itr = unitList.erase(itr); - else - ++itr; - } - break; - case SPELLFAMILY_DRUID: - if (m_spellInfo->SpellFamilyFlags[1] == 0x04000000) // Wild Growth - { - maxSize = m_caster->HasAura(62970) ? 6 : 5; // Glyph of Wild Growth - power = POWER_HEALTH; - } - else if (m_spellInfo->SpellFamilyFlags[2] == 0x0100) // Starfall - { - // Remove targets not in LoS or in stealth - for (std::list::iterator itr = unitList.begin() ; itr != unitList.end();) - { - if ((*itr)->HasStealthAura() || (*itr)->HasInvisibilityAura() || !(*itr)->IsWithinLOSInMap(m_caster)) - itr = unitList.erase(itr); - else - ++itr; - } - break; - } - else - break; + // Avenging Wrath + if (m_preCastSpell == 61987) + // Cast the serverside immunity shield marker + m_caster->CastSpell(unit, 61988, true); - // Remove targets outside caster's raid - for (std::list::iterator itr = unitList.begin() ; itr != unitList.end();) - if (!(*itr)->IsInRaidWith(m_caster)) - itr = unitList.erase(itr); - else - ++itr; - break; - default: - break; - } + if (sSpellMgr->GetSpellInfo(m_preCastSpell)) + // Blizz seems to just apply aura without bothering to cast + m_caster->AddAura(m_preCastSpell, unit); + } - if (maxSize && power != -1) + // handle SPELL_AURA_ADD_TARGET_TRIGGER auras + // this is executed after spell proc spells on target hit + // spells are triggered for each hit spell target + // info confirmed with retail sniffs of permafrost and shadow weaving + if (!m_hitTriggerSpells.empty()) + { + int _duration = 0; + for (HitTriggerSpells::const_iterator i = m_hitTriggerSpells.begin(); i != m_hitTriggerSpells.end(); ++i) + { + if (CanExecuteTriggersOnHit(effMask, i->first) && roll_chance_i(i->second)) { - if (Powers(power) == POWER_HEALTH) - { - if (unitList.size() > maxSize) - { - unitList.sort(Trinity::HealthPctOrderPred()); - unitList.resize(maxSize); - } - } - else - { - for (std::list::iterator itr = unitList.begin() ; itr != unitList.end();) - if ((*itr)->getPowerType() != (Powers)power) - itr = unitList.erase(itr); - else - ++itr; + m_caster->CastSpell(unit, i->first, true); + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->first->Id); - if (unitList.size() > maxSize) + // SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration + // set duration of current aura to the triggered spell + if (i->first->GetDuration() == -1) + { + if (Aura* triggeredAur = unit->GetAura(i->first->Id, m_caster->GetGUID())) { - unitList.sort(Trinity::PowerPctOrderPred((Powers)power)); - unitList.resize(maxSize); + // get duration from aura-only once + if (!_duration) + { + Aura* aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID()); + _duration = aur ? aur->GetDuration() : -1; + } + triggeredAur->SetDuration(_duration); } } } + } + } - // Other special target selection goes here - if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) + // trigger linked auras remove/apply + // TODO: remove/cleanup this, as this table is not documented and people are doing stupid things with it + if (std::vector const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT)) + for (std::vector::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i) + if (*i < 0) + unit->RemoveAurasDueToSpell(-(*i)); + else + unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID()); +} + +void Spell::DoAllEffectOnTarget(GOTargetInfo* target) +{ + if (target->processed) // Check target + return; + target->processed = true; // Target checked in apply effects procedure + + uint32 effectMask = target->effectMask; + if (!effectMask) + return; + + GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID); + if (!go) + return; + + PrepareScriptHitHandlers(); + CallScriptBeforeHitHandlers(); + + for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) + if (effectMask & (1 << effectNumber)) + HandleEffects(NULL, NULL, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + + CallScriptOnHitHandlers(); + + // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) + // ignore autorepeat/melee casts for speed (not exist quest for spells (hm...) + if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) + if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) + p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id); + CallScriptAfterHitHandlers(); +} + +void Spell::DoAllEffectOnTarget(ItemTargetInfo* target) +{ + uint32 effectMask = target->effectMask; + if (!target->item || !effectMask) + return; + + PrepareScriptHitHandlers(); + CallScriptBeforeHitHandlers(); + + for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) + if (effectMask & (1 << effectNumber)) + HandleEffects(NULL, target->item, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + + CallScriptOnHitHandlers(); + + CallScriptAfterHitHandlers(); +} + +bool Spell::UpdateChanneledTargetList() +{ + // Not need check return true + if (m_channelTargetEffectMask == 0) + return true; + + uint8 channelTargetEffectMask = m_channelTargetEffectMask; + uint8 channelAuraMask = 0; + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA) + channelAuraMask |= 1<GetMaxRange(m_spellInfo->IsPositive()); + if (Player* modOwner = m_caster->GetSpellModOwner()) + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); + } + + for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + { + if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask)) + { + Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); + + if (!unit) + continue; + + if (IsValidDeadOrAliveTarget(unit)) { - Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); - for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) - if ((*j)->IsAffectedOnSpell(m_spellInfo)) - maxTargets += (*j)->GetAmount(); + if (channelAuraMask & ihit->effectMask) + { + if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) + { + if (m_caster != unit && !m_caster->IsWithinDistInMap(unit, range)) + { + ihit->effectMask &= ~aurApp->GetEffectMask(); + unit->RemoveAura(aurApp); + continue; + } + } + else // aura is dispelled + continue; + } - if (m_spellInfo->Id == 5246) //Intimidating Shout - unitList.remove(m_targets.GetUnitTarget()); - Trinity::RandomResizeList(unitList, maxTargets); + channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target } + } + } - CallScriptAfterUnitTargetSelectHandlers(unitList, SpellEffIndex(i)); + // is all effects from m_needAliveTargetMask have alive targets + return channelTargetEffectMask == 0; +} - for (std::list::iterator itr = unitList.begin(); itr != unitList.end(); ++itr) - AddUnitTarget(*itr, effectMask, false); - } +// Helper for Chain Healing +// Spell target first +// Raidmates then descending by injury suffered (MaxHealth - Health) +// Other players/mobs then descending by injury suffered (MaxHealth - Health) +struct ChainHealingOrder : public std::binary_function +{ + const Unit* MainTarget; + ChainHealingOrder(Unit const* Target) : MainTarget(Target) {}; + // functor for operator ">" + bool operator()(Unit const* _Left, Unit const* _Right) const + { + return (ChainHealingHash(_Left) < ChainHealingHash(_Right)); + } - if (!gobjectList.empty()) + int32 ChainHealingHash(Unit const* Target) const + { + if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER && Target->ToPlayer()->IsInSameRaidWith(MainTarget->ToPlayer())) { - if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) - { - Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); - for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) - if ((*j)->IsAffectedOnSpell(m_spellInfo)) - maxTargets += (*j)->GetAmount(); - - Trinity::RandomResizeList(gobjectList, maxTargets); - } - for (std::list::iterator itr = gobjectList.begin(); itr != gobjectList.end(); ++itr) - AddGOTarget(*itr, effectMask); + if (Target->IsFullHealth()) + return 40000; + else + return 20000 - Target->GetMaxHealth() + Target->GetHealth(); } + else + return 40000 - Target->GetMaxHealth() + Target->GetHealth(); } - - return effectMask; -} +}; void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura) { @@ -6847,150 +6854,6 @@ void Spell::SetSpellValue(SpellValueMod mod, int32 value) } } -float tangent(float x) -{ - x = tan(x); - //if (x < std::numeric_limits::max() && x > -std::numeric_limits::max()) return x; - //if (x >= std::numeric_limits::max()) return std::numeric_limits::max(); - //if (x <= -std::numeric_limits::max()) return -std::numeric_limits::max(); - if (x < 100000.0f && x > -100000.0f) return x; - if (x >= 100000.0f) return 100000.0f; - if (x <= 100000.0f) return -100000.0f; - return 0.0f; -} - -#define DEBUG_TRAJ(a) //a - -void Spell::SelectTrajTargets() -{ - if (!m_targets.HasTraj()) - return; - - float dist2d = m_targets.GetDist2d(); - if (!dist2d) - return; - - float srcToDestDelta = m_targets.GetDst()->m_positionZ - m_targets.GetSrc()->m_positionZ; - - UnitList unitList; - SearchAreaTarget(unitList, dist2d, PUSH_IN_THIN_LINE, SPELL_TARGETS_ANY); - if (unitList.empty()) - return; - - unitList.sort(Trinity::ObjectDistanceOrderPred(m_caster)); - - float b = tangent(m_targets.GetElevation()); - float a = (srcToDestDelta - dist2d * b) / (dist2d * dist2d); - if (a > -0.0001f) - a = 0; - DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: a %f b %f", a, b);) - - float bestDist = m_spellInfo->GetMaxRange(false); - - UnitList::const_iterator itr = unitList.begin(); - for (; itr != unitList.end(); ++itr) - { - if (m_caster == *itr || m_caster->IsOnVehicle(*itr) || (*itr)->GetVehicle())//(*itr)->IsOnVehicle(m_caster)) - continue; - - const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3) - // TODO: all calculation should be based on src instead of m_caster - const float objDist2d = m_targets.GetSrc()->GetExactDist2d(*itr) * cos(m_targets.GetSrc()->GetRelativeAngle(*itr)); - const float dz = (*itr)->GetPositionZ() - m_targets.GetSrc()->m_positionZ; - - DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);) - - float dist = objDist2d - size; - float height = dist * (a * dist + b); - DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);) - if (dist < bestDist && height < dz + size && height > dz - size) - { - bestDist = dist > 0 ? dist : 0; - break; - } - -#define CHECK_DIST {\ - DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\ - if (dist > bestDist)\ - continue;\ - if (dist < objDist2d + size && dist > objDist2d - size)\ - {\ - bestDist = dist;\ - break;\ - }\ - } - - if (!a) - { - height = dz - size; - dist = height / b; - CHECK_DIST; - - height = dz + size; - dist = height / b; - CHECK_DIST; - - continue; - } - - height = dz - size; - float sqrt1 = b * b + 4 * a * height; - if (sqrt1 > 0) - { - sqrt1 = sqrt(sqrt1); - dist = (sqrt1 - b) / (2 * a); - CHECK_DIST; - } - - height = dz + size; - float sqrt2 = b * b + 4 * a * height; - if (sqrt2 > 0) - { - sqrt2 = sqrt(sqrt2); - dist = (sqrt2 - b) / (2 * a); - CHECK_DIST; - - dist = (-sqrt2 - b) / (2 * a); - CHECK_DIST; - } - - if (sqrt1 > 0) - { - dist = (-sqrt1 - b) / (2 * a); - CHECK_DIST; - } - } - - if (m_targets.GetSrc()->GetExactDist2d(m_targets.GetDst()) > bestDist) - { - float x = m_targets.GetSrc()->m_positionX + cos(m_caster->GetOrientation()) * bestDist; - float y = m_targets.GetSrc()->m_positionY + sin(m_caster->GetOrientation()) * bestDist; - float z = m_targets.GetSrc()->m_positionZ + bestDist * (a * bestDist + b); - - if (itr != unitList.end()) - { - float distSq = (*itr)->GetExactDistSq(x, y, z); - float sizeSq = (*itr)->GetObjectSize(); - sizeSq *= sizeSq; - DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) - if (distSq > sizeSq) - { - float factor = 1 - sqrt(sizeSq / distSq); - x += factor * ((*itr)->GetPositionX() - x); - y += factor * ((*itr)->GetPositionY() - y); - z += factor * ((*itr)->GetPositionZ() - z); - - distSq = (*itr)->GetExactDistSq(x, y, z); - DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) - } - } - - Position trajDst; - trajDst.Relocate(x, y, z, m_caster->GetOrientation()); - m_targets.ModDst(trajDst); - } -} - void Spell::PrepareTargetProcessing() { CheckEffectExecuteData(); @@ -7342,3 +7205,152 @@ void Spell::CancelGlobalCooldown() else if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo); } + +namespace Trinity +{ + +WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo, + SpellTargetCheckTypes selectionType, ConditionList* condList) : _caster(caster), _referer(referer), _spellInfo(spellInfo), + _condList(condList), _targetSelectionType(selectionType) +{ + if (condList) + _condSrcInfo = new ConditionSourceInfo(NULL, caster); + else + _condSrcInfo = NULL; +} + +WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck() +{ + if (_condSrcInfo) + delete _condSrcInfo; +} + +bool WorldObjectSpellTargetCheck::operator()(WorldObject* target) +{ + if (_spellInfo->CheckTarget(_caster, target, true) != SPELL_CAST_OK) + return false; + Unit* unitTarget = target->ToUnit(); + if (Corpse* corpseTarget = target->ToCorpse()) + { + // use ofter for party/assistance checks + if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) + unitTarget = owner; + else + return false; + } + if (unitTarget) + { + switch (_targetSelectionType) + { + case TARGET_CHECK_ENEMY: + if (unitTarget->isTotem()) + return false; + if (!_caster->_IsValidAttackTarget(unitTarget, _spellInfo)) + return false; + break; + case TARGET_CHECK_ALLY: + if (unitTarget->isTotem()) + return false; + if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) + return false; + break; + case TARGET_CHECK_PARTY: + if (unitTarget->isTotem()) + return false; + if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) + return false; + if (!_referer->IsInPartyWith(unitTarget)) + return false; + break; + case TARGET_CHECK_RAID_CLASS: + if (_referer->getClass() != unitTarget->getClass()) + return false; + // nobreak; + case TARGET_CHECK_RAID: + if (unitTarget->isTotem()) + return false; + if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) + return false; + if (!_referer->IsInRaidWith(unitTarget)) + return false; + break; + default: + break; + } + } + if (!_condSrcInfo) + return true; + _condSrcInfo->mConditionTargets[0] = target; + return sConditionMgr->IsObjectMeetToConditions(*_condSrcInfo, *_condList); +} + +WorldObjectSpellNearbyTargetCheck::WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo, + SpellTargetCheckTypes selectionType, ConditionList* condList) + : WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(caster) +{ +} + +bool WorldObjectSpellNearbyTargetCheck::operator()(WorldObject* target) +{ + float dist = target->GetDistance(*_position); + if (dist < _range && WorldObjectSpellTargetCheck::operator ()(target)) + { + _range = dist; + return true; + } + return false; +} + +WorldObjectSpellAreaTargetCheck::WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster, + Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) + : WorldObjectSpellTargetCheck(caster, referer, spellInfo, selectionType, condList), _range(range), _position(position) +{ +} + +bool WorldObjectSpellAreaTargetCheck::operator()(WorldObject* target) +{ + if (!target->IsWithinDist3d(_position, _range)) + return false; + return WorldObjectSpellTargetCheck::operator ()(target); +} + +WorldObjectSpellConeTargetCheck::WorldObjectSpellConeTargetCheck(float coneAngle, float range, Unit* caster, + SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) + : WorldObjectSpellAreaTargetCheck(range, caster, caster, caster, spellInfo, selectionType, condList), _coneAngle(coneAngle) +{ +} + +bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target) +{ + if (_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_BACK) + { + if (!_caster->isInBack(target, _coneAngle)) + return false; + } + else if (_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_LINE) + { + if (!_caster->HasInLine(target, _caster->GetObjectSize())) + return false; + } + else + { + if (!_caster->isInFront(target, _coneAngle)) + return false; + } + return WorldObjectSpellAreaTargetCheck::operator ()(target); +} + +WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, SpellInfo const* spellInfo) + : WorldObjectSpellAreaTargetCheck(range, position, caster, caster, spellInfo, TARGET_CHECK_DEFAULT, NULL) +{ +} + +bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target) +{ + // return all targets on missile trajectory (0 - size of a missile) + if (!_caster->HasInLine(target, 0)) + return false; + return WorldObjectSpellAreaTargetCheck::operator ()(target); +} + +} //namespace Trinity -- cgit v1.2.3