TrinityCore
Loading...
Searching...
No Matches
ThreatManager.cpp
Go to the documentation of this file.
1/*
2 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "ThreatManager.h"
19#include "Creature.h"
20#include "CombatPackets.h"
21#include "CreatureAI.h"
22#include "CreatureGroups.h"
23#include "MapUtils.h"
24#include "MotionMaster.h"
25#include "ObjectAccessor.h"
26#include "Player.h"
27#include "SpellAuraEffects.h"
28#include "SpellMgr.h"
29#include "TemporarySummon.h"
30#include <boost/heap/fibonacci_heap.hpp>
31
33
34class ThreatManager::Heap : public boost::heap::fibonacci_heap<ThreatReference const*, boost::heap::compare<CompareThreatLessThan>>
35{
36};
37
39{
40 if (amount == 0.0f)
41 return;
42 _baseAmount = std::max<float>(_baseAmount + amount, 0.0f);
43 if (amount > 0.0f)
45 else
48}
49
51{
52 if (factor == 1.0f)
53 return;
54 _baseAmount *= factor;
55 if (factor > 1.0f)
57 else
60}
61
63{
64 bool const shouldBeOffline = ShouldBeOffline();
65 if (shouldBeOffline == IsOffline())
66 return;
67
68 if (shouldBeOffline)
69 {
73 }
74 else
75 {
79 }
80}
81
82/*static*/ bool ThreatReference::FlagsAllowFighting(Unit const* a, Unit const* b)
83{
84 if (a->GetTypeId() == TYPEID_UNIT && a->ToCreature()->IsTrigger())
85 return false;
87 {
89 return false;
90 }
91 else
92 {
94 return false;
95 }
96 return true;
97}
98
100{
102 return true;
104 return true;
106 return true;
107 return false;
108}
109
111{
112 if (IsTaunting()) // a taunting victim can never be suppressed
113 return false;
115 return true;
117 return true;
119 return true;
120 return false;
121}
122
124{
125 // Check for SPELL_AURA_MOD_DETAUNT (applied from owner to victim)
126 if (state < TAUNT_STATE_TAUNT && _victim->HasAuraTypeWithCaster(SPELL_AURA_MOD_DETAUNT, _owner->GetGUID()))
127 state = TAUNT_STATE_DETAUNT;
128
129 if (state == _taunted)
130 return;
131
132 std::swap(state, _taunted);
133
134 if (_taunted < state)
136 else
138
139 _mgr._needClientUpdate = true;
140}
141
146
153
155{
156public:
157 explicit ThreatReferenceImpl(ThreatManager* mgr, Unit* victim) : ThreatReference(mgr, victim) { }
158
159 ThreatManager::Heap::handle_type _handle;
160};
161
163{
164 _mgr._sortedThreatList->increase(static_cast<ThreatReferenceImpl*>(this)->_handle);
165}
166
168{
169 _mgr._sortedThreatList->decrease(static_cast<ThreatReferenceImpl*>(this)->_handle);
170}
171
172/*static*/ bool ThreatManager::CanHaveThreatList(Unit const* who)
173{
174 Creature const* cWho = who->ToCreature();
175 // only creatures can have threat list
176 if (!cWho)
177 return false;
178
179 // pets, totems and triggers cannot have threat list
180 if (cWho->IsPet() || cWho->IsTotem() || cWho->IsTrigger())
181 return false;
182
183 // summons cannot have a threat list if they were summoned by a player
185 if (TempSummon const* tWho = cWho->ToTempSummon())
186 if (tWho->GetSummonerGUID().IsPlayer())
187 return false;
188
189 // accessories are fully treated as components of the parent and cannot have threat
191 return false;
192
193 return true;
194}
195
196ThreatManager::ThreatManager(Unit* owner) : _owner(owner), _ownerCanHaveThreatList(false), _needClientUpdate(false), _needThreatClearUpdate(false), _updateTimer(THREAT_UPDATE_INTERVAL),
197 _sortedThreatList(std::make_unique<Heap>()), _currentVictimRef(nullptr), _fixateRef(nullptr)
198{
199 for (int8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
200 _singleSchoolModifiers[i] = 1.0f;
201}
202
204{
205 ASSERT(_myThreatListEntries.empty(), "ThreatManager::~ThreatManager - %s: we still have %zu things threatening us, one of them is %s.", _owner->GetGUID().ToString().c_str(), _myThreatListEntries.size(), _myThreatListEntries.begin()->first.ToString().c_str());
206 ASSERT(_sortedThreatList->empty(), "ThreatManager::~ThreatManager - %s: we still have %zu things threatening us, one of them is %s.", _owner->GetGUID().ToString().c_str(), _sortedThreatList->size(), (*_sortedThreatList->begin())->GetVictim()->GetGUID().ToString().c_str());
207 ASSERT(_threatenedByMe.empty(), "ThreatManager::~ThreatManager - %s: we are still threatening %zu things, one of them is %s.", _owner->GetGUID().ToString().c_str(), _threatenedByMe.size(), _threatenedByMe.begin()->first.ToString().c_str());
208}
209
214
216{
217 if (!CanHaveThreatList())
218 return;
219
220 if (_updateTimer <= tdiff)
221 {
223 {
226 }
227
228 if (!IsThreatListEmpty(true))
229 UpdateVictim();
230
232 }
233 else
234 _updateTimer -= tdiff;
235}
236
241
249
251{
254 return nullptr;
255}
256
258{
259 for (ThreatReference const* ref : *_sortedThreatList)
260 if (!ref->IsOffline())
261 return ref->GetVictim();
262 return nullptr;
263}
264
265bool ThreatManager::IsThreatListEmpty(bool includeOffline) const
266{
267 if (includeOffline)
268 return _sortedThreatList->empty();
269 for (ThreatReference const* ref : *_sortedThreatList)
270 if (ref->IsAvailable())
271 return false;
272 return true;
273}
274
275bool ThreatManager::IsThreatenedBy(ObjectGuid const& who, bool includeOffline) const
276{
277 auto it = _myThreatListEntries.find(who);
278 if (it == _myThreatListEntries.end())
279 return false;
280 return (includeOffline || it->second->IsAvailable());
281}
282bool ThreatManager::IsThreatenedBy(Unit const* who, bool includeOffline) const { return IsThreatenedBy(who->GetGUID(), includeOffline); }
283
284float ThreatManager::GetThreat(Unit const* who, bool includeOffline) const
285{
286 auto it = _myThreatListEntries.find(who->GetGUID());
287 if (it == _myThreatListEntries.end())
288 return 0.0f;
289 return (includeOffline || it->second->IsAvailable()) ? it->second->GetThreat() : 0.0f;
290}
291
293{
294 return _sortedThreatList->size();
295}
296
297uint32 ThreatManager::GetThreatListPlayerCount(bool includeOffline/* = false*/) const
298{
299 if (includeOffline)
300 return uint32(_sortedThreatList->size());
301 uint32 returnValue = 0;
302 for (ThreatReference const* ref : *_sortedThreatList)
303 if (ref->IsAvailable() && ref->GetVictim()->GetTypeId() == TYPEID_PLAYER)
304 ++returnValue;
305 return returnValue;
306}
307
309{
310 auto itr = _myThreatListEntries.begin();
311 auto end = _myThreatListEntries.end();
312 std::function<ThreatReference const* ()> generator = [itr, end]() mutable -> ThreatReference const*
313 {
314 if (itr == end)
315 return nullptr;
316
317 return (itr++)->second;
318 };
319 return { ThreatListIterator{ std::move(generator) }, nullptr };
320}
321
323{
324 auto itr = _sortedThreatList->ordered_begin();
325 auto end = _sortedThreatList->ordered_end();
326 std::function<ThreatReference const* ()> generator = [itr, end]() mutable -> ThreatReference const*
327 {
328 if (itr == end)
329 return nullptr;
330
331 return *(itr++);
332 };
333 return { ThreatListIterator{ std::move(generator) }, nullptr };
334}
335
336std::vector<ThreatReference*> ThreatManager::GetModifiableThreatList()
337{
338 std::vector<ThreatReference*> list;
339 list.reserve(_myThreatListEntries.size());
340 for (auto it = _sortedThreatList->ordered_begin(), end = _sortedThreatList->ordered_end(); it != end; ++it)
341 list.push_back(const_cast<ThreatReference*>(*it));
342 return list;
343}
344
345bool ThreatManager::IsThreateningAnyone(bool includeOffline) const
346{
347 if (includeOffline)
348 return !_threatenedByMe.empty();
349 for (auto const& pair : _threatenedByMe)
350 if (pair.second->IsAvailable())
351 return true;
352 return false;
353}
354
355bool ThreatManager::IsThreateningTo(ObjectGuid const& who, bool includeOffline) const
356{
357 auto it = _threatenedByMe.find(who);
358 if (it == _threatenedByMe.end())
359 return false;
360 return (includeOffline || it->second->IsAvailable());
361}
362bool ThreatManager::IsThreateningTo(Unit const* who, bool includeOffline) const { return IsThreateningTo(who->GetGUID(), includeOffline); }
363
365{
366 for (auto const& pair : _threatenedByMe)
367 {
368 bool const shouldBeSuppressed = pair.second->ShouldBeSuppressed();
369 if (pair.second->IsOnline() && shouldBeSuppressed)
370 {
371 pair.second->_online = ThreatReference::ONLINE_STATE_SUPPRESSED;
372 pair.second->HeapNotifyDecreased();
373 }
374 else if (canExpire && pair.second->IsSuppressed() && !shouldBeSuppressed)
375 {
376 pair.second->_online = ThreatReference::ONLINE_STATE_ONLINE;
377 pair.second->HeapNotifyIncreased();
378 }
379 }
380}
381
382void ThreatManager::AddThreat(Unit* target, float amount, SpellInfo const* spell, bool ignoreModifiers, bool ignoreRedirects)
383{
384 // step 1: we can shortcut if the spell has one of the NO_THREAT attrs set - nothing will happen
385 if (spell)
386 {
388 return;
390 return;
391 }
392
393 // if we cannot actually have a threat list, we instead just set combat state and avoid creating threat refs altogether
394 if (!CanHaveThreatList())
395 {
396 CombatManager& combatMgr = _owner->GetCombatManager();
397 if (!combatMgr.SetInCombatWith(target))
398 return;
399 // traverse redirects and put them in combat, too
400 for (auto const& pair : target->GetThreatManager()._redirectInfo)
401 if (!combatMgr.IsInCombatWith(pair.first))
402 if (Unit* redirTarget = ObjectAccessor::GetUnit(*_owner, pair.first))
403 combatMgr.SetInCombatWith(redirTarget);
404 return;
405 }
406
407 // apply threat modifiers to the amount
408 if (!ignoreModifiers)
409 amount = CalculateModifiedThreat(amount, target, spell);
410
411 // if we're increasing threat, send some/all of it to redirection targets instead if applicable
412 if (!ignoreRedirects && amount > 0.0f)
413 {
414 auto const& redirInfo = target->GetThreatManager()._redirectInfo;
415 if (!redirInfo.empty())
416 {
417 float const origAmount = amount;
418 // intentional iteration by index - there's a nested AddThreat call further down that might cause AI calls which might modify redirect info through spells
419 for (size_t i = 0; i < redirInfo.size(); ++i)
420 {
421 auto const pair = redirInfo[i]; // (victim,pct)
422 Unit* redirTarget = nullptr;
423 auto it = _myThreatListEntries.find(pair.first); // try to look it up in our threat list first (faster)
424 if (it != _myThreatListEntries.end())
425 redirTarget = it->second->_victim;
426 else
427 redirTarget = ObjectAccessor::GetUnit(*_owner, pair.first);
428
429 if (redirTarget)
430 {
431 float amountRedirected = CalculatePct(origAmount, pair.second);
432 AddThreat(redirTarget, amountRedirected, spell, true, true);
433 amount -= amountRedirected;
434 }
435 }
436 }
437 }
438
439 // ensure we're in combat (threat implies combat!)
440 if (!_owner->GetCombatManager().SetInCombatWith(target)) // if this returns false, we're not actually in combat, and thus cannot have threat!
441 return; // typical causes: bad scripts trying to add threat to GMs, dead targets etc
442
443 // ok, now we actually apply threat
444 // check if we already have an entry - if we do, just increase threat for that entry and we're done
445 auto it = _myThreatListEntries.find(target->GetGUID());
446 if (it != _myThreatListEntries.end())
447 {
448 ThreatReference* const ref = it->second;
449 // SUPPRESSED threat states don't go back to ONLINE until threat is caused by them (retail behavior)
451 if (!ref->ShouldBeSuppressed())
452 {
454 ref->HeapNotifyIncreased();
455 }
456
457 if (ref->IsOnline())
458 ref->AddThreat(amount);
459 return;
460 }
461
462 // ok, we're now in combat - create the threat list reference and push it to the respective managers
463 ThreatReference* ref = new ThreatReferenceImpl(this, target);
464 PutThreatListRef(target->GetGUID(), ref);
466
467 ref->UpdateOffline();
468 if (ref->IsOnline()) // we only add the threat if the ref is currently available
469 ref->AddThreat(amount);
470
472 UpdateVictim();
473 else
475}
476
477void ThreatManager::ScaleThreat(Unit* target, float factor)
478{
479 auto it = _myThreatListEntries.find(target->GetGUID());
480 if (it != _myThreatListEntries.end())
481 it->second->ScaleThreat(std::max<float>(factor,0.0f));
482}
483
485{
486 if (_sortedThreatList->empty())
487 return;
488
489 auto it = _sortedThreatList->ordered_begin(), end = _sortedThreatList->ordered_end();
490 ThreatReference const* highest = *it;
491 if (!highest->IsAvailable())
492 return;
493
494 if (highest->IsTaunting() && ((++it) != end)) // might need to skip this - max threat could be the preceding element (there is only one taunt element)
495 {
496 ThreatReference const* a = *it;
497 if (a->IsAvailable() && a->GetThreat() > highest->GetThreat())
498 highest = a;
499 }
500
501 AddThreat(target, highest->GetThreat() - GetThreat(target, true), nullptr, true, true);
502}
503
505{
507
508 uint32 tauntPriority = 0; // lowest is highest
509 std::unordered_map<ObjectGuid, uint32> tauntStates;
510 // Only the last taunt effect applied by something still on our threat list is considered
511 for (AuraEffect const* tauntEffect : tauntEffects)
512 tauntStates[tauntEffect->GetCasterGUID()] = ++tauntPriority;
513
514 for (auto const& pair : _myThreatListEntries)
515 {
516 auto it = tauntStates.find(pair.first);
517 if (it != tauntStates.end())
518 pair.second->UpdateTauntState(ThreatReference::TauntState(ThreatReference::TAUNT_STATE_TAUNT + tauntStates.size() - it->second));
519 else
520 pair.second->UpdateTauntState();
521 }
522
523 // taunt aura update also re-evaluates all suppressed states (retail behavior)
524 EvaluateSuppressed(true);
525}
526
528{
529 for (auto const& pair : _myThreatListEntries)
530 pair.second->ScaleThreat(0.0f);
531}
532
534{
535 auto it = _myThreatListEntries.find(target->GetGUID());
536 if (it != _myThreatListEntries.end())
537 ClearThreat(it->second);
538}
539
547
549{
550 if (!_myThreatListEntries.empty())
551 {
553 do
554 _myThreatListEntries.begin()->second->UnregisterAndFree();
555 while (!_myThreatListEntries.empty());
556 }
557}
558
560{
561 if (target)
562 {
563 auto it = _myThreatListEntries.find(target->GetGUID());
564 if (it != _myThreatListEntries.end())
565 {
566 _fixateRef = it->second;
567 return;
568 }
569 }
570 _fixateRef = nullptr;
571}
572
574{
575 if (_fixateRef)
576 return _fixateRef->GetVictim();
577 else
578 return nullptr;
579}
580
582{
583 ThreatReference const* const newVictim = ReselectVictim();
584 bool const newHighest = newVictim && (newVictim != _currentVictimRef);
585
586 _currentVictimRef = newVictim;
587 if (newHighest || _needClientUpdate)
588 {
589 SendThreatListToClients(newHighest);
590 _needClientUpdate = false;
591 }
592
594}
595
597{
598 if (_sortedThreatList->empty())
599 return nullptr;
600
601 for (auto const& pair : _myThreatListEntries)
602 pair.second->UpdateOffline(); // AI notifies are processed in ::UpdateVictim caller
603
604 // fixated target is always preferred
606 return _fixateRef;
607
608 ThreatReference const* oldVictimRef = _currentVictimRef;
609 if (oldVictimRef && oldVictimRef->IsOffline())
610 oldVictimRef = nullptr;
611 // in 99% of cases - we won't need to actually look at anything beyond the first element
612 ThreatReference const* highest = _sortedThreatList->top();
613 // if the highest reference is offline, the entire list is offline, and we indicate this
614 if (!highest->IsAvailable())
615 return nullptr;
616 // if we have no old victim, or old victim is still highest, then highest is our target and we're done
617 if (!oldVictimRef || highest == oldVictimRef)
618 return highest;
619 // if highest threat doesn't break 110% of old victim, nothing below it is going to do so either; new victim = old victim and done
620 if (!ThreatManager::CompareReferencesLT(oldVictimRef, highest, 1.1f))
621 return oldVictimRef;
622 // if highest threat breaks 130%, it's our new target regardless of range (and we're done)
623 if (ThreatManager::CompareReferencesLT(oldVictimRef, highest, 1.3f))
624 return highest;
625 // if it doesn't break 130%, we need to check if it's melee - if yes, it breaks 110% (we checked earlier) and is our new target
626 if (_owner->IsWithinMeleeRange(highest->_victim))
627 return highest;
628 // If we get here, highest threat is ranged, but below 130% of current - there might be a melee that breaks 110% below us somewhere, so now we need to actually look at the next highest element
629 // luckily, this is a heap, so getting the next highest element is O(log n), and we're just gonna do that repeatedly until we've seen enough targets (or find a target)
630 auto it = _sortedThreatList->ordered_begin(), end = _sortedThreatList->ordered_end();
631 while (it != end)
632 {
633 ThreatReference const* next = *it;
634 // if we've found current victim, we're done (nothing above is higher, and nothing below can be higher)
635 if (next == oldVictimRef)
636 return next;
637 // if next isn't above 110% threat, then nothing below it can be either - we're done, old victim stays
638 if (!ThreatManager::CompareReferencesLT(oldVictimRef, next, 1.1f))
639 return oldVictimRef;
640 // if next is melee, he's above 110% and our new victim
642 return next;
643 // otherwise the next highest target may still be a melee above 110% and we need to look further
644 ++it;
645 }
646 // we should have found the old victim at some point in the loop above, so execution should never get to this point
647 ABORT_MSG("Current victim not found in sorted threat list even though it has a reference - manager desync!");
648 return nullptr;
649}
650
652{
654 std::vector<ObjectGuid> v(std::move(_needsAIUpdate)); // _needsAIUpdate is now empty in case this triggers a recursive call
655 if (!ai)
656 return;
657 for (ObjectGuid const& guid : v)
659 ai->JustStartedThreateningMe(ref->GetVictim());
660}
661
663{
664 _needsAIUpdate.push_back(guid);
665}
666
667// returns true if a is LOWER on the threat list than b
668/*static*/ bool ThreatManager::CompareReferencesLT(ThreatReference const* a, ThreatReference const* b, float aWeight)
669{
670 if (a->_online != b->_online) // online state precedence (ONLINE > SUPPRESSED > OFFLINE)
671 return a->_online < b->_online;
672 if (a->_taunted != b->_taunted) // taunt state precedence (TAUNT > NONE > DETAUNT)
673 return a->_taunted < b->_taunted;
674 return (a->GetThreat()*aWeight < b->GetThreat());
675}
676
677/*static*/ float ThreatManager::CalculateModifiedThreat(float threat, Unit const* victim, SpellInfo const* spell)
678{
679 // modifiers by spell
680 if (spell)
681 {
682 if (SpellThreatEntry const* threatEntry = sSpellMgr->GetSpellThreatEntry(spell->Id))
683 if (threatEntry->pctMod != 1.0f) // flat/AP modifiers handled in Spell::HandleThreatSpells
684 threat *= threatEntry->pctMod;
685
686 if (Player* modOwner = victim->GetSpellModOwner())
687 modOwner->ApplySpellMod(spell, SpellModOp::Hate, threat);
688 }
689
690 // modifiers by effect school
691 ThreatManager const& victimMgr = victim->GetThreatManager();
692 SpellSchoolMask const mask = spell ? spell->GetSchoolMask() : SPELL_SCHOOL_MASK_NORMAL;
693 switch (mask)
694 {
696 threat *= victimMgr._singleSchoolModifiers[SPELL_SCHOOL_NORMAL];
697 break;
699 threat *= victimMgr._singleSchoolModifiers[SPELL_SCHOOL_HOLY];
700 break;
702 threat *= victimMgr._singleSchoolModifiers[SPELL_SCHOOL_FIRE];
703 break;
705 threat *= victimMgr._singleSchoolModifiers[SPELL_SCHOOL_NATURE];
706 break;
708 threat *= victimMgr._singleSchoolModifiers[SPELL_SCHOOL_FROST];
709 break;
711 threat *= victimMgr._singleSchoolModifiers[SPELL_SCHOOL_SHADOW];
712 break;
714 threat *= victimMgr._singleSchoolModifiers[SPELL_SCHOOL_ARCANE];
715 break;
716 default:
717 {
718 auto it = victimMgr._multiSchoolModifiers.find(mask);
719 if (it != victimMgr._multiSchoolModifiers.end())
720 {
721 threat *= it->second;
722 break;
723 }
725 victimMgr._multiSchoolModifiers[mask] = mod;
726 threat *= mod;
727 break;
728 }
729 }
730 return threat;
731}
732
733void ThreatManager::ForwardThreatForAssistingMe(Unit* assistant, float baseAmount, SpellInfo const* spell, bool ignoreModifiers)
734{
735 if (spell && (spell->HasAttribute(SPELL_ATTR1_NO_THREAT) || spell->HasAttribute(SPELL_ATTR4_NO_HELPFUL_THREAT))) // shortcut, none of the calls would do anything
736 return;
737 if (_threatenedByMe.empty())
738 return;
739
740 std::vector<Creature*> canBeThreatened, cannotBeThreatened;
741 for (auto const& pair : _threatenedByMe)
742 {
743 Creature* owner = pair.second->GetOwner();
745 canBeThreatened.push_back(owner);
746 else
747 cannotBeThreatened.push_back(owner);
748 }
749
750 if (!canBeThreatened.empty()) // targets under CC cannot gain assist threat - split evenly among the rest
751 {
752 float const perTarget = baseAmount / canBeThreatened.size();
753 for (Creature* threatened : canBeThreatened)
754 threatened->GetThreatManager().AddThreat(assistant, perTarget, spell, ignoreModifiers);
755 }
756
757 for (Creature* threatened : cannotBeThreatened)
758 threatened->GetThreatManager().AddThreat(assistant, 0.0f, spell, true);
759}
760
761void ThreatManager::RemoveMeFromThreatLists(bool (*unitFilter)(Unit const* otherUnit))
762{
763 std::vector<ThreatReference*> threatReferencesToRemove;
764 threatReferencesToRemove.reserve(_threatenedByMe.size());
765 for (auto const& [guid, ref] : _threatenedByMe)
766 if (!unitFilter || unitFilter(ref->GetOwner()))
767 threatReferencesToRemove.push_back(ref);
768
769 for (ThreatReference* ref : threatReferencesToRemove)
770 ref->_mgr.ClearThreat(_owner);
771}
772
774{
775 SpellEffectValue mod = 0;
777 mod += eff->GetAmount();
778
779 if (_threatenedByMe.empty())
780 return;
781
782 auto it = _threatenedByMe.begin();
783 bool const isIncrease = (it->second->_tempModifier < mod);
784 do
785 {
786 it->second->_tempModifier = mod;
787 if (isIncrease)
788 it->second->HeapNotifyIncreased();
789 else
790 it->second->HeapNotifyDecreased();
791 } while ((++it) != _threatenedByMe.end());
792}
793
800
801void ThreatManager::RegisterRedirectThreat(uint32 spellId, ObjectGuid const& victim, float pct)
802{
803 _redirectRegistry[spellId][victim] = pct;
805}
806
808{
809 auto it = _redirectRegistry.find(spellId);
810 if (it == _redirectRegistry.end())
811 return;
812 _redirectRegistry.erase(it);
814}
815
817{
818 auto it = _redirectRegistry.find(spellId);
819 if (it == _redirectRegistry.end())
820 return;
821 auto& victimMap = it->second;
822 auto it2 = victimMap.find(victim);
823 if (it2 == victimMap.end())
824 return;
825 victimMap.erase(it2);
827}
828
830{
831 if (Creature const* owner = _owner->ToCreature(); owner && owner->IsThreatFeedbackDisabled())
832 return;
833
835 threatClear.UnitGUID = _owner->GetGUID();
836 _owner->SendMessageToSet(threatClear.Write(), false);
837}
838
840{
841 if (Creature const* owner = _owner->ToCreature(); owner && owner->IsThreatFeedbackDisabled())
842 return;
843
845 threatRemove.UnitGUID = _owner->GetGUID();
846 threatRemove.AboutGUID = victim->GetGUID();
847 _owner->SendMessageToSet(threatRemove.Write(), false);
848}
849
850void ThreatManager::SendThreatListToClients(bool newHighest) const
851{
852 if (Creature const* owner = _owner->ToCreature(); owner && owner->IsThreatFeedbackDisabled())
853 return;
854
855 auto fillSharedPacketDataAndSend = [&](auto& packet)
856 {
857 packet.UnitGUID = _owner->GetGUID();
858 packet.ThreatList.reserve(_sortedThreatList->size());
859 for (ThreatReference const* ref : *_sortedThreatList)
860 {
861 if (!ref->IsAvailable())
862 continue;
863
865 threatInfo.UnitGUID = ref->GetVictim()->GetGUID();
866 threatInfo.Threat = int64(ref->GetThreat() * 100);
867 packet.ThreatList.push_back(threatInfo);
868 }
869 _owner->SendMessageToSet(packet.Write(), false);
870 };
871
872 if (newHighest)
873 {
875 highestThreatUpdate.HighestThreatGUID = _currentVictimRef->GetVictim()->GetGUID();
876 fillSharedPacketDataAndSend(highestThreatUpdate);
877 }
878 else
879 {
881 fillSharedPacketDataAndSend(threatUpdate);
882 }
883}
884
886{
887 _needClientUpdate = true;
888 auto& inMap = _myThreatListEntries[guid];
889 ASSERT(!inMap, "Duplicate threat reference at %p being inserted on %s for %s - memory leak!", ref, _owner->GetGUID().ToString().c_str(), guid.ToString().c_str());
890 inMap = ref;
891 static_cast<ThreatReferenceImpl*>(ref)->_handle = _sortedThreatList->push(ref);
892}
893
895{
896 auto it = _myThreatListEntries.find(guid);
897 if (it == _myThreatListEntries.end())
898 return;
899 ThreatReference* ref = it->second;
900 _myThreatListEntries.erase(it);
901 _sortedThreatList->erase(static_cast<ThreatReferenceImpl*>(ref)->_handle);
902
903 if (_fixateRef == ref)
904 _fixateRef = nullptr;
905 if (_currentVictimRef == ref)
906 _currentVictimRef = nullptr;
907}
908
910{
911 auto& inMap = _threatenedByMe[guid];
912 ASSERT(!inMap, "Duplicate threatened-by-me reference at %p being inserted on %s for %s - memory leak!", ref, _owner->GetGUID().ToString().c_str(), guid.ToString().c_str());
913 inMap = ref;
914}
915
917{
918 auto it = _threatenedByMe.find(guid);
919 if (it != _threatenedByMe.end())
920 _threatenedByMe.erase(it);
921}
922
924{
925 _redirectInfo.clear();
926 float totalPct = 0;
927 for (auto const& pair : _redirectRegistry) // (spellid, victim -> pct)
928 for (auto const& victimPair : pair.second) // (victim,pct)
929 {
930 float thisPct = std::min(100.0f - totalPct, victimPair.second);
931 if (thisPct > 0)
932 {
933 _redirectInfo.push_back({ victimPair.first, thisPct });
934 totalPct += thisPct;
935 ASSERT(totalPct <= 100);
936 if (totalPct == 100)
937 return;
938 }
939 }
940}
uint8_t uint8
Definition Define.h:156
int64_t int64
Definition Define.h:149
int8_t int8
Definition Define.h:152
uint32_t uint32
Definition Define.h:154
#define ABORT_MSG
Definition Errors.h:80
#define ASSERT_NOTNULL(pointer)
Definition Errors.h:74
#define ASSERT
Definition Errors.h:72
@ TYPEID_UNIT
Definition ObjectGuid.h:43
@ TYPEID_PLAYER
Definition ObjectGuid.h:44
SpellSchoolMask
@ SPELL_SCHOOL_MASK_NORMAL
@ SPELL_SCHOOL_MASK_SHADOW
@ SPELL_SCHOOL_MASK_ARCANE
@ SPELL_SCHOOL_MASK_NATURE
@ SPELL_SCHOOL_MASK_HOLY
@ SPELL_SCHOOL_MASK_FIRE
@ SPELL_SCHOOL_MASK_FROST
@ SPELL_ATTR2_NO_INITIAL_THREAT
@ SPELL_ATTR1_NO_THREAT
@ SPELL_SCHOOL_SHADOW
@ SPELL_SCHOOL_NORMAL
@ SPELL_SCHOOL_NATURE
@ SPELL_SCHOOL_FROST
@ SPELL_SCHOOL_ARCANE
@ SPELL_SCHOOL_FIRE
@ SPELL_SCHOOL_HOLY
@ MAX_SPELL_SCHOOL
@ SPELL_ATTR4_NO_HELPFUL_THREAT
@ SPELL_AURA_MOD_TOTAL_THREAT
@ SPELL_AURA_MOD_THREAT
@ SPELL_AURA_MOD_DETAUNT
@ SPELL_AURA_MOD_TAUNT
@ SPELL_AURA_MOD_CONFUSE
@ SPELL_AURA_MOD_STUN
double SpellEffectValue
This is a double instead of float to be able to store full range of int32.
#define sSpellMgr
Definition SpellMgr.h:812
@ UNIT_FLAG_IMMUNE_TO_NPC
@ UNIT_FLAG_IMMUNE_TO_PC
@ UNIT_FLAG_PLAYER_CONTROLLED
@ UNIT_MASK_ACCESSORY
Definition Unit.h:379
@ UNIT_MASK_GUARDIAN
Definition Unit.h:372
@ UNIT_MASK_MINION
Definition Unit.h:371
@ UNIT_STATE_CONTROLLED
Definition Unit.h:315
T CalculatePct(T base, U pct)
Definition Util.h:72
ObjectGuid const & GetGUID() const
Definition BaseEntity.h:163
TypeID GetTypeId() const
Definition BaseEntity.h:166
bool SetInCombatWith(Unit *who, bool addSecondUnitSuppressed=false)
bool IsInCombatWith(ObjectGuid const &who) const
virtual void JustStartedThreateningMe(Unit *who)
Definition CreatureAI.h:98
bool IsTrigger() const
Definition Creature.h:127
bool _IsTargetAcceptable(Unit const *target) const
SpellSchoolMask GetMeleeDamageSchoolMask(WeaponAttackType=BASE_ATTACK) const override
Definition Creature.h:237
bool CanCreatureAttack(Unit const *victim, bool force=true) const
std::string ToString() const
Creature * ToCreature()
Definition Object.h:121
uint32 const Id
Definition SpellInfo.h:328
SpellSchoolMask GetSchoolMask() const
bool HasAttribute(SpellAttr0 attribute) const
Definition SpellInfo.h:456
std::unordered_map< ObjectGuid, ThreatReference * > _threatenedByMe
bool CanHaveThreatList() const
ThreatManager(Unit *owner)
static float CalculateModifiedThreat(float threat, Unit const *victim, SpellInfo const *spell)
void SendClearAllThreatToClients() const
void RegisterRedirectThreat(uint32 spellId, ObjectGuid const &victim, float pct)
== REDIRECT SYSTEM ==
void EvaluateSuppressed(bool canExpire=false)
void UnregisterRedirectThreat(uint32 spellId)
void ForwardThreatForAssistingMe(Unit *assistant, float baseAmount, SpellInfo const *spell=nullptr, bool ignoreModifiers=false)
== AFFECT OTHERS' THREAT LISTS ==
bool IsThreatenedBy(ObjectGuid const &who, bool includeOffline=false) const
void PutThreatListRef(ObjectGuid const &guid, ThreatReference *ref)
== MY THREAT LIST ==
bool IsThreateningTo(ObjectGuid const &who, bool includeOffline=false) const
void RemoveMeFromThreatLists(bool(*unitFilter)(Unit const *otherUnit))
Unit * GetCurrentVictim()
static const uint32 THREAT_UPDATE_INTERVAL
void PutThreatenedByMeRef(ObjectGuid const &guid, ThreatReference *ref)
== OTHERS' THREAT LISTS ==
void RegisterForAIUpdate(ObjectGuid const &guid)
void SendThreatListToClients(bool newHighest) const
void UpdateRedirectInfo()
std::array< float, MAX_SPELL_SCHOOL > _singleSchoolModifiers
void UpdateMySpellSchoolModifiers()
static bool CompareReferencesLT(ThreatReference const *a, ThreatReference const *b, float aWeight)
Trinity::IteratorPair< ThreatListIterator, std::nullptr_t > GetUnsortedThreatList() const
static const CompareThreatLessThan CompareThreat
std::unique_ptr< Heap > _sortedThreatList
void ScaleThreat(Unit *target, float factor)
void ClearThreat(Unit *target)
ThreatReference const * _currentVictimRef
Unit * GetAnyTarget() const
Unit * GetLastVictim() const
std::unordered_map< ObjectGuid, ThreatReference * > _myThreatListEntries
bool _ownerCanHaveThreatList
void FixateTarget(Unit *target)
bool IsThreatListEmpty(bool includeOffline=false) const
std::vector< ObjectGuid > _needsAIUpdate
void Update(uint32 tdiff)
std::unordered_map< uint32, std::unordered_map< ObjectGuid, float > > _redirectRegistry
void PurgeThreatListRef(ObjectGuid const &guid)
Unit *const _owner
void AddThreat(Unit *target, float amount, SpellInfo const *spell=nullptr, bool ignoreModifiers=false, bool ignoreRedirects=false)
== AFFECT MY THREAT LIST ==
bool IsThreateningAnyone(bool includeOffline=false) const
ThreatReference const * _fixateRef
ThreatReference const * ReselectVictim()
void SendRemoveToClients(Unit const *victim) const
uint32 GetThreatListPlayerCount(bool includeOffline=false) const
Trinity::IteratorPair< ThreatListIterator, std::nullptr_t > GetSortedThreatList() const
std::vector< ThreatReference * > GetModifiableThreatList()
std::unordered_map< std::underlying_type< SpellSchoolMask >::type, float > _multiSchoolModifiers
Unit * GetFixateTarget() const
friend class ThreatReferenceImpl
void UpdateMyTempModifiers()
void PurgeThreatenedByMeRef(ObjectGuid const &guid)
float GetThreat(Unit const *who, bool includeOffline=false) const
void MatchUnitThreatToHighestThreat(Unit *target)
std::vector< std::pair< ObjectGuid, float > > _redirectInfo
bool _needThreatClearUpdate
size_t GetThreatListSize() const
ThreatManager::Heap::handle_type _handle
ThreatReferenceImpl(ThreatManager *mgr, Unit *victim)
static bool FlagsAllowFighting(Unit const *a, Unit const *b)
void ScaleThreat(float factor)
bool IsTaunting() const
bool ShouldBeSuppressed() const
ThreatManager & _mgr
OnlineState GetOnlineState() const
Creature *const _owner
bool IsOnline() const
bool ShouldBeOffline() const
Unit *const _victim
TauntState _taunted
bool IsOffline() const
float GetThreat() const
OnlineState _online
void UpdateTauntState(TauntState state=TAUNT_STATE_NONE)
Unit * GetVictim() const
void AddThreat(float amount)
bool IsAvailable() const
Utility class to enable range for loop syntax for multimap.equal_range uses.
constexpr iterator begin() const
Definition Unit.h:647
bool IsWithinMeleeRange(Unit const *obj) const
Definition Unit.h:722
AuraEffectList const & GetAuraEffectsByType(AuraType type) const
Definition Unit.h:1362
ThreatManager & GetThreatManager()
Definition Unit.h:1093
std::forward_list< AuraEffect * > AuraEffectList
Definition Unit.h:664
bool IsPet() const
Definition Unit.h:763
bool HasUnitFlag(UnitFlags flags) const
Definition Unit.h:860
TempSummon * ToTempSummon()
Definition Unit.h:1844
bool HasAuraType(AuraType auraType) const
Definition Unit.cpp:4832
Unit * GetVictim() const
Definition Unit.h:738
bool IsImmunedToDamage(SpellSchoolMask meleeSchoolMask) const
Definition Unit.cpp:7874
float GetTotalAuraMultiplierByMiscMask(AuraType auraType, uint32 misc_mask) const
Definition Unit.cpp:5117
bool HasUnitState(const uint32 f) const
Definition Unit.h:755
uint32 HasUnitTypeMask(uint32 mask) const
Definition Unit.h:759
bool HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura=0) const
Definition Unit.cpp:774
CombatManager & GetCombatManager()
Definition Unit.h:1053
bool IsTotem() const
Definition Unit.h:765
virtual bool IsEngaged() const
Definition Unit.h:1049
virtual void SendMessageToSet(WorldPacket const *data, bool self) const
Definition Object.cpp:1099
Unit * GetOwner() const
Definition Object.cpp:1603
bool CanSeeOrDetect(WorldObject const *obj, CanSeeOrDetectExtraArgs const &args={ }) const
Definition Object.cpp:855
Player * GetSpellModOwner() const
Definition Object.cpp:1646
WorldPacket const * Write() override
WorldPacket const * Write() override
TC_GAME_API Unit * GetUnit(WorldObject const &, ObjectGuid const &guid)
auto MapGetValuePtr(M &map, typename M::key_type const &key)
Definition MapUtils.h:37
STL namespace.