1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
|
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CreatureAI.h"
#include "AreaBoundary.h"
#include "Containers.h"
#include "Creature.h"
#include "CreatureAIImpl.h"
#include "CreatureTextMgr.h"
#include "DB2Structure.h"
#include "Errors.h"
#include "Language.h"
#include "Log.h"
#include "Map.h"
#include "MapReference.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "Player.h"
#include "SpellHistory.h"
#include "TemporarySummon.h"
#include "Vehicle.h"
std::unordered_map<std::pair<uint32, Difficulty>, AISpellInfoType> UnitAI::AISpellInfo;
AISpellInfoType* GetAISpellInfo(uint32 spellId, Difficulty difficulty)
{
return Trinity::Containers::MapGetValuePtr(UnitAI::AISpellInfo, { spellId, difficulty });
}
CreatureAI::CreatureAI(Creature* creature, uint32 scriptId)
: UnitAI(creature), me(creature), _boundary(nullptr),
_negateBoundary(false), _scriptId(scriptId ? scriptId : creature->GetScriptId()), _isEngaged(false), _moveInLOSLocked(false)
{
ASSERT(_scriptId, "A CreatureAI was initialized with an invalid scriptId!");
}
CreatureAI::~CreatureAI()
{
}
void CreatureAI::Talk(uint8 id, WorldObject const* whisperTarget /*= nullptr*/)
{
sCreatureTextMgr->SendChat(me, id, whisperTarget);
}
// Disable CreatureAI when charmed
void CreatureAI::OnCharmed(bool isNew)
{
if (isNew && !me->IsCharmed() && !me->LastCharmerGUID.IsEmpty())
{
if (!me->HasReactState(REACT_PASSIVE))
{
if (Unit* lastCharmer = ObjectAccessor::GetUnit(*me, me->LastCharmerGUID))
me->EngageWithTarget(lastCharmer);
}
me->LastCharmerGUID.Clear();
if (!me->IsInCombat())
EnterEvadeMode(EVADE_REASON_NO_HOSTILES);
}
UnitAI::OnCharmed(isNew);
}
void CreatureAI::DoZoneInCombat(Creature* creature /*= nullptr*/)
{
if (!creature)
creature = me;
Map* map = creature->GetMap();
if (!map->IsDungeon()) // use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated
{
TC_LOG_ERROR("scripts.ai", "CreatureAI::DoZoneInCombat: call for map that isn't an instance (%s)", creature->GetGUID().ToString().c_str());
return;
}
if (!map->HavePlayers())
return;
for (MapReference const& ref : map->GetPlayers())
{
if (Player* player = ref.GetSource())
{
if (!player->IsAlive() || !CombatManager::CanBeginCombat(creature, player))
continue;
creature->EngageWithTarget(player);
for (Unit* pet : player->m_Controlled)
creature->EngageWithTarget(pet);
if (Unit* vehicle = player->GetVehicleBase())
creature->EngageWithTarget(vehicle);
}
}
}
// scripts does not take care about MoveInLineOfSight loops
// MoveInLineOfSight can be called inside another MoveInLineOfSight and cause stack overflow
void CreatureAI::MoveInLineOfSight_Safe(Unit* who)
{
if (_moveInLOSLocked == true)
return;
_moveInLOSLocked = true;
MoveInLineOfSight(who);
_moveInLOSLocked = false;
}
void CreatureAI::MoveInLineOfSight(Unit* who)
{
if (me->IsEngaged())
return;
if (me->HasReactState(REACT_AGGRESSIVE) && me->CanStartAttack(who, false))
me->EngageWithTarget(who);
}
void CreatureAI::OnOwnerCombatInteraction(Unit* target)
{
if (!target || !me->IsAlive())
return;
if (!me->HasReactState(REACT_PASSIVE) && me->CanStartAttack(target, true))
me->EngageWithTarget(target);
}
// Distract creature, if player gets too close while stealthed/prowling
void CreatureAI::TriggerAlert(Unit const* who) const
{
// If there's no target, or target isn't a player do nothing
if (!who || who->GetTypeId() != TYPEID_PLAYER)
return;
// 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!
if (me->IsCivilian() || me->HasReactState(REACT_PASSIVE) || !me->IsHostileTo(who) || !me->_IsTargetAcceptable(who))
return;
// Send alert sound (if any) for this creature
me->SendAIReaction(AI_REACTION_ALERT);
// Face the unit (stealthed player) and set distracted state for 5 seconds
me->GetMotionMaster()->MoveDistract(5 * IN_MILLISECONDS, me->GetAbsoluteAngle(who));
}
// adapted from logic in Spell:EffectSummonType before commit 8499434
static bool ShouldFollowOnSpawn(SummonPropertiesEntry const* properties)
{
// Summons without SummonProperties are generally scripted summons that don't belong to any owner
if (!properties)
return false;
switch (properties->Control)
{
case SUMMON_CATEGORY_PET:
return true;
case SUMMON_CATEGORY_WILD:
case SUMMON_CATEGORY_ALLY:
case SUMMON_CATEGORY_UNK:
if (properties->GetFlags().HasFlag(SummonPropertiesFlags::JoinSummonerSpawnGroup))
return true;
switch (SummonTitle(properties->Title))
{
case SummonTitle::Pet:
case SummonTitle::Guardian:
case SummonTitle::Runeblade:
case SummonTitle::Minion:
case SummonTitle::Companion:
return true;
default:
return false;
}
default:
return false;
}
}
void CreatureAI::JustAppeared()
{
if (!IsEngaged())
{
if (TempSummon* summon = me->ToTempSummon())
{
// Only apply this to specific types of summons
if (!summon->GetVehicle() && ShouldFollowOnSpawn(summon->m_Properties) && summon->CanFollowOwner())
{
if (Unit* owner = summon->GetCharmerOrOwner())
{
summon->GetMotionMaster()->Clear();
summon->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, summon->GetFollowAngle());
}
}
}
}
}
void CreatureAI::JustEnteredCombat(Unit* who)
{
if (!IsEngaged() && !me->CanHaveThreatList())
EngagementStart(who);
}
void CreatureAI::EnterEvadeMode(EvadeReason why)
{
if (!_EnterEvadeMode(why))
return;
TC_LOG_DEBUG("scripts.ai", "CreatureAI::EnterEvadeMode: entering evade mode (why: %u) (%s)", why, me->GetGUID().ToString().c_str());
if (!me->GetVehicle()) // otherwise me will be in evade mode forever
{
if (Unit* owner = me->GetCharmerOrOwner())
{
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle());
}
else
{
// Required to prevent attacking creatures that are evading and cause them to reenter combat
// Does not apply to MoveFollow
me->AddUnitState(UNIT_STATE_EVADE);
me->GetMotionMaster()->MoveTargetedHome();
}
}
Reset();
}
bool CreatureAI::UpdateVictim()
{
if (!IsEngaged())
return false;
if (!me->IsAlive())
{
EngagementOver();
return false;
}
if (!me->HasReactState(REACT_PASSIVE))
{
if (Unit* victim = me->SelectVictim())
if (victim != me->GetVictim())
AttackStart(victim);
return me->GetVictim() != nullptr;
}
else if (!me->IsInCombat())
{
EnterEvadeMode(EVADE_REASON_NO_HOSTILES);
return false;
}
else if (me->GetVictim())
me->AttackStop();
return true;
}
void CreatureAI::EngagementStart(Unit* who)
{
if (_isEngaged)
{
TC_LOG_ERROR("scripts.ai", "CreatureAI::EngagementStart called even though creature is already engaged. Creature debug info:\n%s", me->GetDebugInfo().c_str());
return;
}
_isEngaged = true;
me->AtEngage(who);
}
void CreatureAI::EngagementOver()
{
if (!_isEngaged)
{
TC_LOG_DEBUG("scripts.ai", "CreatureAI::EngagementOver called even though creature is not currently engaged. Creature debug info:\n%s", me->GetDebugInfo().c_str());
return;
}
_isEngaged = false;
me->AtDisengage();
}
bool CreatureAI::_EnterEvadeMode(EvadeReason /*why*/)
{
if (me->IsInEvadeMode())
return false;
if (!me->IsAlive())
{
EngagementOver();
return false;
}
me->RemoveAurasOnEvade();
me->CombatStop(true);
me->SetTappedBy(nullptr);
me->ResetPlayerDamageReq();
me->SetLastDamagedTime(0);
me->SetCannotReachTarget(false);
me->DoNotReacquireSpellFocusTarget();
me->SetTarget(ObjectGuid::Empty);
me->GetSpellHistory()->ResetAllCooldowns();
EngagementOver();
return true;
}
Optional<QuestGiverStatus> CreatureAI::GetDialogStatus(Player* /*player*/)
{
return {};
}
const uint32 BOUNDARY_VISUALIZE_CREATURE = 15425;
const float BOUNDARY_VISUALIZE_CREATURE_SCALE = 0.25f;
const int8 BOUNDARY_VISUALIZE_STEP_SIZE = 1;
const int32 BOUNDARY_VISUALIZE_FAILSAFE_LIMIT = 750;
const float BOUNDARY_VISUALIZE_SPAWN_HEIGHT = 5.0f;
int32 CreatureAI::VisualizeBoundary(Seconds duration, Unit* owner, bool fill) const
{
typedef std::pair<int32, int32> coordinate;
if (!owner)
return -1;
if (!_boundary || _boundary->empty())
return LANG_CREATURE_MOVEMENT_NOT_BOUNDED;
std::queue<coordinate> Q;
std::unordered_set<coordinate> alreadyChecked;
std::unordered_set<coordinate> outOfBounds;
Position startPosition = owner->GetPosition();
if (!IsInBoundary(&startPosition)) // fall back to creature position
{
startPosition = me->GetPosition();
if (!IsInBoundary(&startPosition)) // fall back to creature home position
{
startPosition = me->GetHomePosition();
if (!IsInBoundary(&startPosition))
return LANG_CREATURE_NO_INTERIOR_POINT_FOUND;
}
}
float spawnZ = startPosition.GetPositionZ() + BOUNDARY_VISUALIZE_SPAWN_HEIGHT;
bool boundsWarning = false;
Q.push({ 0,0 });
while (!Q.empty())
{
coordinate front = Q.front();
bool hasOutOfBoundsNeighbor = false;
for (coordinate const& off : std::list<coordinate>{ {1, 0}, {0, 1}, {-1, 0}, {0, -1} })
{
coordinate next(front.first + off.first, front.second + off.second);
if (next.first > BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.first < -BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.second > BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.second < -BOUNDARY_VISUALIZE_FAILSAFE_LIMIT)
{
boundsWarning = true;
continue;
}
if (alreadyChecked.find(next) == alreadyChecked.end()) // never check a coordinate twice
{
Position nextPos(startPosition.GetPositionX() + next.first*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionY() + next.second*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionZ());
if (IsInBoundary(&nextPos))
Q.push(next);
else
{
outOfBounds.insert(next);
hasOutOfBoundsNeighbor = true;
}
alreadyChecked.insert(next);
}
else if (outOfBounds.find(next) != outOfBounds.end())
hasOutOfBoundsNeighbor = true;
}
if (fill || hasOutOfBoundsNeighbor)
{
if (TempSummon* point = owner->SummonCreature(BOUNDARY_VISUALIZE_CREATURE, Position(startPosition.GetPositionX() + front.first * BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionY() + front.second * BOUNDARY_VISUALIZE_STEP_SIZE, spawnZ), TEMPSUMMON_TIMED_DESPAWN, duration))
{
point->SetObjectScale(BOUNDARY_VISUALIZE_CREATURE_SCALE);
point->SetUnitFlag(UNIT_FLAG_STUNNED);
point->SetImmuneToAll(true);
if (!hasOutOfBoundsNeighbor)
point->SetUnitFlag(UNIT_FLAG_UNINTERACTIBLE);
}
}
Q.pop();
}
return boundsWarning ? LANG_CREATURE_MOVEMENT_MAYBE_UNBOUNDED : 0;
}
bool CreatureAI::IsInBoundary(Position const* who) const
{
if (!_boundary)
return true;
if (!who)
who = me;
return CreatureAI::IsInBounds(*_boundary, who) != _negateBoundary;
}
bool CreatureAI::IsInBounds(CreatureBoundary const& boundary, Position const* pos)
{
for (AreaBoundary const* areaBoundary : boundary)
if (!areaBoundary->IsWithinBoundary(pos))
return false;
return true;
}
void CreatureAI::SetBoundary(CreatureBoundary const* boundary, bool negateBoundaries /*= false*/)
{
_boundary = boundary;
_negateBoundary = negateBoundaries;
me->DoImmediateBoundaryCheck();
}
bool CreatureAI::CheckInRoom()
{
if (IsInBoundary())
return true;
else
{
EnterEvadeMode(EVADE_REASON_BOUNDARY);
return false;
}
}
Creature* CreatureAI::DoSummon(uint32 entry, Position const& pos, Milliseconds despawnTime, TempSummonType summonType)
{
return me->SummonCreature(entry, pos, summonType, despawnTime);
}
Creature* CreatureAI::DoSummon(uint32 entry, WorldObject* obj, float radius, Milliseconds despawnTime, TempSummonType summonType)
{
Position pos = obj->GetRandomNearPosition(radius);
return me->SummonCreature(entry, pos, summonType, despawnTime);
}
Creature* CreatureAI::DoSummonFlyer(uint32 entry, WorldObject* obj, float flightZ, float radius, Milliseconds despawnTime, TempSummonType summonType)
{
Position pos = obj->GetRandomNearPosition(radius);
pos.m_positionZ += flightZ;
return me->SummonCreature(entry, pos, summonType, despawnTime);
}
|