diff options
| author | Treeston <treeston.mmoc@gmail.com> | 2017-07-01 20:18:02 +0200 |
|---|---|---|
| committer | Shauren <shauren.trinity@gmail.com> | 2020-08-13 22:46:44 +0200 |
| commit | 8be23fcbbdf26e8169defd761e61765f301bebe0 (patch) | |
| tree | 6309b79f7dd617a8ddc801624dbbd4ed7ac22174 /src/server/game | |
| parent | 2c99678118798279372f17d4bb5f5a88ac95c413 (diff) | |
[3.3.5] Combat/Threat rewrite - prep & refactor (#19966)
* Combat/Threat rewrite (PR #19930) prep work. Mostly refactors, and a compatibility layer on ThreatManager/HostileReference that allows scripts to be changed already.
(cherry picked from commit e2a1ccd118d129b96e09ff1a15ed0adb1d4a3897)
Diffstat (limited to 'src/server/game')
28 files changed, 466 insertions, 393 deletions
diff --git a/src/server/game/AI/CoreAI/GuardAI.cpp b/src/server/game/AI/CoreAI/GuardAI.cpp index 2b358945bd9..bce356937a5 100644 --- a/src/server/game/AI/CoreAI/GuardAI.cpp +++ b/src/server/game/AI/CoreAI/GuardAI.cpp @@ -44,14 +44,9 @@ void GuardAI::UpdateAI(uint32 /*diff*/) bool GuardAI::CanSeeAlways(WorldObject const* obj) { - if (!obj->isType(TYPEMASK_UNIT)) - return false; - - ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); - for (ThreatContainer::StorageType::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr) - if ((*itr)->getUnitGuid() == obj->GetGUID()) + if (Unit const* unit = obj->ToUnit()) + if (unit->IsControlledByPlayer() && me->IsEngagedBy(unit)) return true; - return false; } @@ -61,14 +56,14 @@ void GuardAI::EnterEvadeMode(EvadeReason /*why*/) { me->GetMotionMaster()->MoveIdle(); me->CombatStop(true); - me->DeleteThreatList(); + me->GetThreatManager().ClearAllThreat(); return; } TC_LOG_DEBUG("entities.unit", "Guard entry: %u enters evade mode.", me->GetEntry()); me->RemoveAllAuras(); - me->DeleteThreatList(); + me->GetThreatManager().ClearAllThreat(); me->CombatStop(true); // Remove ChaseMovementGenerator from MotionMaster stack list, and add HomeMovementGenerator instead diff --git a/src/server/game/AI/CoreAI/UnitAI.cpp b/src/server/game/AI/CoreAI/UnitAI.cpp index 8d1ed85a6e8..c8942514c90 100644 --- a/src/server/game/AI/CoreAI/UnitAI.cpp +++ b/src/server/game/AI/CoreAI/UnitAI.cpp @@ -104,14 +104,14 @@ bool UnitAI::DoSpellAttackIfReady(uint32 spellId) return false; } -Unit* UnitAI::SelectTarget(SelectAggroTarget targetType, uint32 position, float dist, bool playerOnly, int32 aura) +Unit* UnitAI::SelectTarget(SelectAggroTarget targetType, uint32 position, float dist, bool playerOnly, bool withTank, int32 aura) { - return SelectTarget(targetType, position, DefaultTargetSelector(me, dist, playerOnly, aura)); + return SelectTarget(targetType, position, DefaultTargetSelector(me, dist, playerOnly, withTank, aura)); } -void UnitAI::SelectTargetList(std::list<Unit*>& targetList, uint32 num, SelectAggroTarget targetType, float dist, bool playerOnly, int32 aura) +void UnitAI::SelectTargetList(std::list<Unit*>& targetList, uint32 num, SelectAggroTarget targetType, uint32 offset, float dist, bool playerOnly, bool withTank, int32 aura) { - SelectTargetList(targetList, DefaultTargetSelector(me, dist, playerOnly, aura), num, targetType); + SelectTargetList(targetList, num, targetType, offset, DefaultTargetSelector(me, dist, playerOnly, withTank, aura)); } void UnitAI::DoCast(uint32 spellId) @@ -152,7 +152,7 @@ void UnitAI::DoCast(uint32 spellId) bool playerOnly = spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS); float range = spellInfo->GetMaxRange(false); - DefaultTargetSelector targetSelector(me, range, playerOnly, -(int32)spellId); + DefaultTargetSelector targetSelector(me, range, playerOnly, true, -(int32)spellId); if (!spellInfo->HasAuraInterruptFlag(AURA_INTERRUPT_FLAG_NOT_VICTIM) && targetSelector(me->GetVictim())) target = me->GetVictim(); else @@ -319,7 +319,17 @@ uint32 UnitAI::GetDialogStatus(Player* /*player*/) ThreatManager& UnitAI::GetThreatManager() { - return me->getThreatManager(); + return me->GetThreatManager(); +} + +void UnitAI::SortByDistance(std::list<Unit*> list, bool ascending) +{ + list.sort(Trinity::ObjectDistanceOrderPred(me, ascending)); +} + +DefaultTargetSelector::DefaultTargetSelector(Unit const* unit, float dist, bool playerOnly, bool withMainTank, int32 aura) + : me(unit), m_dist(dist), m_playerOnly(playerOnly), except(withMainTank ? me->GetThreatManager().GetCurrentVictim() : nullptr), m_aura(aura) +{ } bool DefaultTargetSelector::operator()(Unit const* target) const @@ -330,6 +340,9 @@ bool DefaultTargetSelector::operator()(Unit const* target) const if (!target) return false; + if (target == except) + return false; + if (m_playerOnly && (target->GetTypeId() != TYPEID_PLAYER)) return false; @@ -434,8 +447,8 @@ bool NonTankTargetSelector::operator()(Unit const* target) const if (_playerOnly && target->GetTypeId() != TYPEID_PLAYER) return false; - if (HostileReference* currentVictim = _source->getThreatManager().getCurrentVictim()) - return target->GetGUID() != currentVictim->getUnitGuid(); + if (Unit* currentVictim = _source->GetThreatManager().GetCurrentVictim()) + return target != currentVictim; return target != _source->GetVictim(); } @@ -476,8 +489,3 @@ bool FarthestTargetSelector::operator()(Unit const* target) const return true; } - -void SortByDistanceTo(Unit* reference, std::list<Unit*>& targets) -{ - targets.sort(Trinity::ObjectDistanceOrderPred(reference)); -} diff --git a/src/server/game/AI/CoreAI/UnitAI.h b/src/server/game/AI/CoreAI/UnitAI.h index 39f54dff66a..1e4c49c5703 100644 --- a/src/server/game/AI/CoreAI/UnitAI.h +++ b/src/server/game/AI/CoreAI/UnitAI.h @@ -47,11 +47,11 @@ enum SpellEffIndex : uint8; //Selection method used by SelectTarget enum SelectAggroTarget { - SELECT_TARGET_RANDOM = 0, //Just selects a random target - SELECT_TARGET_TOPAGGRO, //Selects targes from top aggro to bottom - SELECT_TARGET_BOTTOMAGGRO, //Selects targets from bottom aggro to top - SELECT_TARGET_NEAREST, - SELECT_TARGET_FARTHEST + SELECT_TARGET_RANDOM = 0, // just pick a random target + SELECT_TARGET_MAXTHREAT, // prefer targets higher in the threat list + SELECT_TARGET_MINTHREAT, // prefer targets lower in the threat list + SELECT_TARGET_MAXDISTANCE, // prefer targets further from us + SELECT_TARGET_MINDISTANCE // prefer targets closer to us }; // default predicate function to select target based on distance, player and/or aura criteria @@ -60,14 +60,15 @@ struct TC_GAME_API DefaultTargetSelector Unit const* me; float m_dist; bool m_playerOnly; + Unit const* except; int32 m_aura; // unit: the reference unit // dist: if 0: ignored, if > 0: maximum distance to the reference unit, if < 0: minimum distance to the reference unit // playerOnly: self explaining + // withMainTank: allow current tank to be selected // aura: if 0: ignored, if > 0: the target shall have the aura, if < 0, the target shall NOT have the aura - DefaultTargetSelector(Unit const* unit, float dist, bool playerOnly, int32 aura) : me(unit), m_dist(dist), m_playerOnly(playerOnly), m_aura(aura) { } - + DefaultTargetSelector(Unit const* unit, float dist, bool playerOnly, bool withMainTank, int32 aura); bool operator()(Unit const* target) const; }; @@ -125,8 +126,6 @@ private: bool _inLos; }; -TC_GAME_API void SortByDistanceTo(Unit* reference, std::list<Unit*>& targets); - class TC_GAME_API UnitAI { protected: @@ -153,92 +152,174 @@ class TC_GAME_API UnitAI virtual void SetGUID(ObjectGuid /*guid*/, int32 /*id*/ = 0) { } virtual ObjectGuid GetGUID(int32 /*id*/ = 0) const { return ObjectGuid::Empty; } - Unit* SelectTarget(SelectAggroTarget targetType, uint32 position = 0, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); - // Select the targets satisfying the predicate. + // Select the best target (in <targetType> order) from the threat list that fulfill the following: + // - Not among the first <offset> entries in <targetType> order (or MAXTHREAT order, if <targetType> is RANDOM). + // - Within at most <dist> yards (if dist > 0.0f) + // - At least -<dist> yards away (if dist < 0.0f) + // - Is a player (if playerOnly = true) + // - Not the current tank (if withTank = false) + // - Has aura with ID <aura> (if aura > 0) + // - Does not have aura with ID -<aura> (if aura < 0) + Unit* SelectTarget(SelectAggroTarget targetType, uint32 offset = 0, float dist = 0.0f, bool playerOnly = false, bool withTank = true, int32 aura = 0); + // Select the best target (in <targetType> order) satisfying <predicate> from the threat list. + // If <offset> is nonzero, the first <offset> entries in <targetType> order (or MAXTHREAT order, if <targetType> is RANDOM) are skipped. template<class PREDICATE> - Unit* SelectTarget(SelectAggroTarget targetType, uint32 position, PREDICATE const& predicate) + Unit* SelectTarget(SelectAggroTarget targetType, uint32 offset, PREDICATE const& predicate) { - ThreatContainer::StorageType const& threatlist = GetThreatManager().getThreatList(); - if (position >= threatlist.size()) + ThreatManager& mgr = GetThreatManager(); + // shortcut: if we ignore the first <offset> elements, and there are at most <offset> elements, then we ignore ALL elements + if (mgr.GetThreatListSize() <= offset) return nullptr; std::list<Unit*> targetList; - Unit* currentVictim = nullptr; - if (auto currentVictimReference = GetThreatManager().getCurrentVictim()) + if (targetType == SELECT_TARGET_MAXDISTANCE || targetType == SELECT_TARGET_MINDISTANCE) { - currentVictim = currentVictimReference->getTarget(); + for (ThreatReference* ref : mgr.GetUnsortedThreatList()) + { + if (ref->IsOffline()) + continue; - // Current victim always goes first - if (currentVictim && predicate(currentVictim)) + targetList.push_back(ref->GetVictim()); + } + } + else + { + Unit* currentVictim = mgr.GetCurrentVictim(); + if (currentVictim) targetList.push_back(currentVictim); + + for (ThreatReference* ref : mgr.GetSortedThreatList()) + { + if (ref->IsOffline()) + continue; + + Unit* thisTarget = ref->GetVictim(); + if (thisTarget != currentVictim) + targetList.push_back(thisTarget); + } } - for (HostileReference* hostileRef : threatlist) + // filter by predicate + targetList.remove_if([&predicate](Unit* target) { return !predicate(target); }); + + // shortcut: the list certainly isn't gonna get any larger after this point + if (targetList.size() <= offset) + return nullptr; + + // right now, list is unsorted for DISTANCE types - re-sort by MAXDISTANCE + if (targetType == SELECT_TARGET_MAXDISTANCE || targetType == SELECT_TARGET_MINDISTANCE) + SortByDistance(targetList, targetType == SELECT_TARGET_MINDISTANCE); + + // then reverse the sorting for MIN sortings + if (targetType == SELECT_TARGET_MINTHREAT) + targetList.reverse(); + + // now pop the first <offset> elements + while (offset) { - if (currentVictim != nullptr && hostileRef->getTarget() != currentVictim && predicate(hostileRef->getTarget())) - targetList.push_back(hostileRef->getTarget()); - else if (currentVictim == nullptr && predicate(hostileRef->getTarget())) - targetList.push_back(hostileRef->getTarget()); + targetList.pop_front(); + --offset; } - if (position >= targetList.size()) + // maybe nothing fulfills the predicate + if (targetList.empty()) return nullptr; - if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - SortByDistanceTo(me, targetList); - switch (targetType) { - case SELECT_TARGET_NEAREST: - case SELECT_TARGET_TOPAGGRO: - { - auto itr = targetList.begin(); - std::advance(itr, position); - return *itr; - } - case SELECT_TARGET_FARTHEST: - case SELECT_TARGET_BOTTOMAGGRO: - { - auto ritr = targetList.rbegin(); - std::advance(ritr, position); - return *ritr; - } + case SELECT_TARGET_MAXTHREAT: + case SELECT_TARGET_MINTHREAT: + case SELECT_TARGET_MAXDISTANCE: + case SELECT_TARGET_MINDISTANCE: + return targetList.front(); case SELECT_TARGET_RANDOM: return Trinity::Containers::SelectRandomContainerElement(targetList); default: - break; + return nullptr; } - - return nullptr; } - void SelectTargetList(std::list<Unit*>& targetList, uint32 num, SelectAggroTarget targetType, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); - - // Select the targets satifying the predicate. + // Select the best (up to) <num> targets (in <targetType> order) from the threat list that fulfill the following: + // - Not among the first <offset> entries in <targetType> order (or MAXTHREAT order, if <targetType> is RANDOM). + // - Within at most <dist> yards (if dist > 0.0f) + // - At least -<dist> yards away (if dist < 0.0f) + // - Is a player (if playerOnly = true) + // - Not the current tank (if withTank = false) + // - Has aura with ID <aura> (if aura > 0) + // - Does not have aura with ID -<aura> (if aura < 0) + // The resulting targets are stored in <targetList> (which is cleared first). + void SelectTargetList(std::list<Unit*>& targetList, uint32 num, SelectAggroTarget targetType, uint32 offset = 0, float dist = 0.0f, bool playerOnly = false, bool withTank = true, int32 aura = 0); + + // Select the best (up to) <num> targets (in <targetType> order) satisfying <predicate> from the threat list and stores them in <targetList> (which is cleared first). + // If <offset> is nonzero, the first <offset> entries in <targetType> order (or MAXTHREAT order, if <targetType> is RANDOM) are skipped. template <class PREDICATE> - void SelectTargetList(std::list<Unit*>& targetList, PREDICATE const& predicate, uint32 maxTargets, SelectAggroTarget targetType) + void SelectTargetList(std::list<Unit*>& targetList, uint32 num, SelectAggroTarget targetType, uint32 offset, PREDICATE const& predicate) { - ThreatContainer::StorageType const& threatlist = GetThreatManager().getThreatList(); - if (threatlist.empty()) + targetList.clear(); + ThreatManager& mgr = GetThreatManager(); + // shortcut: we're gonna ignore the first <offset> elements, and there's at most <offset> elements, so we ignore them all - nothing to do here + if (mgr.GetThreatListSize() <= offset) return; - for (HostileReference* hostileRef : threatlist) - if (predicate(hostileRef->getTarget())) - targetList.push_back(hostileRef->getTarget()); + if (targetType == SELECT_TARGET_MAXDISTANCE || targetType == SELECT_TARGET_MINDISTANCE) + { + for (ThreatReference* ref : mgr.GetUnsortedThreatList()) + { + if (ref->IsOffline()) + continue; + + targetList.push_back(ref->GetVictim()); + } + } + else + { + Unit* currentVictim = mgr.GetCurrentVictim(); + if (currentVictim) + targetList.push_back(currentVictim); + + for (ThreatReference* ref : mgr.GetSortedThreatList()) + { + if (ref->IsOffline()) + continue; + + Unit* thisTarget = ref->GetVictim(); + if (thisTarget != currentVictim) + targetList.push_back(thisTarget); + } + } + + // filter by predicate + targetList.remove_if([&predicate](Unit* target) { return !predicate(target); }); - if (targetList.size() < maxTargets) + // shortcut: the list isn't gonna get any larger + if (targetList.size() <= offset) + { + targetList.clear(); return; + } - if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - SortByDistanceTo(me, targetList); + // right now, list is unsorted for DISTANCE types - re-sort by MAXDISTANCE + if (targetType == SELECT_TARGET_MAXDISTANCE || targetType == SELECT_TARGET_MINDISTANCE) + SortByDistance(targetList, targetType == SELECT_TARGET_MINDISTANCE); - if (targetType == SELECT_TARGET_FARTHEST || targetType == SELECT_TARGET_BOTTOMAGGRO) + // now the list is MAX sorted, reverse for MIN types + if (targetType == SELECT_TARGET_MINTHREAT) targetList.reverse(); + // ignore the first <offset> elements + while (offset) + { + targetList.pop_front(); + --offset; + } + + if (targetList.size() <= num) + return; + if (targetType == SELECT_TARGET_RANDOM) - Trinity::Containers::RandomResize(targetList, maxTargets); + Trinity::Containers::RandomResize(targetList, num); else - targetList.resize(maxTargets); + targetList.resize(num); } // Called at any Damage to any victim (before damage apply) @@ -300,6 +381,7 @@ class TC_GAME_API UnitAI UnitAI& operator=(UnitAI const& right) = delete; ThreatManager& GetThreatManager(); + void SortByDistance(std::list<Unit*> list, bool ascending = true); }; #endif diff --git a/src/server/game/AI/CreatureAI.cpp b/src/server/game/AI/CreatureAI.cpp index 54fbabd0b50..6894f4af091 100644 --- a/src/server/game/AI/CreatureAI.cpp +++ b/src/server/game/AI/CreatureAI.cpp @@ -85,8 +85,8 @@ void CreatureAI::DoZoneInCombat(Creature* creature /*= nullptr*/, float maxRange if (Unit* summoner = creature->ToTempSummon()->GetSummoner()) { Unit* target = summoner->getAttackerForHelper(); - if (!target && summoner->CanHaveThreatList() && !summoner->getThreatManager().isThreatListEmpty()) - target = summoner->getThreatManager().getHostilTarget(); + if (!target && summoner->CanHaveThreatList() && !summoner->GetThreatManager().IsThreatListEmpty()) + target = summoner->GetThreatManager().GetAnyTarget(); if (target && (creature->IsFriendlyTo(summoner) || creature->IsHostileTo(target))) creature->AI()->AttackStart(target); } @@ -117,16 +117,8 @@ void CreatureAI::DoZoneInCombat(Creature* creature /*= nullptr*/, float maxRange { creature->SetInCombatWith(player); player->SetInCombatWith(creature); - creature->AddThreat(player, 0.0f); + creature->GetThreatManager().AddThreat(player, 0.0f, nullptr, true, true); } - - /* Causes certain things to never leave the threat list (Priest Lightwell, etc): - for (Unit::ControlList::const_iterator itr = player->m_Controlled.begin(); itr != player->m_Controlled.end(); ++itr) - { - creature->SetInCombatWith(*itr); - (*itr)->SetInCombatWith(creature); - creature->AddThreat(*itr, 0.0f); - }*/ } } } @@ -144,11 +136,11 @@ void CreatureAI::MoveInLineOfSight_Safe(Unit* who) void CreatureAI::MoveInLineOfSight(Unit* who) { - if (me->GetVictim()) + if (me->IsEngaged()) return; if (me->HasReactState(REACT_AGGRESSIVE) && me->CanStartAttack(who, false)) - AttackStart(who); + me->EngageWithTarget(who); } void CreatureAI::_OnOwnerCombatInteraction(Unit* target) @@ -157,12 +149,7 @@ void CreatureAI::_OnOwnerCombatInteraction(Unit* target) return; if (!me->HasReactState(REACT_PASSIVE) && me->CanStartAttack(target, true)) - { - if (me->IsInCombat()) - me->AddThreat(target, 0.0f); - else - AttackStart(target); - } + me->EngageWithTarget(target); } // Distract creature, if player gets too close while stealthed/prowling @@ -172,8 +159,8 @@ void CreatureAI::TriggerAlert(Unit const* who) const if (!who || who->GetTypeId() != TYPEID_PLAYER) return; - // If this unit isn't an NPC, is already distracted, is in combat, is confused, stunned or fleeing, do nothing - if (me->GetTypeId() != TYPEID_UNIT || me->IsInCombat() || me->HasUnitState(UNIT_STATE_CONFUSED | UNIT_STATE_STUNNED | UNIT_STATE_FLEEING | UNIT_STATE_DISTRACTED)) + // If this unit isn't an NPC, is already distracted, is fighting, is confused, stunned or fleeing, do nothing + if (me->GetTypeId() != TYPEID_UNIT || me->IsEngaged() || me->HasUnitState(UNIT_STATE_CONFUSED | UNIT_STATE_STUNNED | UNIT_STATE_FLEEING | UNIT_STATE_DISTRACTED)) return; // Only alert for hostiles! @@ -230,7 +217,7 @@ void CreatureAI::SetGazeOn(Unit* target) bool CreatureAI::UpdateVictimWithGaze() { - if (!me->IsInCombat()) + if (!me->IsEngaged()) return false; if (me->HasReactState(REACT_PASSIVE)) @@ -250,7 +237,7 @@ bool CreatureAI::UpdateVictimWithGaze() bool CreatureAI::UpdateVictim() { - if (!me->IsInCombat()) + if (!me->IsEngaged()) return false; if (!me->HasReactState(REACT_PASSIVE)) @@ -261,7 +248,7 @@ bool CreatureAI::UpdateVictim() return me->GetVictim() != nullptr; } - else if (me->getThreatManager().isThreatListEmpty()) + else if (me->GetThreatManager().IsThreatListEmpty()) { EnterEvadeMode(EVADE_REASON_NO_HOSTILES); return false; @@ -278,7 +265,7 @@ bool CreatureAI::_EnterEvadeMode(EvadeReason /*why*/) me->RemoveAurasOnEvade(); // sometimes bosses stuck in combat? - me->DeleteThreatList(); + me->GetThreatManager().ClearAllThreat(); me->CombatStop(true); me->SetLootRecipient(nullptr); me->ResetPlayerDamageReq(); diff --git a/src/server/game/AI/CreatureAI.h b/src/server/game/AI/CreatureAI.h index 754e936862d..76eec1909d8 100644 --- a/src/server/game/AI/CreatureAI.h +++ b/src/server/game/AI/CreatureAI.h @@ -85,7 +85,7 @@ class TC_GAME_API CreatureAI : public UnitAI // Called for reaction at stopping attack at no attackers or targets virtual void EnterEvadeMode(EvadeReason why = EVADE_REASON_OTHER); - // Called for reaction at enter to combat if not in combat yet (enemy can be nullptr) + // Called for reaction when initially engaged virtual void EnterCombat(Unit* /*victim*/) { } // Called when the creature is killed diff --git a/src/server/game/AI/PlayerAI/PlayerAI.cpp b/src/server/game/AI/PlayerAI/PlayerAI.cpp index 6d5b7060099..0f99211a84b 100644 --- a/src/server/game/AI/PlayerAI/PlayerAI.cpp +++ b/src/server/game/AI/PlayerAI/PlayerAI.cpp @@ -1216,7 +1216,7 @@ void SimpleCharmedPlayerAI::UpdateAI(const uint32 diff) } } - if (charmer->IsInCombat()) + if (charmer->IsEngaged()) { Unit* target = me->GetVictim(); if (!target || !charmer->IsValidAttackTarget(target) || target->HasBreakableByDamageCrowdControlAura()) diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp index bde3a192642..ff1e5591fb8 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp @@ -193,6 +193,49 @@ void ScriptedAI::DoPlaySoundToSet(WorldObject* source, uint32 soundId) source->PlayDirectSound(soundId); } +void ScriptedAI::AddThreat(Unit* victim, float amount, Unit* who) +{ + if (!victim) + return; + if (!who) + who = me; + who->GetThreatManager().AddThreat(victim, amount, nullptr, true, true); +} + +void ScriptedAI::ModifyThreatByPercent(Unit* victim, int32 pct, Unit* who) +{ + if (!victim) + return; + if (!who) + who = me; + who->GetThreatManager().ModifyThreatByPercent(victim, pct); +} + +void ScriptedAI::ResetThreat(Unit* victim, Unit* who) +{ + if (!victim) + return; + if (!who) + who = me; + who->GetThreatManager().ResetThreat(victim); +} + +void ScriptedAI::ResetThreatList(Unit* who) +{ + if (!who) + who = me; + who->GetThreatManager().ResetAllThreat(); +} + +float ScriptedAI::GetThreat(Unit const* victim, Unit const* who) +{ + if (!victim) + return 0.0f; + if (!who) + who = me; + return who->GetThreatManager().GetThreat(victim); +} + Creature* ScriptedAI::DoSpawnCreature(uint32 entry, float offsetX, float offsetY, float offsetZ, float angle, uint32 type, uint32 despawntime) { return me->SummonCreature(entry, me->GetPositionX() + offsetX, me->GetPositionY() + offsetY, me->GetPositionZ() + offsetZ, angle, TempSummonType(type), despawntime); @@ -276,38 +319,6 @@ SpellInfo const* ScriptedAI::SelectSpell(Unit* target, uint32 school, uint32 mec return apSpell[urand(0, spellCount - 1)]; } -void ScriptedAI::DoResetThreat() -{ - if (!me->CanHaveThreatList() || me->getThreatManager().isThreatListEmpty()) - { - TC_LOG_ERROR("scripts", "DoResetThreat called for creature that either cannot have threat list or has empty threat list (me entry = %d)", me->GetEntry()); - return; - } - - ThreatContainer::StorageType threatlist = me->getThreatManager().getThreatList(); - - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - { - Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid()); - if (unit && DoGetThreat(unit)) - DoModifyThreatPercent(unit, -100); - } -} - -float ScriptedAI::DoGetThreat(Unit* unit) -{ - if (!unit) - return 0.0f; - return me->getThreatManager().getThreat(unit); -} - -void ScriptedAI::DoModifyThreatPercent(Unit* unit, int32 pct) -{ - if (!unit) - return; - me->getThreatManager().modifyThreatPercent(unit, pct); -} - void ScriptedAI::DoTeleportTo(float x, float y, float z, uint32 time) { me->Relocate(x, y, z); @@ -493,7 +504,7 @@ void BossAI::TeleportCheaters() float x, y, z; me->GetPosition(x, y, z); - ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType threatList = me->GetThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr) if (Unit* target = (*itr)->getTarget()) if (target->GetTypeId() == TYPEID_PLAYER && !CheckBoundary(target)) @@ -503,7 +514,7 @@ void BossAI::TeleportCheaters() void BossAI::JustSummoned(Creature* summon) { summons.Summon(summon); - if (me->IsInCombat()) + if (me->IsEngaged()) DoZoneInCombat(summon); } diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.h b/src/server/game/AI/ScriptedAI/ScriptedCreature.h index bb61dfbaab0..084f05552c4 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.h +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.h @@ -208,11 +208,16 @@ struct TC_GAME_API ScriptedAI : public CreatureAI //Plays a sound to all nearby players void DoPlaySoundToSet(WorldObject* source, uint32 soundId); - //Drops all threat to 0%. Does not remove players from the threat list - void DoResetThreat(); - - float DoGetThreat(Unit* unit); - void DoModifyThreatPercent(Unit* unit, int32 pct); + // Add specified amount of threat directly to victim (ignores redirection effects) - also puts victim in combat and engages them if necessary + void AddThreat(Unit* victim, float amount, Unit* who = nullptr); + // Adds/removes the specified percentage from the specified victim's threat (to who, or me if not specified) + void ModifyThreatByPercent(Unit* victim, int32 pct, Unit* who = nullptr); + // Resets the victim's threat level to who (or me if not specified) to zero + void ResetThreat(Unit* victim, Unit* who = nullptr); + // Resets the specified unit's threat list (me if not specified) - does not delete entries, just sets their threat to zero + void ResetThreatList(Unit* who = nullptr); + // Returns the threat level of victim towards who (or me if not specified) + float GetThreat(Unit const* victim, Unit const* who = nullptr); void DoTeleportTo(float x, float y, float z, uint32 time = 0); void DoTeleportTo(float const pos[4]); diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp index 46e4159bb4c..8f06a5df423 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp @@ -102,8 +102,7 @@ bool npc_escortAI::AssistPlayerInCombatAgainst(Unit* who) } else { - who->SetInCombatWith(me); - me->AddThreat(who, 0.0f); + me->EngageWithTarget(who); return true; } } @@ -125,24 +124,7 @@ void npc_escortAI::MoveInLineOfSight(Unit* who) { float fAttackRadius = me->GetAttackDistance(who); if (me->IsWithinDistInMap(who, fAttackRadius) && me->IsWithinLOSInMap(who)) - { - if (!me->GetVictim()) - { - // Clear distracted state on combat - if (me->HasUnitState(UNIT_STATE_DISTRACTED)) - { - me->ClearUnitState(UNIT_STATE_DISTRACTED); - me->GetMotionMaster()->Clear(); - } - - AttackStart(who); - } - else if (me->GetMap()->IsDungeon()) - { - who->SetInCombatWith(me); - me->AddThreat(who, 0.0f); - } - } + me->EngageWithTarget(who); } } } @@ -192,7 +174,7 @@ void npc_escortAI::ReturnToLastPoint() void npc_escortAI::EnterEvadeMode(EvadeReason /*why*/) { me->RemoveAllAuras(); - me->DeleteThreatList(); + me->GetThreatManager().ClearAllThreat(); me->CombatStop(true); me->SetLootRecipient(NULL); diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp index 6c38e34df97..04cd868b1da 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp @@ -51,9 +51,7 @@ void FollowerAI::AttackStart(Unit* who) if (me->Attack(who, true)) { - me->AddThreat(who, 0.0f); - me->SetInCombatWith(who); - who->SetInCombatWith(me); + me->EngageWithTarget(who); // in case it doesn't have threat+combat yet if (me->HasUnitState(UNIT_STATE_FOLLOW)) me->ClearUnitState(UNIT_STATE_FOLLOW); @@ -86,18 +84,8 @@ bool FollowerAI::AssistPlayerInCombatAgainst(Unit* who) //too far away and no free sight? if (me->IsWithinDistInMap(who, MAX_PLAYER_DISTANCE) && me->IsWithinLOSInMap(who)) { - //already fighting someone? - if (!me->GetVictim()) - { - AttackStart(who); - return true; - } - else - { - who->SetInCombatWith(me); - me->AddThreat(who, 0.0f); - return true; - } + me->EngageWithTarget(who); + return true; } return false; @@ -130,10 +118,7 @@ void FollowerAI::MoveInLineOfSight(Unit* who) AttackStart(who); } else if (me->GetMap()->IsDungeon()) - { - who->SetInCombatWith(me); - me->AddThreat(who, 0.0f); - } + me->EngageWithTarget(who); } } } @@ -175,7 +160,7 @@ void FollowerAI::JustRespawned() void FollowerAI::EnterEvadeMode(EvadeReason /*why*/) { me->RemoveAllAuras(); - me->DeleteThreatList(); + me->GetThreatManager().ClearAllThreat(); me->CombatStop(true); me->SetLootRecipient(NULL); diff --git a/src/server/game/AI/SmartScripts/SmartAI.cpp b/src/server/game/AI/SmartScripts/SmartAI.cpp index fb596a054da..eb6e4e65e14 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.cpp +++ b/src/server/game/AI/SmartScripts/SmartAI.cpp @@ -558,18 +558,8 @@ bool SmartAI::AssistPlayerInCombatAgainst(Unit* who) //too far away and no free sight? if (me->IsWithinDistInMap(who, SMART_MAX_AID_DIST) && me->IsWithinLOSInMap(who)) { - //already fighting someone? - if (!me->GetVictim()) - { - AttackStart(who); - return true; - } - else - { - who->SetInCombatWith(me); - me->AddThreat(who, 0.0f); - return true; - } + me->EngageWithTarget(who); + return true; } return false; diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index a701fd98369..2968ef7b108 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -445,16 +445,11 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!me) break; - ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); - for (auto i = threatList.begin(); i != threatList.end(); ++i) + for (auto* ref : me->GetThreatManager().GetUnsortedThreatList()) { - if (Unit* target = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid())) - { - me->getThreatManager().modifyThreatPercent(target, e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_THREAT_ALL_PCT: Creature %s modify threat for %s, value %i", - me->GetGUID().ToString().c_str(), target->GetGUID().ToString().c_str(), - e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); - } + ref->ModifyThreatByPercent(std::max<int32>(-100,int32(e.action.threatPCT.threatINC) - int32(e.action.threatPCT.threatDEC))); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_THREAT_ALL_PCT: Creature %s modify threat for %s, value %i", + me->GetGUID().ToString().c_str(), ref->GetVictim()->GetGUID().ToString().c_str(), int32(e.action.threatPCT.threatINC)-int32(e.action.threatPCT.threatDEC)); } break; } @@ -467,10 +462,9 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u { if (IsUnit(target)) { - me->getThreatManager().modifyThreatPercent(target->ToUnit(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); + me->GetThreatManager().ModifyThreatByPercent(target->ToUnit(), std::max<int32>(-100, int32(e.action.threatPCT.threatINC) - int32(e.action.threatPCT.threatDEC))); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_THREAT_SINGLE_PCT: Creature %s modify threat for %s, value %i", - me->GetGUID().ToString().c_str(), target->GetGUID().ToString().c_str(), - e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); + me->GetGUID().ToString().c_str(), target->GetGUID().ToString().c_str(), int32(e.action.threatPCT.threatINC) - int32(e.action.threatPCT.threatDEC)); } } break; @@ -2148,7 +2142,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u { for (WorldObject* const target : targets) if (IsUnit(target)) - me->AddThreat(target->ToUnit(), float(e.action.threatPCT.threatINC) - float(e.action.threatPCT.threatDEC)); + me->GetThreatManager().AddThreat(target->ToUnit(), float(e.action.threatPCT.threatINC) - float(e.action.threatPCT.threatDEC), nullptr, true, true); break; } case SMART_ACTION_LOAD_EQUIPMENT: @@ -2421,10 +2415,10 @@ void SmartScript::GetTargets(ObjectVector& targets, SmartScriptHolder const& e, { if (e.target.hostilRandom.powerType) { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0))) + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_MAXTHREAT, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0))) targets.push_back(u); } - else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0)) + else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_MAXTHREAT, 1, float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0)) targets.push_back(u); } break; @@ -2433,10 +2427,10 @@ void SmartScript::GetTargets(ObjectVector& targets, SmartScriptHolder const& e, { if (e.target.hostilRandom.powerType) { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0))) + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_MINTHREAT, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0))) targets.push_back(u); } - else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0)) + else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_MINTHREAT, 0, float(e.target.hostilRandom.maxDist), e.target.hostilRandom.playerOnly != 0)) targets.push_back(u); } break; @@ -2467,7 +2461,7 @@ void SmartScript::GetTargets(ObjectVector& targets, SmartScriptHolder const& e, case SMART_TARGET_FARTHEST: if (me) { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_FARTHEST, 0, FarthestTargetSelector(me, float(e.target.farthest.maxDist), e.target.farthest.playerOnly != 0, e.target.farthest.isInLos != 0))) + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_MAXDISTANCE, 0, FarthestTargetSelector(me, float(e.target.farthest.maxDist), e.target.farthest.playerOnly != 0, e.target.farthest.isInLos != 0))) targets.push_back(u); } break; @@ -2684,14 +2678,10 @@ void SmartScript::GetTargets(ObjectVector& targets, SmartScriptHolder const& e, } case SMART_TARGET_THREAT_LIST: { - if (me) - { - ThreatContainer::StorageType const& threatList = me->getThreatManager().getThreatList(); - for (HostileReference const* ref : threatList) - if (Unit* temp = ObjectAccessor::GetUnit(*me, ref->getUnitGuid())) - if (e.target.hostilRandom.maxDist == 0 || me->IsWithinCombatRange(temp, float(e.target.hostilRandom.maxDist))) - targets.push_back(temp); - } + if (me && me->CanHaveThreatList()) + for (auto* ref : me->GetThreatManager().GetUnsortedThreatList()) + if (!e.target.hostilRandom.maxDist || me->IsWithinCombatRange(ref->GetVictim(), float(e.target.hostilRandom.maxDist))) + targets.push_back(ref->GetVictim()); break; } case SMART_TARGET_CLOSEST_ENEMY: @@ -2775,18 +2765,18 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); break; case SMART_EVENT_UPDATE_OOC: - if (me && me->IsInCombat()) + if (me && me->IsEngaged()) return; ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); break; case SMART_EVENT_UPDATE_IC: - if (!me || !me->IsInCombat()) + if (!me || !me->IsEngaged()) return; ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); break; case SMART_EVENT_HEALT_PCT: { - if (!me || !me->IsInCombat() || !me->GetMaxHealth()) + if (!me || !me->IsEngaged() || !me->GetMaxHealth()) return; uint32 perc = (uint32)me->GetHealthPct(); if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) @@ -2796,7 +2786,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_TARGET_HEALTH_PCT: { - if (!me || !me->IsInCombat() || !me->GetVictim() || !me->EnsureVictim()->GetMaxHealth()) + if (!me || !me->IsEngaged() || !me->GetVictim() || !me->EnsureVictim()->GetMaxHealth()) return; uint32 perc = (uint32)me->EnsureVictim()->GetHealthPct(); if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) @@ -2806,7 +2796,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_MANA_PCT: { - if (!me || !me->IsInCombat() || !me->GetMaxPower(POWER_MANA)) + if (!me || !me->IsEngaged() || !me->GetMaxPower(POWER_MANA)) return; uint32 perc = uint32(me->GetPowerPct(POWER_MANA)); if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) @@ -2816,7 +2806,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_TARGET_MANA_PCT: { - if (!me || !me->IsInCombat() || !me->GetVictim() || !me->EnsureVictim()->GetMaxPower(POWER_MANA)) + if (!me || !me->IsEngaged() || !me->GetVictim() || !me->EnsureVictim()->GetMaxPower(POWER_MANA)) return; uint32 perc = uint32(me->EnsureVictim()->GetPowerPct(POWER_MANA)); if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) @@ -2826,7 +2816,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_RANGE: { - if (!me || !me->IsInCombat() || !me->GetVictim()) + if (!me || !me->IsEngaged() || !me->GetVictim()) return; if (me->IsInRange(me->GetVictim(), (float)e.event.minMaxRepeat.min, (float)e.event.minMaxRepeat.max)) @@ -2837,7 +2827,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_VICTIM_CASTING: { - if (!me || !me->IsInCombat()) + if (!me || !me->IsEngaged()) return; Unit* victim = me->GetVictim(); @@ -2855,7 +2845,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_FRIENDLY_HEALTH: { - if (!me || !me->IsInCombat()) + if (!me || !me->IsEngaged()) return; Unit* target = DoSelectLowestHpFriendly((float)e.event.friendlyHealth.radius, e.event.friendlyHealth.hpDeficit); @@ -2871,7 +2861,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_FRIENDLY_IS_CC: { - if (!me || !me->IsInCombat()) + if (!me || !me->IsEngaged()) return; std::vector<Creature*> creatures; @@ -2994,7 +2984,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_OOC_LOS: { - if (!me || me->IsInCombat()) + if (!me || me->IsEngaged()) return; //can trigger if closer than fMaxAllowedRange float range = (float)e.event.los.maxDist; @@ -3014,7 +3004,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_IC_LOS: { - if (!me || !me->IsInCombat()) + if (!me || !me->IsEngaged()) return; //can trigger if closer than fMaxAllowedRange float range = (float)e.event.los.maxDist; @@ -3204,7 +3194,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_FRIENDLY_HEALTH_PCT: { - if (!me || !me->IsInCombat()) + if (!me || !me->IsEngaged()) return; ObjectVector targets; @@ -3364,10 +3354,10 @@ void SmartScript::UpdateTimer(SmartScriptHolder& e, uint32 const diff) if (e.event.event_phase_mask && !IsInPhase(e.event.event_phase_mask)) return; - if (e.GetEventType() == SMART_EVENT_UPDATE_IC && (!me || !me->IsInCombat())) + if (e.GetEventType() == SMART_EVENT_UPDATE_IC && (!me || !me->IsEngaged())) return; - if (e.GetEventType() == SMART_EVENT_UPDATE_OOC && (me && me->IsInCombat())) //can be used with me=nullptr (go script) + if (e.GetEventType() == SMART_EVENT_UPDATE_OOC && (me && me->IsEngaged())) //can be used with me=nullptr (go script) return; if (e.timer < diff) @@ -3719,7 +3709,7 @@ void SmartScript::OnMoveInLineOfSight(Unit* who) if (!me) return; - ProcessEventsFor(me->IsInCombat() ? SMART_EVENT_IC_LOS : SMART_EVENT_OOC_LOS, who); + ProcessEventsFor(me->IsEngaged() ? SMART_EVENT_IC_LOS : SMART_EVENT_OOC_LOS, who); } // SmartScript end diff --git a/src/server/game/Combat/ThreatManager.cpp b/src/server/game/Combat/ThreatManager.cpp index f7240308aef..f655f2bfa86 100644 --- a/src/server/game/Combat/ThreatManager.cpp +++ b/src/server/game/Combat/ThreatManager.cpp @@ -131,6 +131,9 @@ void HostileReference::fireStatusChanged(ThreatRefStatusChangeEvent& threatRefSt GetSource()->processThreatEvent(&threatRefStatusChangeEvent); } +// -- compatibility layer for combat rewrite (PR #19930) +Unit* HostileReference::GetOwner() const { return GetSource()->GetOwner(); } + //============================================================ void HostileReference::addThreat(float modThreat) @@ -264,7 +267,7 @@ void ThreatContainer::clearReferences() //============================================================ // Return the HostileReference of NULL, if not found -HostileReference* ThreatContainer::getReferenceByTarget(Unit* victim) const +HostileReference* ThreatContainer::getReferenceByTarget(Unit const* victim) const { if (!victim) return NULL; @@ -293,7 +296,7 @@ HostileReference* ThreatContainer::addThreat(Unit* victim, float threat) //============================================================ -void ThreatContainer::modifyThreatPercent(Unit* victim, int32 percent) +void ThreatContainer::ModifyThreatByPercent(Unit* victim, int32 percent) { if (HostileReference* ref = getReferenceByTarget(victim)) ref->addThreatPercent(percent); @@ -392,6 +395,30 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileR ThreatManager::ThreatManager(Unit* owner) : iCurrentVictim(NULL), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL) { } +// -- compatibility layer for combat rewrite (PR #19930) +void ThreatManager::ForwardThreatForAssistingMe(Unit* victim, float amount, SpellInfo const* spell, bool ignoreModifiers, bool ignoreRedirection) +{ + (void)ignoreModifiers; (void)ignoreRedirection; + GetOwner()->getHostileRefManager().threatAssist(victim, amount, spell); +} + +void ThreatManager::AddThreat(Unit* victim, float amount, SpellInfo const* spell, bool ignoreModifiers, bool ignoreRedirection) +{ + (void)ignoreModifiers; (void)ignoreRedirection; + if (!iOwner->CanHaveThreatList() || iOwner->HasUnitState(UNIT_STATE_EVADE)) + return; + iOwner->SetInCombatWith(victim); + victim->SetInCombatWith(iOwner); + addThreat(victim, amount, spell ? spell->GetSchoolMask() : victim->GetMeleeDamageSchoolMask(), spell); +} + +void ThreatManager::ClearAllThreat() +{ + if (iOwner->CanHaveThreatList(true) && !isThreatListEmpty()) + iOwner->SendClearThreatListOpcode(); + clearReferences(); +} + //============================================================ void ThreatManager::clearReferences() @@ -471,9 +498,9 @@ void ThreatManager::_addThreat(Unit* victim, float threat) //============================================================ -void ThreatManager::modifyThreatPercent(Unit* victim, int32 percent) +void ThreatManager::ModifyThreatByPercent(Unit* victim, int32 percent) { - iThreatContainer.modifyThreatPercent(victim, percent); + iThreatContainer.ModifyThreatByPercent(victim, percent); } //============================================================ diff --git a/src/server/game/Combat/ThreatManager.h b/src/server/game/Combat/ThreatManager.h index 118fbd2a328..1b9a4c9c8eb 100644 --- a/src/server/game/Combat/ThreatManager.h +++ b/src/server/game/Combat/ThreatManager.h @@ -23,6 +23,7 @@ #include "LinkedReference/Reference.h" #include "UnitEvents.h" #include "ObjectGuid.h" +#include "IteratorPair.h" #include <list> @@ -50,6 +51,19 @@ class TC_GAME_API HostileReference : public Reference<Unit, ThreatManager> public: HostileReference(Unit* refUnit, ThreatManager* threatManager, float threat); + // -- compatibility layer for combat rewrite (PR #19930) + Unit* GetOwner() const; + Unit* GetVictim() const { return getTarget(); } + void AddThreat(float amt) { addThreat(amt); } + void SetThreat(float amt) { setThreat(amt); } + void ModifyThreatByPercent(int32 pct) { addThreatPercent(pct); } + void ScaleThreat(float factor) { setThreat(iThreat*factor); } + bool IsOnline() const { return iOnline; } + bool IsAvailable() const { return iOnline; } + bool IsOffline() const { return !iOnline; } + float GetThreat() const { return getThreat(); } + void ClearThreat() { removeReference(); } + //================================================= void addThreat(float modThreat); @@ -156,7 +170,7 @@ class TC_GAME_API ThreatContainer HostileReference* addThreat(Unit* victim, float threat); - void modifyThreatPercent(Unit* victim, int32 percent); + void ModifyThreatByPercent(Unit* victim, int32 percent); HostileReference* selectNextVictim(Creature* attacker, HostileReference* currentVictim) const; @@ -174,7 +188,7 @@ class TC_GAME_API ThreatContainer return iThreatList.empty() ? nullptr : iThreatList.front(); } - HostileReference* getReferenceByTarget(Unit* victim) const; + HostileReference* getReferenceByTarget(Unit const* victim) const; StorageType const & getThreatList() const { return iThreatList; } @@ -200,9 +214,31 @@ class TC_GAME_API ThreatContainer //================================================= +typedef HostileReference ThreatReference; class TC_GAME_API ThreatManager { public: + // -- compatibility layer for combat rewrite (PR #19930) + Trinity::IteratorPair<std::list<ThreatReference*>::const_iterator> GetSortedThreatList() const { auto& list = iThreatContainer.getThreatList(); return { list.cbegin(), list.cend() }; } + Trinity::IteratorPair<std::list<ThreatReference*>::const_iterator> GetUnsortedThreatList() const { return GetSortedThreatList(); } + Unit* SelectVictim() { return getHostilTarget(); } + Unit* GetCurrentVictim() const { if (ThreatReference* ref = getCurrentVictim()) return ref->GetVictim(); else return nullptr; } + bool IsThreatListEmpty(bool includeOffline = false) const { return includeOffline ? areThreatListsEmpty() : isThreatListEmpty(); } + bool IsThreatenedBy(Unit const* who, bool includeOffline = false) const { return (FindReference(who, includeOffline) != nullptr); } + size_t GetThreatListSize() const { return iThreatContainer.iThreatList.size(); } + void ForwardThreatForAssistingMe(Unit* victim, float amount, SpellInfo const* spell, bool ignoreModifiers = false, bool ignoreRedirection = false); + Unit* GetAnyTarget() const { auto const& list = getThreatList(); if (!list.empty()) return list.front()->getTarget(); return nullptr; } + void ResetThreat(Unit const* who) { if (auto* ref = FindReference(who, true)) ref->setThreat(0.0f); } + void ResetAllThreat() { resetAllAggro(); } + float GetThreat(Unit const* who, bool includeOffline = false) const { if (auto* ref = FindReference(who, includeOffline)) return ref->GetThreat(); return 0.0f; } + void ClearThreat(Unit const* who) { if (auto* ref = FindReference(who, true)) ref->removeReference(); } + void ClearAllThreat(); + void AddThreat(Unit* victim, float amount, SpellInfo const* spell = nullptr, bool ignoreModifiers = false, bool ignoreRedirection = false); + private: + HostileReference* FindReference(Unit const* who, bool includeOffline) const { if (auto* ref = iThreatContainer.getReferenceByTarget(who)) return ref; if (includeOffline) if (auto* ref = iThreatOfflineContainer.getReferenceByTarget(who)) return ref; return nullptr; } + + public: + friend class HostileReference; explicit ThreatManager(Unit* owner); @@ -215,7 +251,7 @@ class TC_GAME_API ThreatManager void doAddThreat(Unit* victim, float threat); - void modifyThreatPercent(Unit* victim, int32 percent); + void ModifyThreatByPercent(Unit* victim, int32 percent); float getThreat(Unit* victim, bool alsoSearchOfflineList = false); diff --git a/src/server/game/Combat/UnitEvents.h b/src/server/game/Combat/UnitEvents.h index c845981a0c0..fec0f089ac7 100644 --- a/src/server/game/Combat/UnitEvents.h +++ b/src/server/game/Combat/UnitEvents.h @@ -115,7 +115,7 @@ class TC_GAME_API ThreatRefStatusChangeEvent : public UnitBaseEvent void setThreatManager(ThreatManager* pThreatManager) { iThreatManager = pThreatManager; } - ThreatManager* getThreatManager() const { return iThreatManager; } + ThreatManager* GetThreatManager() const { return iThreatManager; } }; #endif diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 986932856c0..f6d3137f51b 100644 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -263,9 +263,7 @@ bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) if (assistant && assistant->CanAssistTo(&m_owner, victim)) { assistant->SetNoCallAssistance(true); - assistant->CombatStart(victim); - if (assistant->IsAIEnabled) - assistant->AI()->AttackStart(victim); + assistant->EngageWithTarget(victim); } } } @@ -739,7 +737,7 @@ void Creature::Update(uint32 diff) } // periodic check to see if the creature has passed an evade boundary - if (IsAIEnabled && !IsInEvadeMode() && IsInCombat()) + if (IsAIEnabled && !IsInEvadeMode() && IsEngaged()) { if (diff >= m_boundaryCheckTime) { @@ -750,7 +748,7 @@ void Creature::Update(uint32 diff) } // if periodic combat pulse is enabled and we are both in combat and in a dungeon, do this now - if (m_combatPulseDelay > 0 && IsInCombat() && GetMap()->IsDungeon()) + if (m_combatPulseDelay > 0 && IsEngaged() && GetMap()->IsDungeon()) { if (diff > m_combatPulseTime) m_combatPulseTime = 0; @@ -768,13 +766,8 @@ void Creature::Update(uint32 diff) if (player->IsGameMaster()) continue; - if (player->IsAlive() && this->IsHostileTo(player)) - { - if (CanHaveThreatList()) - AddThreat(player, 0.0f); - this->SetInCombatWith(player); - player->SetInCombatWith(this); - } + if (player->IsAlive() && IsHostileTo(player)) + EngageWithTarget(player); } } @@ -1817,7 +1810,7 @@ bool Creature::CanStartAttack(Unit const* who, bool force) const if (!_IsTargetAcceptable(who)) return false; - if (who->IsInCombat() && IsWithinDist(who, ATTACK_DISTANCE)) + if (who->IsEngaged() && IsWithinDist(who, ATTACK_DISTANCE)) if (Unit* victim = who->getAttackerForHelper()) if (IsWithinDistInMap(victim, sWorld->getFloatConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS))) force = true; @@ -2375,7 +2368,7 @@ bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction / return false; // skip fighting creature - if (IsInCombat()) + if (IsEngaged()) return false; // only free creature @@ -2425,7 +2418,7 @@ bool Creature::_IsTargetAcceptable(Unit const* target) const Unit const* targetVictim = target->getAttackerForHelper(); // if I'm already fighting target, or I'm hostile towards the target, the target is acceptable - if (IsInCombatWith(target) || IsHostileTo(target)) + if (IsEngagedBy(target) || IsHostileTo(target)) return true; // if the target's victim is friendly, and the target is neutral, the target is acceptable @@ -2626,11 +2619,7 @@ void Creature::SetInCombatWithZone() continue; if (player->IsAlive()) - { - this->SetInCombatWith(player); - player->SetInCombatWith(this); - AddThreat(player, 0.0f); - } + EngageWithTarget(player); } } } diff --git a/src/server/game/Entities/Creature/CreatureGroups.cpp b/src/server/game/Entities/Creature/CreatureGroups.cpp index 07547ae9139..1dd2fcfeae3 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.cpp +++ b/src/server/game/Entities/Creature/CreatureGroups.cpp @@ -172,7 +172,7 @@ void CreatureGroup::RemoveMember(Creature* member) member->SetFormation(NULL); } -void CreatureGroup::MemberAttackStart(Creature* member, Unit* target) +void CreatureGroup::MemberEngagingTarget(Creature* member, Unit* target) { uint8 groupAI = sFormationMgr->CreatureGroupMap[member->GetSpawnId()]->groupAI; if (!groupAI) @@ -188,11 +188,7 @@ void CreatureGroup::MemberAttackStart(Creature* member, Unit* target) for (CreatureGroupMemberType::iterator itr = m_members.begin(); itr != m_members.end(); ++itr) { - if (m_leader) // avoid crash if leader was killed and reset. - TC_LOG_DEBUG("entities.unit", "GROUP ATTACK: group instance id %u calls member instid %u", m_leader->GetInstanceId(), member->GetInstanceId()); - Creature* other = itr->first; - // Skip self if (other == member) continue; @@ -200,11 +196,8 @@ void CreatureGroup::MemberAttackStart(Creature* member, Unit* target) if (!other->IsAlive()) continue; - if (other->GetVictim()) - continue; - if (((other != m_leader && (groupAI & FLAG_MEMBERS_ASSIST_LEADER)) || (other == m_leader && (groupAI & FLAG_LEADER_ASSISTS_MEMBER))) && other->IsValidAttackTarget(target)) - other->AI()->AttackStart(target); + other->EngageWithTarget(target); } } diff --git a/src/server/game/Entities/Creature/CreatureGroups.h b/src/server/game/Entities/Creature/CreatureGroups.h index 85eb7454432..ebab74504c3 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.h +++ b/src/server/game/Entities/Creature/CreatureGroups.h @@ -89,7 +89,7 @@ class TC_GAME_API CreatureGroup void FormationReset(bool dismiss); void LeaderMoveTo(Position destination, uint32 id = 0, uint32 moveType = 0, bool orientation = false); - void MemberAttackStart(Creature* member, Unit* target); + void MemberEngagingTarget(Creature* member, Unit* target); }; #define sFormationMgr FormationMgr::instance() diff --git a/src/server/game/Entities/Object/Object.cpp b/src/server/game/Entities/Object/Object.cpp index 4321a39f172..7d06755b363 100644 --- a/src/server/game/Entities/Object/Object.cpp +++ b/src/server/game/Entities/Object/Object.cpp @@ -844,7 +844,7 @@ void MovementInfo::OutDebug() WorldObject::WorldObject(bool isWorldObject) : WorldLocation(), LastUsedScriptID(0), m_name(""), m_isActive(false), m_isWorldObject(isWorldObject), m_zoneScript(NULL), m_transport(NULL), m_zoneId(0), m_areaId(0), m_staticFloorZ(VMAP_INVALID_HEIGHT), m_currMap(NULL), m_InstanceId(0), -_dbPhase(0), m_notifyflags(0), m_executed_notifies(0) +_dbPhase(0), m_notifyflags(0) { m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE | GHOST_VISIBILITY_GHOST); m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); diff --git a/src/server/game/Entities/Object/Object.h b/src/server/game/Entities/Object/Object.h index 8b6f6dc8a5c..e66e14f76fc 100644 --- a/src/server/game/Entities/Object/Object.h +++ b/src/server/game/Entities/Object/Object.h @@ -539,9 +539,7 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation void AddToNotify(uint16 f) { m_notifyflags |= f;} bool isNeedNotify(uint16 f) const { return (m_notifyflags & f) != 0; } uint16 GetNotifyFlags() const { return m_notifyflags; } - bool NotifyExecuted(uint16 f) const { return (m_executed_notifies & f) != 0; } - void SetNotified(uint16 f) { m_executed_notifies |= f;} - void ResetAllNotifies() { m_notifyflags = 0; m_executed_notifies = 0; } + void ResetAllNotifies() { m_notifyflags = 0; } bool isActiveObject() const { return m_isActive; } void setActive(bool isActiveObject); @@ -614,7 +612,6 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation int32 _dbPhase; uint16 m_notifyflags; - uint16 m_executed_notifies; virtual bool _IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D, bool incOwnRadius = true, bool incTargetRadius = true) const; bool CanNeverSee(WorldObject const* obj) const; diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 4d47e9d9ccc..9b12184bd38 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -21591,14 +21591,38 @@ void Player::UpdateAfkReport(time_t currTime) } } +void Player::SetContestedPvP(Player* attackedPlayer) +{ + if (attackedPlayer && (attackedPlayer == this || (duel && duel->opponent == attackedPlayer))) + return; + + SetContestedPvPTimer(30000); + if (!HasUnitState(UNIT_STATE_ATTACK_PLAYER)) + { + AddUnitState(UNIT_STATE_ATTACK_PLAYER); + AddPlayerFlag(PLAYER_FLAGS_CONTESTED_PVP); + // call MoveInLineOfSight for nearby contested guards + Trinity::AIRelocationNotifier notifier(*this); + Cell::VisitWorldObjects(this, notifier, GetVisibilityRange()); + } + for (Unit* unit : m_Controlled) + { + if (!unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER)) + { + unit->AddUnitState(UNIT_STATE_ATTACK_PLAYER); + Trinity::AIRelocationNotifier notifier(*unit); + Cell::VisitWorldObjects(this, notifier, GetVisibilityRange()); + } + } +} + void Player::UpdateContestedPvP(uint32 diff) { - if (!m_contestedPvPTimer||IsInCombat()) + if (!m_contestedPvPTimer || IsInCombat()) return; + if (m_contestedPvPTimer <= diff) - { ResetContestedPvP(); - } else m_contestedPvPTimer -= diff; } diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index 773cae4e538..d88465d9229 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -1703,6 +1703,7 @@ class TC_GAME_API Player : public Unit, public GridObject<Player> void UpdateAfkReport(time_t currTime); void UpdatePvPFlag(time_t currTime); + void SetContestedPvP(Player* attackedPlayer = nullptr); void UpdateContestedPvP(uint32 currTime); void SetContestedPvPTimer(uint32 newTime) {m_contestedPvPTimer = newTime;} void ResetContestedPvP(); diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index 9bdd317e0ea..8f3ca085bfe 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -468,7 +468,7 @@ void Unit::Update(uint32 p_time) // Having this would prevent spells from being proced, so let's crash ASSERT(!m_procDeep); - if (CanHaveThreatList() && getThreatManager().isNeedUpdateToClient(p_time)) + if (CanHaveThreatList() && GetThreatManager().isNeedUpdateToClient(p_time)) SendThreatListUpdate(); // update combat timer only for players and pets (only pets with PetAI) @@ -883,7 +883,7 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam if (damagetype != DOT && damage > 0 && !victim->GetOwnerGUID().IsPlayer() && (!spellProto || !spellProto->HasAura(SPELL_AURA_DAMAGE_SHIELD))) victim->ToCreature()->SetLastDamagedTime(GameTime::GetGameTime() + MAX_AGGRO_RESET_TIME); - victim->AddThreat(this, float(damage), damageSchoolMask, spellProto); + victim->GetThreatManager().AddThreat(this, float(damage), spellProto); } else // victim is a player { @@ -5617,6 +5617,9 @@ void Unit::_removeAttacker(Unit* pAttacker) Unit* Unit::getAttackerForHelper() const // If someone wants to help, who to give them { + if (!IsEngaged()) + return nullptr; + if (Unit* victim = GetVictim()) if ((!IsPet() && !GetPlayerMovingMe()) || IsInCombatWith(victim) || victim->IsInCombatWith(this)) return victim; @@ -5720,14 +5723,14 @@ bool Unit::Attack(Unit* victim, bool meleeAttack) if (creature && !IsPet()) { // should not let player enter combat by right clicking target - doesn't helps - AddThreat(victim, 0.0f); + GetThreatManager().AddThreat(victim, 0.0f); SetInCombatWith(victim); if (victim->GetTypeId() == TYPEID_PLAYER) victim->SetInCombatWith(this); if (Unit* owner = victim->GetOwner()) { - AddThreat(owner, 0.0f); + GetThreatManager().AddThreat(owner, 0.0f); SetInCombatWith(owner); if (owner->GetTypeId() == TYPEID_PLAYER) owner->SetInCombatWith(this); @@ -6636,13 +6639,16 @@ void Unit::SendEnergizeSpellLog(Unit* victim, uint32 spellID, int32 damage, int3 void Unit::EnergizeBySpell(Unit* victim, uint32 spellId, int32 damage, Powers powerType) { + if (SpellInfo const* info = sSpellMgr->GetSpellInfo(spellId, GetMap()->GetDifficultyID())) + EnergizeBySpell(victim, info, damage, powerType); +} + +void Unit::EnergizeBySpell(Unit* victim, SpellInfo const* spellInfo, int32 damage, Powers powerType) +{ int32 gain = victim->ModifyPower(powerType, damage); int32 overEnergize = damage - gain; - - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId, GetMap()->GetDifficultyID()); - victim->getHostileRefManager().threatAssist(this, float(damage) * 0.5f, spellInfo); - - SendEnergizeSpellLog(victim, spellId, damage, overEnergize, powerType); + victim->GetThreatManager().ForwardThreatForAssistingMe(this, float(damage)/2, spellInfo, true); + SendEnergizeSpellLog(victim, spellInfo->Id, damage, overEnergize, powerType); } uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, SpellEffectInfo const* effect, uint32 stack) const @@ -7995,11 +8001,11 @@ void Unit::CombatStart(Unit* target, bool initialAggro) SetInCombatWith(target); target->SetInCombatWith(this); } - Unit* who = target->GetCharmerOrOwnerOrSelf(); - if (who->GetTypeId() == TYPEID_PLAYER) - SetContestedPvP(who->ToPlayer()); Player* me = GetCharmerOrOwnerPlayerOrPlayerItself(); + Unit* who = target->GetCharmerOrOwnerOrSelf(); + if (me && who->GetTypeId() == TYPEID_PLAYER) + me->SetContestedPvP(who->ToPlayer()); if (me && who->IsPvP() && (who->GetTypeId() != TYPEID_PLAYER || !me->duel || me->duel->opponent != who)) @@ -8041,7 +8047,7 @@ void Unit::SetInCombatState(bool PvP, Unit* enemy) creature->AI()->EnterCombat(enemy); if (creature->GetFormation()) - creature->GetFormation()->MemberAttackStart(creature, enemy); + creature->GetFormation()->MemberEngagingTarget(creature, enemy); } if (IsPet()) @@ -8726,7 +8732,7 @@ void Unit::setDeathState(DeathState s) if (s != ALIVE && s != JUST_RESPAWNED) { CombatStop(); - DeleteThreatList(); + GetThreatManager().ClearAllThreat(); getHostileRefManager().deleteReferences(); if (IsNonMeleeSpellCast(false)) @@ -8795,7 +8801,7 @@ bool Unit::CanHaveThreatList(bool skipAliveCheck) const // return false; // summons can not have a threat list, unless they are controlled by a creature - if (HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN) && ((Pet*)this)->GetOwnerGUID().IsPlayer()) + if (HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN) && GetOwnerGUID().IsPlayer()) return false; return true; @@ -8815,24 +8821,6 @@ float Unit::ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask) //====================================================================== -void Unit::AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask, SpellInfo const* threatSpell) -{ - // Only mobs can manage threat lists - if (CanHaveThreatList() && !HasUnitState(UNIT_STATE_EVADE)) - m_ThreatManager.addThreat(victim, fThreat, schoolMask, threatSpell); -} - -//====================================================================== - -void Unit::DeleteThreatList() -{ - if (CanHaveThreatList(true) && !m_ThreatManager.isThreatListEmpty()) - SendClearThreatListOpcode(); - m_ThreatManager.clearReferences(); -} - -//====================================================================== - void Unit::TauntApply(Unit* taunter) { ASSERT(GetTypeId() == TYPEID_UNIT); @@ -9987,7 +9975,7 @@ void Unit::CleanupBeforeRemoveFromMap(bool finalCleanup) m_Events.KillAllEvents(false); // non-delatable (currently cast spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList CombatStop(); - DeleteThreatList(); + GetThreatManager().ClearAllThreat(); getHostileRefManager().deleteReferences(); } @@ -10633,8 +10621,7 @@ Player* Unit::GetSpellModOwner() const if (HasUnitTypeMask(UNIT_MASK_PET | UNIT_MASK_TOTEM | UNIT_MASK_GUARDIAN)) { if (Unit* owner = GetOwner()) - if (Player* player = owner->ToPlayer()) - return player; + return owner->ToPlayer(); } return nullptr; } @@ -11153,29 +11140,6 @@ float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized) const } } -void Unit::SetContestedPvP(Player* attackedPlayer) -{ - Player* player = GetCharmerOrOwnerPlayerOrPlayerItself(); - - if (!player || (attackedPlayer && (attackedPlayer == player || (player->duel && player->duel->opponent == attackedPlayer)))) - return; - - player->SetContestedPvPTimer(30000); - if (!player->HasUnitState(UNIT_STATE_ATTACK_PLAYER)) - { - player->AddUnitState(UNIT_STATE_ATTACK_PLAYER); - player->AddPlayerFlag(PLAYER_FLAGS_CONTESTED_PVP); - // call MoveInLineOfSight for nearby contested guards - UpdateObjectVisibility(); - } - if (!HasUnitState(UNIT_STATE_ATTACK_PLAYER)) - { - AddUnitState(UNIT_STATE_ATTACK_PLAYER); - // call MoveInLineOfSight for nearby contested guards - UpdateObjectVisibility(); - } -} - Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id) { if (GetTypeId() != TYPEID_PLAYER) @@ -11475,7 +11439,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) if (!creature->IsPet()) { - creature->DeleteThreatList(); + creature->GetThreatManager().ClearAllThreat(); // must be after setDeathState which resets dynamic flags if (!creature->loot.isLooted()) @@ -11845,7 +11809,7 @@ bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* au CastStop(); CombatStop(); /// @todo CombatStop(true) may cause crash (interrupt spells) - DeleteThreatList(); + GetThreatManager().ClearAllThreat(); Player* playerCharmer = charmer->ToPlayer(); @@ -11988,7 +11952,7 @@ void Unit::RemoveCharmedBy(Unit* charmer) CastStop(); CombatStop(); /// @todo CombatStop(true) may cause crash (interrupt spells) getHostileRefManager().deleteReferences(); - DeleteThreatList(); + GetThreatManager().ClearAllThreat(); if (_oldFactionId) { @@ -12471,8 +12435,8 @@ void Unit::OnPhaseChange() // modify threat lists for new phasemask if (GetTypeId() != TYPEID_PLAYER) { - std::list<HostileReference*> threatList = getThreatManager().getThreatList(); - std::list<HostileReference*> offlineThreatList = getThreatManager().getOfflineThreatList(); + std::list<HostileReference*> threatList = GetThreatManager().getThreatList(); + std::list<HostileReference*> offlineThreatList = GetThreatManager().getOfflineThreatList(); // merge expects sorted lists threatList.sort(); @@ -13385,11 +13349,11 @@ void Unit::UpdateHeight(float newZ) void Unit::SendThreatListUpdate() { - if (!getThreatManager().isThreatListEmpty()) + if (!GetThreatManager().isThreatListEmpty()) { WorldPackets::Combat::ThreatUpdate packet; packet.UnitGUID = GetGUID(); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = GetThreatManager().getThreatList(); packet.ThreatList.reserve(tlist.size()); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { @@ -13404,12 +13368,12 @@ void Unit::SendThreatListUpdate() void Unit::SendChangeCurrentVictimOpcode(HostileReference* pHostileReference) { - if (!getThreatManager().isThreatListEmpty()) + if (!GetThreatManager().isThreatListEmpty()) { WorldPackets::Combat::HighestThreatUpdate packet; packet.UnitGUID = GetGUID(); packet.HighestThreatGUID = pHostileReference->getUnitGuid(); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = GetThreatManager().getThreatList(); packet.ThreatList.reserve(tlist.size()); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { diff --git a/src/server/game/Entities/Unit/Unit.h b/src/server/game/Entities/Unit/Unit.h index efa33a90cee..65508f9d345 100644 --- a/src/server/game/Entities/Unit/Unit.h +++ b/src/server/game/Entities/Unit/Unit.h @@ -976,8 +976,9 @@ class TC_GAME_API Unit : public WorldObject bool IsWithinCombatRange(const Unit* obj, float dist2compare) const; bool IsWithinMeleeRange(Unit const* obj) const; float GetMeleeRange(Unit const* target) const; + virtual SpellSchoolMask GetMeleeDamageSchoolMask() const; bool IsWithinBoundaryRadius(const Unit* obj) const; - void GetRandomContactPoint(const Unit* target, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const; + void GetRandomContactPoint(Unit const* target, float& x, float& y, float& z, float distance2dMin, float distance2dMax) const; uint32 m_extraAttacks; bool m_canDualWield; @@ -1267,6 +1268,12 @@ class TC_GAME_API Unit : public WorldObject bool IsInFlight() const { return HasUnitState(UNIT_STATE_IN_FLIGHT); } + bool IsEngaged() const { return IsInCombat(); } + bool IsEngagedBy(Unit const* who) const { return IsInCombatWith(who); } + void EngageWithTarget(Unit* who) { SetInCombatWith(who); who->SetInCombatWith(this); GetThreatManager().AddThreat(who, 0.0f); } + bool IsThreatened() const { return CanHaveThreatList() && !GetThreatManager().IsThreatListEmpty(); } + bool IsThreatenedBy(Unit const* who) const { return who && CanHaveThreatList() && GetThreatManager().IsThreatenedBy(who); } + bool IsInCombat() const { return HasUnitFlag(UNIT_FLAG_IN_COMBAT); } bool IsPetInCombat() const { return HasUnitFlag(UNIT_FLAG_PET_IN_COMBAT); } bool IsInCombatWith(Unit const* who) const; @@ -1303,8 +1310,9 @@ class TC_GAME_API Unit : public WorldObject void SendHealSpellLog(HealInfo& healInfo, bool critical = false); int32 HealBySpell(HealInfo& healInfo, bool critical = false); - void SendEnergizeSpellLog(Unit* victim, uint32 spellID, int32 damage, int32 overEnergize, Powers powerType); - void EnergizeBySpell(Unit* victim, uint32 SpellID, int32 Damage, Powers powertype); + void SendEnergizeSpellLog(Unit* victim, uint32 spellId, int32 damage, int32 overEnergize, Powers powerType); + void EnergizeBySpell(Unit* victim, uint32 spellId, int32 damage, Powers powerType); + void EnergizeBySpell(Unit* victim, SpellInfo const* spellInfo, int32 damage, Powers powerType); void CastSpell(SpellCastTargets const& targets, SpellInfo const* spellInfo, CustomSpellValues const* value, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = nullptr, AuraEffect const* triggeredByAura = nullptr, ObjectGuid originalCaster = ObjectGuid::Empty); void CastSpell(Unit* victim, uint32 spellId, bool triggered, Item* castItem = nullptr, AuraEffect const* triggeredByAura = nullptr, ObjectGuid originalCaster = ObjectGuid::Empty); @@ -1761,12 +1769,11 @@ class TC_GAME_API Unit : public WorldObject // Threat related methods bool CanHaveThreatList(bool skipAliveCheck = false) const; - void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = NULL); float ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL); - void DeleteThreatList(); void TauntApply(Unit* victim); void TauntFadeOut(Unit* taunter); - ThreatManager& getThreatManager() { return m_ThreatManager; } + ThreatManager& GetThreatManager() { return m_ThreatManager; } + ThreatManager const& GetThreatManager() const { return m_ThreatManager; } void addHatedBy(HostileReference* pHostileReference) { m_HostileRefManager.insertFirst(pHostileReference); } void removeHatedBy(HostileReference* /*pHostileReference*/) { /* nothing to do yet */ } HostileRefManager& getHostileRefManager() { return m_HostileRefManager; } @@ -2094,8 +2101,6 @@ class TC_GAME_API Unit : public WorldObject CharmInfo* m_charmInfo; SharedVisionList m_sharedVision; - virtual SpellSchoolMask GetMeleeDamageSchoolMask() const; - MotionMaster* i_motionMaster; uint32 m_reactiveTimer[MAX_REACTIVE]; diff --git a/src/server/game/Grids/ObjectGridLoader.cpp b/src/server/game/Grids/ObjectGridLoader.cpp index 92af45e54c5..a64771876d9 100644 --- a/src/server/game/Grids/ObjectGridLoader.cpp +++ b/src/server/game/Grids/ObjectGridLoader.cpp @@ -219,11 +219,10 @@ void ObjectGridStoper::Visit(CreatureMapType &m) { iter->GetSource()->RemoveAllDynObjects(); iter->GetSource()->RemoveAllAreaTriggers(); - - if (iter->GetSource()->IsInCombat() || !iter->GetSource()->getThreatManager().areThreatListsEmpty()) + if (iter->GetSource()->IsInCombat() || !iter->GetSource()->GetThreatManager().areThreatListsEmpty()) { iter->GetSource()->CombatStop(); - iter->GetSource()->DeleteThreatList(); + iter->GetSource()->GetThreatManager().ClearAllThreat(); iter->GetSource()->AI()->EnterEvadeMode(); } } diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index 380c36d0bdd..1b21a491954 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -40,6 +40,7 @@ #include "Spell.h" #include "SpellHistory.h" #include "SpellMgr.h" +#include "ThreatManager.h" #include "Unit.h" #include "Util.h" #include "Vehicle.h" @@ -4498,7 +4499,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool case 1515: // Tame beast // FIX_ME: this is 2.0.12 threat effect replaced in 2.1.x by dummy aura, must be checked for correctness if (caster && target->CanHaveThreatList()) - target->AddThreat(caster, 10.0f); + target->GetThreatManager().AddThreat(caster, 10.0f); break; case 13139: // net-o-matic // root to self part of (root_target->charge->root_self sequence @@ -5794,7 +5795,7 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c HealInfo healInfo(caster, caster, heal, GetSpellInfo(), GetSpellInfo()->GetSchoolMask()); caster->HealBySpell(healInfo); - caster->getHostileRefManager().threatAssist(caster, healInfo.GetEffectiveHeal() * 0.5f, GetSpellInfo()); + caster->GetThreatManager().ForwardThreatForAssistingMe(caster, healInfo.GetEffectiveHeal()*0.5f, GetSpellInfo()); caster->ProcSkillsAndAuras(caster, PROC_FLAG_DONE_PERIODIC, PROC_FLAG_TAKEN_PERIODIC, PROC_SPELL_TYPE_HEAL, PROC_SPELL_PHASE_NONE, hitMask, nullptr, nullptr, &healInfo); } @@ -5904,7 +5905,7 @@ void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const SpellPeriodicAuraLogInfo pInfo(this, heal, damage, heal - healInfo.GetEffectiveHeal(), healInfo.GetAbsorb(), 0, 0.0f, crit); target->SendPeriodicAuraLog(&pInfo); - target->getHostileRefManager().threatAssist(caster, float(healInfo.GetEffectiveHeal()) * 0.5f, GetSpellInfo()); + target->GetThreatManager().ForwardThreatForAssistingMe(caster, float(healInfo.GetEffectiveHeal())*0.5f, GetSpellInfo()); // %-based heal - does not proc auras if (GetAuraType() == SPELL_AURA_OBS_MOD_HEALTH) @@ -5952,7 +5953,8 @@ void AuraEffect::HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) con if (gainAmount) { gainedAmount = caster->ModifyPower(powerType, gainAmount); - target->AddThreat(caster, float(gainedAmount) * 0.5f, GetSpellInfo()->GetSchoolMask(), GetSpellInfo()); + // energize is not modified by threat modifiers + target->GetThreatManager().AddThreat(caster, float(gainedAmount) * 0.5f, GetSpellInfo(), true); } // Drain Mana @@ -6003,7 +6005,7 @@ void AuraEffect::HandleObsModPowerAuraTick(Unit* target, Unit* caster) const int32 gain = target->ModifyPower(powerType, amount); if (caster) - target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, GetSpellInfo()); + target->GetThreatManager().ForwardThreatForAssistingMe(caster, float(gain)*0.5f, GetSpellInfo(), true); target->SendPeriodicAuraLog(&pInfo); } @@ -6036,7 +6038,7 @@ void AuraEffect::HandlePeriodicEnergizeAuraTick(Unit* target, Unit* caster) cons target->SendPeriodicAuraLog(&pInfo); if (caster) - target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, GetSpellInfo()); + target->GetThreatManager().ForwardThreatForAssistingMe(caster, float(gain)*0.5f, GetSpellInfo(), true); } void AuraEffect::HandlePeriodicPowerBurnAuraTick(Unit* target, Unit* caster) const diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index 75b8a94a535..6d279322c55 100644 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -2453,7 +2453,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) HealInfo healInfo(caster, unitTarget, addhealth, m_spellInfo, m_spellInfo->GetSchoolMask()); caster->HealBySpell(healInfo, crit); - unitTarget->getHostileRefManager().threatAssist(caster, float(healInfo.GetEffectiveHeal()) * 0.5f, m_spellInfo); + unitTarget->GetThreatManager().ForwardThreatForAssistingMe(caster, float(healInfo.GetEffectiveHeal())*0.5f, m_spellInfo); m_healing = healInfo.GetEffectiveHeal(); // Do triggers for unit @@ -2523,8 +2523,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) if (missInfo == SPELL_MISS_RESIST && m_spellInfo->HasAttribute(SPELL_ATTR0_CU_PICKPOCKET) && unitTarget->GetTypeId() == TYPEID_UNIT) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); - if (unitTarget->ToCreature()->IsAIEnabled) - unitTarget->ToCreature()->AI()->AttackStart(m_caster); + unitTarget->ToCreature()->EngageWithTarget(m_caster); } } @@ -2620,14 +2619,16 @@ SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) // 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 (Player* playerOwner = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself()) + { + playerOwner->SetContestedPvP(); + playerOwner->UpdatePvP(true); + } } if (unit->IsInCombat() && m_spellInfo->HasInitialAggro()) { m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit); - unit->getHostileRefManager().threatAssist(m_caster, 0.0f); + unit->GetThreatManager().ForwardThreatForAssistingMe(m_caster, 0.0f, nullptr, true); } } } @@ -4838,14 +4839,14 @@ void Spell::HandleThreatSpells() // positive spells distribute threat among all units that are in combat with target, like healing if (m_spellInfo->IsPositive()) - target->getHostileRefManager().threatAssist(m_caster, threatToAdd, m_spellInfo); + target->GetThreatManager().ForwardThreatForAssistingMe(m_caster, threatToAdd, m_spellInfo); // for negative spells threat gets distributed among affected targets else { if (!target->CanHaveThreatList()) continue; - target->AddThreat(m_caster, threatToAdd, m_spellInfo->GetSchoolMask(), m_spellInfo); + target->GetThreatManager().AddThreat(m_caster, threatToAdd, m_spellInfo, true); } } TC_LOG_DEBUG("spells", "Spell %u, added an additional %f threat for %s %u target(s)", m_spellInfo->Id, threat, m_spellInfo->IsPositive() ? "assisting" : "harming", uint32(m_UniqueTargetInfo.size())); @@ -7937,7 +7938,7 @@ bool WorldObjectSpellTargetCheck::operator()(WorldObject* target) return false; break; case TARGET_CHECK_THREAT: - if (_referer->getThreatManager().getThreat(unitTarget, true) <= 0.0f) + if (_referer->GetThreatManager().getThreat(unitTarget, true) <= 0.0f) return false; break; case TARGET_CHECK_TAP: diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index 728c7b6911e..5276bb187be 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -2214,7 +2214,7 @@ void Spell::EffectDistract(SpellEffIndex /*effIndex*/) return; // Check for possible target - if (!unitTarget || unitTarget->IsInCombat()) + if (!unitTarget || unitTarget->IsEngaged()) return; // target must be OK to do this @@ -2730,17 +2730,17 @@ void Spell::EffectTaunt(SpellEffIndex /*effIndex*/) return; } - if (!unitTarget->getThreatManager().getOnlineContainer().empty()) + if (!unitTarget->GetThreatManager().getOnlineContainer().empty()) { // Also use this effect to set the taunter's threat to the taunted creature's highest value - float myThreat = unitTarget->getThreatManager().getThreat(m_caster); - float topThreat = unitTarget->getThreatManager().getOnlineContainer().getMostHated()->getThreat(); + float myThreat = unitTarget->GetThreatManager().getThreat(m_caster); + float topThreat = unitTarget->GetThreatManager().getOnlineContainer().getMostHated()->getThreat(); if (topThreat > myThreat) - unitTarget->getThreatManager().doAddThreat(m_caster, topThreat - myThreat); + unitTarget->GetThreatManager().doAddThreat(m_caster, topThreat - myThreat); //Set aggro victim to caster - if (HostileReference* forcedVictim = unitTarget->getThreatManager().getOnlineContainer().getReferenceByTarget(m_caster)) - unitTarget->getThreatManager().setCurrentVictim(forcedVictim); + if (HostileReference* forcedVictim = unitTarget->GetThreatManager().getOnlineContainer().getReferenceByTarget(m_caster)) + unitTarget->GetThreatManager().setCurrentVictim(forcedVictim); } if (unitTarget->ToCreature()->IsAIEnabled && !unitTarget->ToCreature()->HasReactState(REACT_PASSIVE)) @@ -2950,7 +2950,7 @@ void Spell::EffectThreat(SpellEffIndex /*effIndex*/) if (!unitTarget->CanHaveThreatList()) return; - unitTarget->AddThreat(m_caster, float(damage)); + unitTarget->GetThreatManager().AddThreat(m_caster, float(damage)); } void Spell::EffectHealMaxHealth(SpellEffIndex /*effIndex*/) @@ -4589,7 +4589,7 @@ void Spell::EffectModifyThreatPercent(SpellEffIndex /*effIndex*/) if (!unitTarget) return; - unitTarget->getThreatManager().modifyThreatPercent(m_caster, damage); + unitTarget->GetThreatManager().ModifyThreatByPercent(m_caster, damage); } void Spell::EffectTransmitted(SpellEffIndex effIndex) |
