forked from mangoszero/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerbotAI.cpp
More file actions
1718 lines (1493 loc) · 46.6 KB
/
PlayerbotAI.cpp
File metadata and controls
1718 lines (1493 loc) · 46.6 KB
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "../botpch.h"
#include "PlayerbotMgr.h"
#include "playerbot.h"
#include "AiFactory.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "strategy/values/LastMovementValue.h"
#include "strategy/actions/LogLevelAction.h"
#include "strategy/values/LastSpellCastValue.h"
#include "LootObjectStack.h"
#include "PlayerbotAIConfig.h"
#include "PlayerbotAI.h"
#include "PlayerbotFactory.h"
#include "PlayerbotSecurity.h"
#include "Util.h"
using namespace ai;
using namespace std;
// Function declarations
vector<string>& split(const string &s, char delim, vector<string> &elems);
vector<string> split(const string &s, char delim);
char * strstri (string str1, string str2);
uint64 extractGuid(WorldPacket& packet);
/**
* Extracts the quest ID from a string.
* @param str The input string.
* @return The extracted quest ID.
*/
uint32 PlayerbotChatHandler::extractQuestId(string str)
{
char* source = (char*)str.c_str();
char* cId = ExtractKeyFromLink(&source,"Hquest");
return cId ? atol(cId) : 0;
}
/**
* Adds a packet handler for a specific opcode.
* @param opcode The opcode.
* @param handler The handler name.
*/
void PacketHandlingHelper::AddHandler(uint16 opcode, string handler)
{
handlers[opcode] = handler;
}
/**
* Handles packets using the provided ExternalEventHelper.
* @param helper The ExternalEventHelper instance.
*/
void PacketHandlingHelper::Handle(ExternalEventHelper &helper)
{
while (!queue.empty())
{
helper.HandlePacket(handlers, queue.top());
queue.pop();
}
}
/**
* Adds a packet to the queue for handling.
* @param packet The packet to add.
*/
void PacketHandlingHelper::AddPacket(const WorldPacket& packet)
{
if (handlers.find(packet.GetOpcode()) != handlers.end())
{
queue.push(WorldPacket(packet));
}
}
/**
* Default constructor for PlayerbotAI.
*/
PlayerbotAI::PlayerbotAI() : PlayerbotAIBase(), bot(NULL), aiObjectContext(NULL),
currentEngine(NULL), chatHelper(this), chatFilter(this), accountId(0), security(NULL), master(NULL), currentState(BOT_STATE_NON_COMBAT),
m_eatingUntil(0), m_drinkingUntil(0),
m_isJumping(false), m_jumpStartTime(0),
m_jumpStartX(0.f), m_jumpStartY(0.f), m_jumpStartZ(0.f),
m_jumpSinAngle(0.f), m_jumpCosAngle(1.f), m_jumpXYSpeed(0.f),
m_pendingJump(false), m_jumpRequestTime(0),
m_jumpTargetX(0.f), m_jumpTargetY(0.f), m_jumpTargetZ(0.f), m_jumpTargetO(0.f)
{
for (int i = 0 ; i < BOT_STATE_MAX; i++)
{
engines[i] = NULL;
}
}
/**
* Constructor for PlayerbotAI with a bot parameter.
* @param bot The player bot.
*/
PlayerbotAI::PlayerbotAI(Player* bot) :
PlayerbotAIBase(), chatHelper(this), chatFilter(this), security(bot), master(NULL),
m_eatingUntil(0), m_drinkingUntil(0),
m_isJumping(false), m_jumpStartTime(0),
m_jumpStartX(0.f), m_jumpStartY(0.f), m_jumpStartZ(0.f),
m_jumpSinAngle(0.f), m_jumpCosAngle(1.f), m_jumpXYSpeed(0.f),
m_pendingJump(false), m_jumpRequestTime(0),
m_jumpTargetX(0.f), m_jumpTargetY(0.f), m_jumpTargetZ(0.f), m_jumpTargetO(0.f)
{
this->bot = bot;
accountId = sObjectMgr.GetPlayerAccountIdByGUID(bot->GetObjectGuid());
aiObjectContext = AiFactory::createAiObjectContext(bot, this);
engines[BOT_STATE_COMBAT] = AiFactory::createCombatEngine(bot, this, aiObjectContext);
engines[BOT_STATE_NON_COMBAT] = AiFactory::createNonCombatEngine(bot, this, aiObjectContext);
engines[BOT_STATE_DEAD] = AiFactory::createDeadEngine(bot, this, aiObjectContext);
currentEngine = engines[BOT_STATE_NON_COMBAT];
currentState = BOT_STATE_NON_COMBAT;
//masterIncomingPacketHandlers.AddHandler(CMSG_GAMEOBJ_REPORT_USE, "use game object");
masterIncomingPacketHandlers.AddHandler(CMSG_AREATRIGGER, "area trigger");
masterIncomingPacketHandlers.AddHandler(CMSG_GAMEOBJ_USE, "use game object");
masterIncomingPacketHandlers.AddHandler(CMSG_LOOT_ROLL, "loot roll");
masterIncomingPacketHandlers.AddHandler(CMSG_GOSSIP_HELLO, "gossip hello");
masterIncomingPacketHandlers.AddHandler(CMSG_QUESTGIVER_HELLO, "gossip hello");
masterIncomingPacketHandlers.AddHandler(CMSG_QUESTGIVER_COMPLETE_QUEST, "complete quest");
masterIncomingPacketHandlers.AddHandler(CMSG_QUESTGIVER_ACCEPT_QUEST, "accept quest");
masterIncomingPacketHandlers.AddHandler(CMSG_ACTIVATETAXI, "activate taxi");
masterIncomingPacketHandlers.AddHandler(CMSG_ACTIVATETAXIEXPRESS, "activate taxi");
masterIncomingPacketHandlers.AddHandler(CMSG_MOVE_SPLINE_DONE, "taxi done");
masterIncomingPacketHandlers.AddHandler(CMSG_GROUP_UNINVITE_GUID, "uninvite");
masterIncomingPacketHandlers.AddHandler(CMSG_PUSHQUESTTOPARTY, "quest share");
masterIncomingPacketHandlers.AddHandler(CMSG_GUILD_INVITE, "guild invite");
botOutgoingPacketHandlers.AddHandler(SMSG_GROUP_INVITE, "group invite");
botOutgoingPacketHandlers.AddHandler(BUY_ERR_NOT_ENOUGHT_MONEY, "not enough money");
botOutgoingPacketHandlers.AddHandler(BUY_ERR_REPUTATION_REQUIRE, "not enough reputation");
botOutgoingPacketHandlers.AddHandler(SMSG_GROUP_SET_LEADER, "group set leader");
botOutgoingPacketHandlers.AddHandler(SMSG_FORCE_RUN_SPEED_CHANGE, "check mount state");
botOutgoingPacketHandlers.AddHandler(SMSG_RESURRECT_REQUEST, "resurrect request");
botOutgoingPacketHandlers.AddHandler(SMSG_INVENTORY_CHANGE_FAILURE, "cannot equip");
botOutgoingPacketHandlers.AddHandler(SMSG_TRADE_STATUS, "trade status");
botOutgoingPacketHandlers.AddHandler(SMSG_LOOT_RESPONSE, "loot response");
botOutgoingPacketHandlers.AddHandler(SMSG_QUESTUPDATE_ADD_KILL, "quest objective completed");
botOutgoingPacketHandlers.AddHandler(SMSG_ITEM_PUSH_RESULT, "item push result");
botOutgoingPacketHandlers.AddHandler(SMSG_PARTY_COMMAND_RESULT, "party command");
botOutgoingPacketHandlers.AddHandler(SMSG_CAST_FAILED, "cast failed");
botOutgoingPacketHandlers.AddHandler(SMSG_DUEL_REQUESTED, "duel requested");
//botOutgoingPacketHandlers.AddHandler(SMSG_LFG_ROLE_CHECK_UPDATE, "lfg role check");
//botOutgoingPacketHandlers.AddHandler(SMSG_LFG_PROPOSAL_UPDATE, "lfg proposal");
masterOutgoingPacketHandlers.AddHandler(SMSG_PARTY_COMMAND_RESULT, "party command");
masterOutgoingPacketHandlers.AddHandler(MSG_RAID_READY_CHECK, "ready check");
masterOutgoingPacketHandlers.AddHandler(MSG_RAID_READY_CHECK_FINISHED, "ready check finished");
}
/**
* Destructor for PlayerbotAI.
*/
PlayerbotAI::~PlayerbotAI()
{
for (int i = 0 ; i < BOT_STATE_MAX; i++)
{
if (engines[i])
{
delete engines[i];
}
}
if (aiObjectContext)
{
delete aiObjectContext;
}
}
static const float BOT_JUMP_VELOCITY = 7.9557f;
static const float BOT_JUMP_GRAVITY = 19.2911f;
void PlayerbotAI::RequestJump()
{
if (m_pendingJump || m_isJumping)
return;
Player* master = GetMaster();
if (!master)
return;
m_jumpTargetX = master->GetPositionX();
m_jumpTargetY = master->GetPositionY();
m_jumpTargetZ = master->GetPositionZ();
m_jumpTargetO = master->GetOrientation();
m_pendingJump = true;
m_jumpRequestTime = getMSTime();
}
void PlayerbotAI::StartJump(bool forward, float orientation)
{
if (m_isJumping || bot->IsDead())
return;
bot->GetMotionMaster()->Clear();
bot->GetMotionMaster()->MoveIdle();
m_jumpStartTime = getMSTime();
m_jumpStartX = bot->GetPositionX();
m_jumpStartY = bot->GetPositionY();
m_jumpStartZ = bot->GetPositionZ();
float o = (orientation >= 0.f) ? orientation : bot->GetOrientation();
m_jumpCosAngle = cosf(o);
m_jumpSinAngle = sinf(o);
m_jumpXYSpeed = forward ? bot->GetSpeed(MOVE_RUN) : 0.f;
m_isJumping = true;
bot->SetFallInformation(0, m_jumpStartZ);
bot->m_movementInfo.SetMovementFlags(MOVEFLAG_FALLING);
if (forward)
bot->m_movementInfo.AddMovementFlag(MOVEFLAG_FORWARD);
bot->m_movementInfo.SetFallTime(0);
bot->m_movementInfo.SetJumpInfo(-BOT_JUMP_VELOCITY, m_jumpCosAngle, m_jumpSinAngle, m_jumpXYSpeed);
bot->m_movementInfo.ChangePosition(m_jumpStartX, m_jumpStartY, m_jumpStartZ, o);
bot->m_movementInfo.UpdateTime(m_jumpStartTime);
WorldPacket data(MSG_MOVE_JUMP, 64);
data << bot->GetPackGUID();
bot->m_movementInfo.Write(data);
bot->SendMessageToSet(&data, false);
}
void PlayerbotAI::UpdateJump()
{
if (m_pendingJump && !m_isJumping)
{
if (getMSTime() - m_jumpRequestTime > 10000)
{
m_pendingJump = false;
}
else
{
float dx = m_jumpTargetX - bot->GetPositionX();
float dy = m_jumpTargetY - bot->GetPositionY();
float dist2d = sqrtf(dx * dx + dy * dy);
if (dist2d <= 0.5f)
{
m_pendingJump = false;
StartJump(true, m_jumpTargetO);
}
else
{
bot->GetMotionMaster()->MovePoint(0, m_jumpTargetX, m_jumpTargetY, m_jumpTargetZ);
}
}
return;
}
if (!m_isJumping)
return;
uint32 now = getMSTime();
uint32 fallTimeMs = now - m_jumpStartTime;
float t = fallTimeMs / 1000.f;
float z = m_jumpStartZ + BOT_JUMP_VELOCITY * t - 0.5f * BOT_JUMP_GRAVITY * t * t;
float x = m_jumpStartX + m_jumpCosAngle * m_jumpXYSpeed * t;
float y = m_jumpStartY + m_jumpSinAngle * m_jumpXYSpeed * t;
float maxDuration = 2.f * BOT_JUMP_VELOCITY / BOT_JUMP_GRAVITY * 1000.f + 100.f;
bool landed = fallTimeMs > 200 && ((z <= m_jumpStartZ + 0.05f) || (float(fallTimeMs) >= maxDuration));
bot->m_movementInfo.UpdateTime(now);
bot->m_movementInfo.SetFallTime(fallTimeMs);
bot->m_movementInfo.ChangePosition(x, y, z, bot->GetOrientation());
if (landed)
{
m_isJumping = false;
float landZ = m_jumpStartZ;
if (Map* map = bot->GetMap())
{
float terrainZ = map->GetHeight(x, y, z > m_jumpStartZ ? z : m_jumpStartZ);
if (terrainZ > INVALID_HEIGHT)
landZ = terrainZ;
}
bot->m_movementInfo.RemoveMovementFlag(MovementFlags(MOVEFLAG_FALLING | MOVEFLAG_FORWARD));
bot->m_movementInfo.ChangePosition(x, y, landZ, bot->GetOrientation());
WorldPacket data(MSG_MOVE_FALL_LAND, 64);
data << bot->GetPackGUID();
bot->m_movementInfo.Write(data);
bot->SendMessageToSet(&data, false);
bot->SetFallInformation(fallTimeMs, landZ);
bot->GetMotionMaster()->Clear();
bot->GetMotionMaster()->MoveIdle();
bot->GetMap()->PlayerRelocation(bot, x, y, landZ, bot->GetOrientation());
}
}
void PlayerbotAI::UpdateAI(uint32 elapsed)
{
if (bot->IsBeingTeleported())
{
return;
}
if (nextAICheckDelay > sPlayerbotAIConfig.globalCoolDown &&
bot->IsNonMeleeSpellCasted(true, true, false) &&
*GetAiObjectContext()->GetValue<bool>("invalid target", "current target"))
{
Spell* spell = bot->GetCurrentSpell(CURRENT_GENERIC_SPELL);
if (spell && !IsPositiveSpell(spell->m_spellInfo))
{
InterruptSpell();
SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown);
}
}
if (nextAICheckDelay > sPlayerbotAIConfig.maxWaitForMove &&
!bot->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
{
if (bot->IsInCombat())
nextAICheckDelay = sPlayerbotAIConfig.maxWaitForMove;
else
{
Player* master = GetMaster();
if (master && master->IsInCombat())
{
InterruptSpell();
nextAICheckDelay = sPlayerbotAIConfig.maxWaitForMove;
}
}
}
if (m_drinkingUntil || m_eatingUntil)
{
if (bot->IsInCombat() || !bot->IsSitState())
{
m_drinkingUntil = 0;
m_eatingUntil = 0;
}
}
if (m_isJumping || m_pendingJump)
UpdateJump();
PlayerbotAIBase::UpdateAI(elapsed);
}
void PlayerbotAI::UpdateAIInternal(uint32 elapsed)
{
ExternalEventHelper helper(aiObjectContext);
while (!chatCommands.empty())
{
ChatCommandHolder holder = chatCommands.top();
string command = holder.GetCommand();
Player* owner = holder.GetOwner();
if (!helper.ParseChatCommand(command, owner) && holder.GetType() == CHAT_MSG_WHISPER)
{
ostringstream out; out << "Unknown command " << command;
TellMaster(out);
helper.ParseChatCommand("help");
}
chatCommands.pop();
}
botOutgoingPacketHandlers.Handle(helper);
masterIncomingPacketHandlers.Handle(helper);
masterOutgoingPacketHandlers.Handle(helper);
DoNextAction();
}
/**
* Handles teleport acknowledgment for the bot.
*/
void PlayerbotAI::HandleTeleportAck()
{
bot->GetMotionMaster()->Clear(true);
if (bot->IsBeingTeleportedNear())
{
WorldPacket p = WorldPacket(MSG_MOVE_TELEPORT_ACK, 8 + 4 + 4);
p << bot->GetObjectGuid();
p << (uint32)0; // supposed to be flags? not used currently
p << (uint32)time(0); // time - not currently used
bot->GetSession()->HandleMoveTeleportAckOpcode(p);
}
else if (bot->IsBeingTeleportedFar())
{
bot->GetSession()->HandleMoveWorldportAckOpcode();
}
LastMovement& movement = aiObjectContext->GetValue<LastMovement&>("last movement")->Get();
if (movement.lastFollowState)
{
ChangeStrategy("+follow master,-stay", BOT_STATE_NON_COMBAT);
movement.lastFollowState = false;
}
}
/**
* Resets the bot's state and strategies.
*/
void PlayerbotAI::Reset()
{
if (bot->IsTaxiFlying())
{
return;
}
currentEngine = engines[BOT_STATE_NON_COMBAT];
nextAICheckDelay = 0;
aiObjectContext->GetValue<Unit*>("old target")->Set(NULL);
aiObjectContext->GetValue<Unit*>("current target")->Set(NULL);
aiObjectContext->GetValue<LootObject>("loot target")->Set(LootObject());
aiObjectContext->GetValue<uint32>("lfg proposal")->Set(0);
LastSpellCast & lastSpell = aiObjectContext->GetValue<LastSpellCast& >("last spell cast")->Get();
lastSpell.Reset();
LastMovement & lastMovement = aiObjectContext->GetValue<LastMovement& >("last movement")->Get();
lastMovement.Set(NULL);
bot->GetMotionMaster()->Clear();
bot->m_taxi.ClearTaxiDestinations();
InterruptSpell();
for (int i = 0 ; i < BOT_STATE_MAX; i++)
{
engines[i]->Init();
}
}
/**
* Handles a command from the master.
* @param type The type of the command.
* @param text The command text.
* @param fromPlayer The player who sent the command.
*/
void PlayerbotAI::HandleCommand(uint32 type, const string& text, Player& fromPlayer)
{
if (!GetSecurity()->CheckLevelFor(PLAYERBOT_SECURITY_INVITE, type != CHAT_MSG_WHISPER, &fromPlayer))
{
return;
}
if (type == CHAT_MSG_ADDON)
{
return;
}
string filtered = text;
if (!sPlayerbotAIConfig.commandPrefix.empty())
{
if (filtered.find(sPlayerbotAIConfig.commandPrefix) != 0)
{
return;
}
filtered = filtered.substr(sPlayerbotAIConfig.commandPrefix.size());
}
filtered = chatFilter.Filter(trim((string&)filtered));
if (filtered.empty())
{
return;
}
if (filtered.find("who") != 0 && !GetSecurity()->CheckLevelFor(PLAYERBOT_SECURITY_ALLOW_ALL, type != CHAT_MSG_WHISPER, &fromPlayer))
{
return;
}
if (type == CHAT_MSG_RAID_WARNING && filtered.find(bot->GetName()) != string::npos && filtered.find("award") == string::npos)
{
ChatCommandHolder cmd("warning", &fromPlayer, type);
chatCommands.push(cmd);
return;
}
if (filtered.size() > 2 && filtered.substr(0, 2) == "d " || filtered.size() > 3 && filtered.substr(0, 3) == "do ")
{
std::string action = filtered.substr(filtered.find(" ") + 1);
DoSpecificAction(action);
}
else if (filtered == "reset")
{
Reset();
}
else
{
ChatCommandHolder cmd(filtered, &fromPlayer, type);
chatCommands.push(cmd);
}
}
/**
* Handles outgoing packets from the bot.
* @param packet The packet to handle.
*/
void PlayerbotAI::HandleBotOutgoingPacket(const WorldPacket& packet)
{
switch (packet.GetOpcode())
{
case SMSG_CAST_FAILED:
{
WorldPacket p(packet);
p.rpos(0);
uint8 status, result;
p >> status >> result;
if (result != SPELL_CAST_OK)
{
LastSpellCast& lastSpell = aiObjectContext->GetValue<LastSpellCast&>("last spell cast")->Get();
SpellInterrupted(lastSpell.id);
botOutgoingPacketHandlers.AddPacket(packet);
}
return;
}
case SMSG_SPELL_FAILURE:
{
WorldPacket p(packet);
p.rpos(0);
ObjectGuid casterGuid;
p >> casterGuid.ReadAsPacked();
if (casterGuid != bot->GetObjectGuid())
{
return;
}
uint32 spellId;
p >> spellId;
SpellInterrupted(spellId);
return;
}
case SMSG_SPELL_DELAYED:
{
WorldPacket p(packet);
p.rpos(0);
ObjectGuid casterGuid;
p >> casterGuid.ReadAsPacked();
if (casterGuid != bot->GetObjectGuid())
{
return;
}
uint32 delaytime;
p >> delaytime;
if (delaytime <= 1000)
{
IncreaseNextCheckDelay(delaytime);
}
return;
}
default:
botOutgoingPacketHandlers.AddPacket(packet);
}
}
/**
* Handles spell interruption for the bot.
* @param spellid The ID of the interrupted spell.
*/
void PlayerbotAI::SpellInterrupted(uint32 spellid)
{
if (!spellid)
return;
LastSpellCast& lastSpell = aiObjectContext->GetValue<LastSpellCast&>("last spell cast")->Get();
if (lastSpell.id != spellid)
{
return;
}
lastSpell.Reset();
time_t now = time(0);
if (now <= lastSpell.time)
{
return;
}
uint32 castTimeSpent = 1000 * (now - lastSpell.time);
uint32 globalCooldown = CalculateGlobalCooldown(lastSpell.id);
if (castTimeSpent < globalCooldown)
{
SetNextCheckDelay(globalCooldown - castTimeSpent);
}
else
{
SetNextCheckDelay(0);
}
lastSpell.id = 0;
}
/**
* Calculates the global cooldown for a spell.
* @param spellid The ID of the spell.
* @return The global cooldown in milliseconds.
*/
uint32 PlayerbotAI::CalculateGlobalCooldown(uint32 spellid)
{
if (!spellid)
{
return 0;
}
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid );
if (bot->GetGlobalCooldownMgr().HasGlobalCooldown(spellInfo))
{
return sPlayerbotAIConfig.globalCoolDown;
}
return sPlayerbotAIConfig.reactDelay;
}
/**
* Handles incoming packets from the master.
* @param packet The packet to handle.
*/
void PlayerbotAI::HandleMasterIncomingPacket(const WorldPacket& packet)
{
masterIncomingPacketHandlers.AddPacket(packet);
}
/**
* Handles outgoing packets to the master.
* @param packet The packet to handle.
*/
void PlayerbotAI::HandleMasterOutgoingPacket(const WorldPacket& packet)
{
masterOutgoingPacketHandlers.AddPacket(packet);
}
/**
* Changes the current engine to the specified type.
* @param type The type of the engine.
*/
void PlayerbotAI::ChangeEngine(BotState type)
{
Engine* engine = engines[type];
if (currentEngine != engine)
{
currentEngine = engine;
currentState = type;
ReInitCurrentEngine();
switch (type)
{
case BOT_STATE_COMBAT:
sLog.outDebug("=== %s COMBAT ===", bot->GetName());
break;
case BOT_STATE_NON_COMBAT:
sLog.outDebug("=== %s NON-COMBAT ===", bot->GetName());
break;
case BOT_STATE_DEAD:
sLog.outDebug("=== %s DEAD ===", bot->GetName());
break;
}
}
}
/**
* Executes the next action for the bot.
*/
void PlayerbotAI::DoNextAction()
{
if (bot->IsBeingTeleported() /*|| bot->IsBeingTeleportedDelayEvent()*/|| (GetMaster() && GetMaster()->IsBeingTeleported()))
{
return;
}
currentEngine->DoNextAction(NULL);
/*if (!bot->GetAurasByType(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED).empty())
{
bot->m_movementInfo.SetMovementFlags((MovementFlags)(MOVEFLAG_FLYING|MOVEFLAG_CAN_FLY));
WorldPacket packet(CMSG_MOVE_SET_FLY);
packet << bot->GetObjectGuid().WriteAsPacked();
packet << bot->m_movementInfo;
bot->SetMover(bot);
bot->GetSession()->HandleMovementOpcodes(packet);
}*/
Player* master = GetMaster();
if (bot->IsMounted() && bot->IsFlying())
{
bot->m_movementInfo.SetMovementFlags((MovementFlags)(MOVEFLAG_FLYING|MOVEFLAG_CAN_FLY));
//bot->SetSpeedRate(MOVE_FLIGHT, 1.0f, true);
bot->SetSpeedRate(MOVE_RUN, 1.0f, true);
if (master)
{
//bot->SetSpeedRate(MOVE_FLIGHT, master->GetSpeedRate(MOVE_FLIGHT), true);
//bot->SetSpeedRate(MOVE_RUN, master->GetSpeedRate(MOVE_FLIGHT), true);
}
}
if (currentEngine != engines[BOT_STATE_DEAD] && !bot->IsAlive())
{
ChangeEngine(BOT_STATE_DEAD);
}
if (currentEngine == engines[BOT_STATE_DEAD] && bot->IsAlive())
{
ChangeEngine(BOT_STATE_NON_COMBAT);
}
Group *group = bot->GetGroup();
if (!master && group)
{
for (GroupReference *gref = group->GetFirstMember(); gref; gref = gref->next())
{
Player* member = gref->getSource();
PlayerbotAI* ai = bot->GetPlayerbotAI();
if (member && member->IsInWorld() && !member->GetPlayerbotAI() && (!master || master->GetPlayerbotAI()))
{
ai->SetMaster(member);
ai->ResetStrategies();
ai->TellMaster("Hello");
break;
}
}
}
}
/**
* Reinitializes the current engine.
*/
void PlayerbotAI::ReInitCurrentEngine()
{
InterruptSpell();
currentEngine->Init();
}
/**
* Changes the strategy for the specified engine type.
* @param names The names of the strategies.
* @param type The type of the engine.
*/
void PlayerbotAI::ChangeStrategy(string names, BotState type)
{
Engine* e = engines[type];
if (!e)
{
return;
}
e->ChangeStrategy(names);
}
/**
* Executes a specific action for the bot.
* @param name The name of the action.
*/
void PlayerbotAI::DoSpecificAction(string name)
{
for (int i = 0 ; i < BOT_STATE_MAX; i++)
{
ostringstream out;
ActionResult res = engines[i]->ExecuteAction(name);
switch (res)
{
case ACTION_RESULT_UNKNOWN:
continue;
case ACTION_RESULT_OK:
out << name << ": done";
TellMaster(out);
return;
case ACTION_RESULT_IMPOSSIBLE:
out << name << ": impossible";
TellMaster(out);
return;
case ACTION_RESULT_USELESS:
out << name << ": useless";
TellMaster(out);
return;
case ACTION_RESULT_FAILED:
out << name << ": failed";
TellMaster(out);
return;
}
}
ostringstream out;
out << name << ": unknown action";
TellMaster(out);
}
/**
* Checks if the bot contains a specific strategy.
* @param type The type of the strategy.
* @return True if the strategy is contained, false otherwise.
*/
bool PlayerbotAI::ContainsStrategy(StrategyType type)
{
for (int i = 0 ; i < BOT_STATE_MAX; i++)
{
if (engines[i]->ContainsStrategy(type))
{
return true;
}
}
return false;
}
/**
* Checks if the bot has a specific strategy.
* @param name The name of the strategy.
* @param type The type of the engine.
* @return True if the strategy is present, false otherwise.
*/
bool PlayerbotAI::HasStrategy(string name, BotState type)
{
return engines[type]->HasStrategy(name);
}
/**
* Resets the strategies for the bot.
*/
void PlayerbotAI::ResetStrategies()
{
for (int i = 0 ; i < BOT_STATE_MAX; i++)
{
engines[i]->removeAllStrategies();
}
AiFactory::AddDefaultCombatStrategies(bot, this, engines[BOT_STATE_COMBAT]);
AiFactory::AddDefaultNonCombatStrategies(bot, this, engines[BOT_STATE_NON_COMBAT]);
AiFactory::AddDefaultDeadStrategies(bot, this, engines[BOT_STATE_DEAD]);
}
/**
* Checks if the player is a ranged class.
* @param player The player to check.
* @return True if the player is a ranged class, false otherwise.
*/
bool PlayerbotAI::IsRanged(Player* player)
{
PlayerbotAI* botAi = player->GetPlayerbotAI();
if (botAi)
{
return botAi->ContainsStrategy(STRATEGY_TYPE_RANGED);
}
switch (player->getClass())
{
//case CLASS_DEATH_KNIGHT:
case CLASS_PALADIN:
case CLASS_WARRIOR:
case CLASS_ROGUE:
return false;
case CLASS_DRUID:
return !HasAnyAuraOf(player, "cat form", "bear form", "dire bear form", NULL);
}
return true;
}
/**
* Checks if the player is a tank class.
* @param player The player to check.
* @return True if the player is a tank class, false otherwise.
*/
bool PlayerbotAI::IsTank(Player* player)
{
PlayerbotAI* botAi = player->GetPlayerbotAI();
if (botAi)
{
return botAi->ContainsStrategy(STRATEGY_TYPE_TANK);
}
switch (player->getClass())
{
//case CLASS_DEATH_KNIGHT:
case CLASS_PALADIN:
case CLASS_WARRIOR:
return true;
case CLASS_DRUID:
return HasAnyAuraOf(player, "bear form", "dire bear form", NULL);
}
return false;
}
/**
* Checks if the player is a healer class.
* @param player The player to check.
* @return True if the player is a healer class, false otherwise.
*/
bool PlayerbotAI::IsHeal(Player* player)
{
PlayerbotAI* botAi = player->GetPlayerbotAI();
if (botAi)
{
return botAi->ContainsStrategy(STRATEGY_TYPE_HEAL);
}
switch (player->getClass())
{
case CLASS_PRIEST:
return true;
case CLASS_DRUID:
return HasAnyAuraOf(player, "tree of life form", NULL);
}
return false;
}
namespace MaNGOS
{
/**
* Checks if a unit is within range based on its GUID.
*/
class UnitByGuidInRangeCheck
{
public:
UnitByGuidInRangeCheck(WorldObject const* obj, ObjectGuid guid, float range) : i_obj(obj), i_range(range), i_guid(guid) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
return u->GetObjectGuid() == i_guid && i_obj->IsWithinDistInMap(u, i_range);
}
private:
WorldObject const* i_obj;
float i_range;
ObjectGuid i_guid;
};
/**
* Checks if a game object is within range based on its GUID.
*/
class GameObjectByGuidInRangeCheck
{
public:
GameObjectByGuidInRangeCheck(WorldObject const* obj, ObjectGuid guid, float range) : i_obj(obj), i_range(range), i_guid(guid) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(GameObject* u)
{
if (u && i_obj->IsWithinDistInMap(u, i_range) && u->isSpawned() && u->GetGOInfo() && u->GetObjectGuid() == i_guid)
{
return true;
}
return false;
}
private:
WorldObject const* i_obj;
float i_range;
ObjectGuid i_guid;
};
};
/**
* Retrieves a unit based on its GUID.
* @param guid The GUID of the unit.
* @return The unit, or NULL if not found.
*/
Unit* PlayerbotAI::GetUnit(ObjectGuid guid)
{
if (!guid)
{
return NULL;
}
list<Unit*> targets;
MaNGOS::UnitByGuidInRangeCheck u_check(bot, guid, sPlayerbotAIConfig.sightDistance);
MaNGOS::UnitListSearcher<MaNGOS::UnitByGuidInRangeCheck> searcher(targets, u_check);
Cell::VisitAllObjects(bot, searcher, sPlayerbotAIConfig.sightDistance);
if (targets.empty())
{
return NULL;
}
return *targets.begin();
}
/**
* Retrieves a creature based on its GUID.
* @param guid The GUID of the creature.
* @return The creature, or NULL if not found.
*/
Creature* PlayerbotAI::GetCreature(ObjectGuid guid)
{
if (!guid)
{
return NULL;
}
list<Unit *> targets;