-
Notifications
You must be signed in to change notification settings - Fork 0
/
VL_foxBot.lua
4858 lines (4514 loc) · 139 KB
/
VL_foxBot.lua
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
--[[
foxBot v1.7 by fox: https://taraxis.com/foxBot-SRB2
Based heavily on VL_ExAI-v2.lua by CobaltBW: https://mb.srb2.org/showthread.php?t=46020
Initially an experiment to run bots off of PreThinkFrame instead of BotTiccmd
This allowed AI to control a real player for use in netgames etc.
Since they're no longer "bots" to the game, it integrates a few concepts from ClassicCoop-v1.3.lua by FuriousFox: https://mb.srb2.org/showthread.php?t=41377
Such as ring-sharing, nullifying damage, etc. to behave more like a true SP bot, as player.bot is read-only
Future TODO?
* Avoid inturrupting players/bots carrying other players/bots due to flying too close
(need to figure out a good way to detect if we're carrying someone)
* Modular rewrite, defining behaviors on hashed functions - this would allow:
* Mod support - AI hooks / overrides for targeting, ability rules, etc.
* Gametype support - definable goals based on current game mode
* Better abstractions - no more monolithic mess / derpy leader system
* Other things to improve your life immeasurably
* "Bounce" detection flag based on leader's last momentum?
* Would increase abil threshold, allowing Tails etc. to bounce with leader better
* Register fallback convars in case of conflicts? For buddyex compatibility etc.
--------------------------------------------------------------------------------
Copyright (c) 2023 Alex Strout and Claire Ellis
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
--[[
--------------------------------------------------------------------------------
GLOBAL CONVARS
(see "bothelp" at bottom for a description of each)
--------------------------------------------------------------------------------
]]
local CV_MaxPlayers = CV_FindVar("maxplayers")
local CV_CoopStarposts = CV_FindVar("coopstarposts")
local CV_ExAI = CV_RegisterVar({
name = "ai_sys",
defaultvalue = "On",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = CV_OnOff
})
local CV_AIDebug = CV_RegisterVar({
name = "ai_debug",
defaultvalue = "-1",
flags = 0,
PossibleValue = {MIN = -1, MAX = 31}
})
local CV_AISeekDist = CV_RegisterVar({
name = "ai_seekdist",
defaultvalue = "512",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {MIN = 64, MAX = 1536}
})
local CV_AIIgnore = CV_RegisterVar({
name = "ai_ignore",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {
Off = 0,
Enemies = 1,
RingsMonitors = 2,
All = 3
}
})
local CV_AICatchup = CV_RegisterVar({
name = "ai_catchup",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = CV_OnOff
})
local CV_AIKeepDisconnected = CV_RegisterVar({
name = "ai_keepdisconnected",
defaultvalue = "On",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = CV_OnOff
})
local CV_AIDefaultLeader = CV_RegisterVar({
name = "ai_defaultleader",
defaultvalue = "-1",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {MIN = -1, MAX = 32}
})
local CV_AIMaxBots = CV_RegisterVar({
name = "ai_maxbots",
defaultvalue = "2",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {MIN = 0, MAX = 32}
})
local CV_AIReserveSlot = CV_RegisterVar({
name = "ai_reserveslot",
defaultvalue = "On",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = CV_OnOff
})
local CV_AIHurtMode = CV_RegisterVar({
name = "ai_hurtmode",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {
Off = 0,
ShieldLoss = 1,
RingLoss = 2
}
})
local CV_AIStatMode = CV_RegisterVar({
name = "ai_statmode",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {
Off = 0,
Rings = 1,
Lives = 2,
Both = 3
}
})
local CV_AITeleMode = CV_RegisterVar({
name = "ai_telemode",
defaultvalue = "0",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {MIN = 0, MAX = UINT16_MAX}
})
local CV_AIShowHud = CV_RegisterVar({
name = "ai_showhud",
defaultvalue = "On",
flags = 0,
PossibleValue = CV_OnOff
})
--[[
--------------------------------------------------------------------------------
GLOBAL TYPE DEFINITIONS
Defines any mobj types etc. needed by foxBot
--------------------------------------------------------------------------------
]]
freeslot(
"MT_FOXAI_POINT"
)
mobjinfo[MT_FOXAI_POINT] = {
spawnstate = S_INVISIBLE,
radius = FRACUNIT,
height = FRACUNIT,
--Sector clipping allowed to properly account for radius in floorz / ceilingz checks
flags = MF_NOGRAVITY|MF_NOTHINK|MF_NOCLIPTHING
}
--[[
--------------------------------------------------------------------------------
GLOBAL HELPER VALUES / FUNCTIONS
Used in various points throughout code
--------------------------------------------------------------------------------
]]
--Global MT_FOXAI_POINTs used in various functions
local PosCheckerObj = nil
--Global vars
local isspecialstage = leveltime and G_IsSpecialStage() --Also set on MapLoad
--NetVars!
addHook("NetVars", function(network)
PosCheckerObj = network($)
isspecialstage = network($)
end)
--Text table used for HUD hook
local hudtext = {}
--Return whether player has elevated privileges
local function IsAdmin(player)
return player == server
or (player and player.valid
and IsPlayerAdmin(player))
end
--Return whether player has authority over bot
local function IsAuthority(player, bot, strict)
return bot == player
or (IsAdmin(player) and not strict)
or (bot and bot.valid
and (bot.ai_owner == player
or (bot.ai and bot.ai.ronin
and bot.ai.realleader == player)))
end
--Return shortened player name
local function ShortName(player)
if string.len(player.name) > 10
return string.sub(player.name, 1, 10) .. ".."
end
return player.name
end
--Return player name without 2.2.11's colored [BOT] suffix
local function BotlessName(player)
local len = string.len(player.name) - 7
if string.sub(player.name, len + 1) == "\x84[BOT]\x80"
return string.sub(player.name, 1, len)
end
return player.name
end
--Return descriptive bot type
local function BotType(bot)
if bot.bot == BOT_MPAI
return "mp bot"
elseif bot.bot != BOT_NONE
return "2p bot"
end
return "bot"
end
--Return if bot is considered an "sp bot" (2p bot)
local function SPBot(bot)
return bot.bot and bot.bot != BOT_MPAI
end
--Resolve player by number (string or int)
local function ResolvePlayerByNum(num)
num = tonumber($)
if num != nil and num >= 0 and num < 32
return players[num]
end
return nil
end
--Resolve multiple players by string (or player by number)
local function ResolveMultiplePlayersByNum(player, num)
--Support "all" and "disconnect[ed/ing]" arguments
if type(num) == "string" --Double-check before using string lib
local b = string.lower(string.sub(num, 1, 10))
if b == "all" or b == "disconnect"
local ret = {}
for pbot in players.iterate
if IsAuthority(player, pbot)
and (
b == "all" or pbot.quittime
--Avoid dropping summoned bots w/ "disconnected"
or (pbot.ai and pbot.ai.ronin and not pbot.ai_owner)
)
table.insert(ret, #pbot)
end
end
return ret
end
end
--Plain old boring num
return ResolvePlayerByNum(num)
end
--Return number of connected players/bots
local function PlayerCount()
local pcount = 0
for _ in players.iterate
pcount = $ + 1
end
return pcount
end
--Returns absolute angle (0 to 180)
--Useful for comparing angles
local function AbsAngle(ang)
if ang < 0 and ang > ANGLE_180
return InvAngle(ang)
end
return ang
end
--Returns last (maxn) array element
local function TableLast(t)
return t[table.maxn(t)]
end
--Destroys mobj and returns nil for assignment shorthand
local function DestroyObj(mobj)
if mobj and mobj.valid
P_RemoveMobj(mobj)
end
return nil
end
--Moves specified poschecker to x, y, z coordinates, optionally with radius and height
--Useful for checking floorz/ceilingz or other properties at some arbitrary point in space
local function CheckPos(poschecker, x, y, z, radius, height)
if poschecker and poschecker.valid
P_SetOrigin(poschecker, x, y, z)
else
poschecker = P_SpawnMobj(x, y, z, MT_FOXAI_POINT)
end
--Optionally set radius and height, resetting to type default if not specified
poschecker.radius = radius or poschecker.info.radius
poschecker.height = height or poschecker.info.height
return poschecker
end
--Fix bizarre bug where floorz / ceilingz of certain objects is sometimes inaccurate
--(e.g. rings or blue spheres on FOFs - not needed for players or other recently moved objects)
local function FixBadFloorOrCeilingZ(pmo)
--Briefly set MF_NOCLIP so we don't accidentally destroy the object, oops (e.g. ERZ snails in walls)
local oflags = pmo.flags
pmo.flags = $ | MF_NOCLIP
P_SetOrigin(pmo, pmo.x, pmo.y, pmo.z)
pmo.flags = oflags
end
--Returns height-adjusted Z for accurate comparison to FloorOrCeilingZ
local function AdjustedZ(bmo, pmo)
if bmo.eflags & MFE_VERTICALFLIP
return pmo.z + pmo.height
end
return pmo.z
end
--Returns floorz or ceilingz for pmo based on bmo's flip status
local function FloorOrCeilingZ(bmo, pmo)
if bmo.eflags & MFE_VERTICALFLIP
return pmo.ceilingz
end
return pmo.floorz
end
--Returns water top or bottom for pmo based on bmo's flip status
local function WaterTopOrBottom(bmo, pmo)
if bmo.eflags & MFE_VERTICALFLIP
return pmo.waterbottom
end
return pmo.watertop
end
--Same as above, but for an arbitrary position in space
--Note this may be inaccurate for player-specific things like standing on goop or on other objects
--(e.g. players above solid objects will report that object's height as their floorz - whereas this will not)
local function FloorOrCeilingZAtPos(bmo, x, y, z, radius, height)
--Work around lack of a P_CeilingzAtPos function
PosCheckerObj = CheckPos(PosCheckerObj, x, y, z, radius, height)
PosCheckerObj.eflags = $ & ~MFE_VERTICALFLIP | (bmo.eflags & MFE_VERTICALFLIP)
--PosCheckerObj.state = S_LOCKON2
return FloorOrCeilingZ(bmo, PosCheckerObj)
end
--More accurately predict an object's FloorOrCeilingZ by physically shifting it forward and then back
--This terrifies me
local function PredictFloorOrCeilingZ(bmo, pfac)
--Amazingly, this somehow does not trigger sector tags etc.
--Could alternatively use an MF_SOLID PosChecker, ignoring players with a MobjCollide hook
--However, I prefer this for now as it's using the original object's legitimate floor checks
local ox, oy, oz = bmo.x, bmo.y, bmo.z
local oflags = bmo.flags
bmo.flags = $ | MF_NOCLIPTHING
P_SetOrigin(bmo,
bmo.x + bmo.momx * pfac,
bmo.y + bmo.momy * pfac,
bmo.z + bmo.momz * pfac)
local predictfloor = FloorOrCeilingZ(bmo, bmo)
bmo.flags = oflags
P_SetOrigin(bmo, ox, oy, oz)
return predictfloor
end
--P_CheckSight wrapper to approximate sight checks for objects above/below FOFs
--Eliminates being able to "see" targets through FOFs at extreme angles
local function CheckSight(bmo, pmo)
--Allow equal heights so we can see DSZ3 boss
return bmo.floorz <= pmo.ceilingz
and bmo.ceilingz >= pmo.floorz
and P_CheckSight(bmo, pmo)
end
--P_SuperReady but without the shield and PF_JUMPED checks
local function SuperReady(player)
return not player.powers[pw_super]
and not player.powers[pw_invulnerability]
and not player.powers[pw_tailsfly]
and (player.charflags & SF_SUPER)
--and (player.pflags & PF_JUMPED)
--and not (player.powers[pw_shield] & SH_NOSTACK)
and not (maptol & TOL_NIGHTS)
and All7Emeralds(emeralds)
and player.rings >= 50
end
--CONS_Printf but substituting consoleplayer for secondarydisplayplayer
local function ConsPrint(player, ...)
if player == secondarydisplayplayer
player = consoleplayer
end
CONS_Printf(player, ...)
end
--Send player prefs to server
COM_AddCommand("__SendPlayerPrefs", function(player, analog, directionchar, autobrake)
player.pflags = $
& ~PF_ANALOGMODE
& ~PF_DIRECTIONCHAR
& ~PF_AUTOBRAKE
if not SPBot(player) --Avoid setting these flags on BOT_2PHUMAN
if tonumber(analog)
player.pflags = $ | PF_ANALOGMODE
end
if tonumber(directionchar)
player.pflags = $ | PF_DIRECTIONCHAR
end
end
if tonumber(autobrake)
player.pflags = $ | PF_AUTOBRAKE
end
end, 0)
--[[
--------------------------------------------------------------------------------
AI SETUP FUNCTIONS / CONSOLE COMMANDS
Any AI "setup" logic, including console commands
--------------------------------------------------------------------------------
]]
--Set a new target for AI
local function SetTarget(ai, target)
--Clean up previous target, if any
if ai.target and ai.target.valid
and ai.target.ai_attacker == ai
ai.target.ai_attacker = nil
end
--Set target and reset (or define) target-specific vars
ai.target = target
ai.targetjumps = 0 --If too many, abort target
if target and target.valid
and not target.ai_attacker
target.ai_attacker = ai
end
end
--Reset (or define) all AI vars to their initial values
local function ResetAI(ai)
ai.think_last = 0 --Last think time
ai.jump_last = 0 --Jump history
ai.spin_last = 0 --Spin history
ai.move_last = 0 --Directional input history
ai.zoom_last = false --Zoom tube history
ai.anxiety = 0 --Catch-up counter
ai.panic = 0 --Catch-up mode
ai.panicjumps = 0 --If too many, just teleport
ai.flymode = 0 --0 = No interaction. 1 = Grab Sonic. 2 = Sonic is latched.
ai.spinmode = 0 --If 1, Tails is spinning or preparing to charge spindash
ai.thinkfly = 0 --If 1, Tails will attempt to fly when Sonic jumps
ai.idlecount = 0 --Checks the amount of time without any player inputs
ai.bored = 0 --AI will act independently if "bored".
ai.drowning = 0 --AI drowning panic. 2 = Tails flies for air.
SetTarget(ai, nil) --Enemy to target
ai.targetcount = 0 --Number of targets in range (used for armageddon shield)
ai.targetnosight = 0 --How long the target has been out of view
ai.playernosight = 0 --How long the player has been out of view
ai.stalltics = 0 --Time that AI has struggled to move
ai.attackwait = 0 --Tics to wait before attacking again
ai.attackoverheat = 0 --Used by Fang to determine whether to wait
ai.cmd_time = 0 --If > 0, suppress bot ai in favor of player controls
ai.pushtics = 0 --Time leader has pushed against something (used to maybe attack it)
ai.longjump = 0 --AI is making a decently sized leap for an enemy
ai.doteleport = false --AI is attempting to teleport
ai.teleporttime = 0 --Time since AI has first attempted to teleport
ai.predictgap = 0 --AI is jumping a gap
ai.loseshield = false --If true, lose our shield (e.g. due to leader getting hit)
ai.busy = false --AI is "busy" (spectating, in combat, etc.)
ai.busyleader = nil --Temporary leader when busy
--Destroy any child objects if they're around
ai.overlay = DestroyObj($) --Speech bubble overlay - only (re)create this if needed in think logic
ai.overlaytime = 0 --Time overlay has been active
ai.waypoint = DestroyObj($) --Transient waypoint used for navigating around corners
end
--Update all followers' followerindex
local function UpdateFollowerIndices(leader)
if not (leader and leader.valid and leader.ai_followers)
return
end
for k, b in ipairs(leader.ai_followers)
if b and b.valid and b.ai
b.ai.followerindex = k
end
end
--Maintain a recursive "tail" reference to our last follower
local tail = TableLast(leader.ai_followers)
if tail and tail.valid and tail.ai_followers
tail = $.ai_followers.tail
end
leader.ai_followers.tail = tail
--Bubble this change up through realleader (if applicable)
local baseleader = leader
while leader.ai
and leader.ai.realleader
and leader.ai.realleader.valid
and leader.ai.realleader.ai_followers
and TableLast(leader.ai.realleader.ai_followers) == leader
and leader.ai.realleader != baseleader
leader.ai.realleader.ai_followers.tail = tail
leader = leader.ai.realleader
end
end
--Register follower with leader for lookup later
local function RegisterFollower(leader, bot)
if not (leader and leader.valid)
return
end
if not leader.ai_followers
leader.ai_followers = {}
end
table.insert(leader.ai_followers, bot)
UpdateFollowerIndices(leader)
end
--Unregister follower with leader
local function UnregisterFollower(leader, bot)
if not (leader and leader.valid and leader.ai_followers)
return
end
for k, b in ipairs(leader.ai_followers)
if b == bot
table.remove(leader.ai_followers, k)
break
end
end
if leader.ai_followers[1]
UpdateFollowerIndices(leader)
else
leader.ai_followers = nil
end
end
--Register bot with player owner for lookup later
local function RegisterOwner(player, bot)
if not (player and player.valid)
return
end
if not player.ai_ownedbots
player.ai_ownedbots = {}
end
table.insert(player.ai_ownedbots, bot)
if bot and bot.valid
bot.ai_owner = player
end
end
--Unregister bot with player owner
local function UnregisterOwner(player, bot)
if bot and bot.valid
bot.ai_owner = nil
end
if not (player and player.valid and player.ai_ownedbots)
return
end
for k, b in ipairs(player.ai_ownedbots)
if b == bot
table.remove(player.ai_ownedbots, k)
break
end
end
if not player.ai_ownedbots[1]
player.ai_ownedbots = nil
end
end
--Create AI table for a given player, if needed
local function SetupAI(player)
if player.ai
return
end
--Create table, defining any vars that shouldn't be reset via ResetAI
player.ai = {
leader = nil, --Bot's leader
realleader = nil, --Bot's "real" leader (if temporarily following someone else)
followerindex = 0, --Our index in realleader's ai_followers array
lastrings = player.rings, --Last ring count of bot (used to sync w/ leader)
lastlives = player.lives, --Last life count of bot (used to sync w/ leader)
realrings = player.rings, --"Real" ring count of bot (outside of sync)
realxtralife = player.xtralife, --"Real" xtralife count of bot (outside of sync)
reallives = player.lives, --"Real" life count of bot (outside of sync)
ronin = false, --Headless bot from disconnected client?
timeseed = P_RandomByte() + #player, --Used for time-based pseudo-random behaviors (e.g. via BotTime)
syncrings = false, --Current sync setting for rings
synclives = false, --Current sync setting for lives
lastseenpos = { x = 0, y = 0, z = 0 } --Last seen position tracking
}
ResetAI(player.ai) --Define the rest w/ their respective values
player.ai.playernosight = 3 * TICRATE --For setup only, queue an instant teleport
end
--Restore "real" ring / life counts for a given player
local function RestoreRealRings(player)
player.rings = player.ai.realrings
player.xtralife = player.ai.realxtralife
end
local function RestoreRealLives(player)
player.lives = player.ai.reallives
--Transition to spectating if we had no lives left
if player.lives < 1 and not player.spectator
player.playerstate = PST_REBORN
end
end
--"Repossess" a bot for player control
local function Repossess(player)
--Reset our original analog etc. prefs
--SendWeaponPref isn't exposed to Lua, so just cycle convars to trigger it
--However, 2.2.11 now prevents this as none of the convars are marked CV_ALLOWLUA
--So we must manually restore some pflags with ugly convar lookups :P
if not netgame or player == consoleplayer
local CV_Analog = CV_FindVar("configanalog")
local CV_Directionchar = CV_FindVar("directionchar")
local CV_Autobrake = CV_FindVar("autobrake")
if not netgame and #player > 0
CV_Analog = CV_FindVar("configanalog2")
CV_Directionchar = CV_FindVar("directionchar2")
CV_Autobrake = CV_FindVar("autobrake2")
end
COM_BufInsertText(player, "__SendPlayerPrefs " .. CV_Analog.value .. " " .. CV_Directionchar.value .. " " .. CV_Autobrake.value)
end
--Reset our vertical aiming (in case we have vert look disabled)
player.aiming = 0
--Reset anything else
ResetAI(player.ai)
end
--Destroy AI table (and any child tables / objects) for a given player, if needed
local function DestroyAI(player)
if not player.ai
return
end
--Reset pflags etc. for player
--Also resets all vars, clears target, etc.
Repossess(player)
--Unregister ourself from our (real) leader if still valid
UnregisterFollower(player.ai.realleader, player)
--Kick headless bots w/ no client
--Otherwise they sit and do nothing
if player.ai.ronin
player.quittime = 1
end
--Restore our "real" ring / life counts if synced
if player.ai.syncrings
RestoreRealRings(player)
end
if player.ai.synclives
RestoreRealLives(player)
end
--SP bots record our last good realleader to reset to later
if SPBot(player)
player.ai_lastrealleader = player.ai.realleader
end
--My work here is done
player.ai = nil
collectgarbage()
end
--Get our "top" leader in a leader chain (if applicable)
--e.g. for A <- B <- D <- C, D's "top" leader is A
local function GetTopLeader(bot, basebot)
--basebot automatically set to bot if nil
if bot != basebot and bot.valid and bot.ai
and bot.ai.realleader and bot.ai.realleader.valid
return GetTopLeader(bot.ai.realleader, basebot or bot)
end
return bot
end
--Get our "bottom" follower in a leader chain (if applicable)
--e.g. for A <- B <- D <- C, A's "bottom" follower is C
local function GetBottomFollower(bot, basebot)
--basebot automatically set to bot if nil
if bot != basebot and bot.valid and bot.ai_followers
for k, b in ipairs(bot.ai_followers)
--Pick a random node if the tree splits
if P_RandomByte() < 128
or table.maxn(bot.ai_followers) == k
return GetBottomFollower(b, basebot or bot)
end
end
end
return bot
end
--List all bots, optionally excluding bots led by leader
local function SubListBots(player, leader, owner, bot, level)
if bot == leader
return 0
end
local msg = #bot .. " - " .. bot.name
for i = 0, level
msg = " " .. $
end
if bot.realmo and bot.realmo.valid and bot.realmo.skin
msg = $ .. " \x86(" .. bot.realmo.skin .. ")"
end
if bot.spectator
msg = $ .. " \x87(KO'd)"
end
if bot.quittime
msg = $ .. " \x85(disconnecting)"
elseif bot.ai_owner and bot.ai_owner.valid
msg = $ .. " \x8A(" .. BotType(bot) .. ": " .. #bot.ai_owner .. " - " .. bot.ai_owner.name .. ")"
elseif bot.ai and bot.ai.cmd_time
msg = $ .. " \x81(player-controlled)"
elseif bot.ai and bot.ai.ronin
msg = $ .. " \x83(disconnected)"
elseif not bot.bot
msg = $ .. " \x84(player)"
end
local count = 0
if owner == nil or IsAuthority(owner, bot, true)
ConsPrint(player, msg)
count = 1
end
if bot.ai_followers
for _, b in ipairs(bot.ai_followers)
if b and b.valid
count = $ + SubListBots(player, leader, owner, b, level + 1)
end
end
end
return count
end
local function ListBots(player, leader, owner)
if leader != nil
leader = ResolvePlayerByNum($)
if leader and leader.valid
ConsPrint(player, "\x84 Excluding players/bots led by " .. leader.name)
end
end
if owner != nil
owner = ResolvePlayerByNum($)
if owner and owner.valid
ConsPrint(player, "\x81 Showing only players/bots owned by " .. owner.name)
end
end
local count = 0
for p in players.iterate
if not p.ai
count = $ + SubListBots(player, leader, owner, p, 0)
end
end
ConsPrint(player, "Returned " .. count .. " nodes")
end
COM_AddCommand("LISTBOTS", ListBots, COM_LOCAL)
--Set player as a bot following a particular leader
--Internal/Admin-only: Optionally specify some other player/bot to follow leader
local function SetBot(player, leader, bot)
local pbot = player
if bot != nil --Must check nil as 0 is valid
pbot = ResolveMultiplePlayersByNum(player, bot)
if type(pbot) == "table"
for _, bot in ipairs(pbot)
SetBot(player, leader, bot)
end
return
end
if not IsAuthority(player, pbot)
pbot = nil
end
end
if not (pbot and pbot.valid)
ConsPrint(player, "Invalid bot! Please specify a bot by number:")
ListBots(player, nil, #player)
return
end
--Make sure we won't end up following ourself
local pleader = ResolvePlayerByNum(leader)
if pleader and pleader.valid
and GetTopLeader(pleader, pbot) == pbot
if pbot == player
ConsPrint(pleader, pbot.name + " tried to follow you, but you're already following them!")
if pleader == pbot.ai_owner
ConsPrint(pleader, pbot.name + "\x8A has no leader and will be removed shortly...")
end
end
ConsPrint(player, pbot.name + " would end up following itself! Please try a different leader:")
ListBots(player, #pbot)
return
end
--Set up our AI (if needed) and figure out leader
SetupAI(pbot)
if pleader and pleader.valid
ConsPrint(player, "Set bot " + pbot.name + " following " + pleader.name)
if player != pbot
ConsPrint(pbot, player.name + " set bot " + pbot.name + " following " + pleader.name)
end
elseif pbot.ai.realleader
ConsPrint(player, "Stopping bot " + pbot.name)
if player != pbot
ConsPrint(pbot, player.name + " stopping bot " + pbot.name)
end
else
ConsPrint(player, "Invalid leader! Please specify a leader by number:")
ListBots(player, #pbot)
end
--Valid leader?
if pleader and pleader.valid
--Unregister ourself from our old (real) leader (if applicable)
UnregisterFollower(pbot.ai.realleader, pbot)
--Set the new leader
pbot.ai.leader = pleader
pbot.ai.realleader = pleader
--Register ourself as a follower
RegisterFollower(pleader, pbot)
else
--Destroy AI if no leader set
DestroyAI(pbot)
--Allow bot to return itself to owner if able (owner not following it)
if pbot.ai_owner and pbot.ai_owner.valid and pbot.ai_owner != player
SetBot(pbot, #pbot.ai_owner)
end
end
end
COM_AddCommand("SETBOT2", SetBot, COM_SPLITSCREEN)
COM_AddCommand("SETBOT", SetBot, 0)
--Add player as a bot following us
local function AddBot(player, skin, color, name, type)
if not (player.realmo and player.realmo.valid)
ConsPrint(player, "Can't do this outside a level!")
return
end
if netgame
if not IsAdmin(player)
and player.ai_ownedbots
and table.maxn(player.ai_ownedbots) >= CV_AIMaxBots.value
ConsPrint(player, "Too many bots! Maximum allowed per player: " .. CV_AIMaxBots.value)
return
end
if CV_AIReserveSlot.value
and PlayerCount() >= CV_MaxPlayers.value - 1
ConsPrint(player, "Too many bots for current maxplayers count: " .. CV_MaxPlayers.value)
if IsAdmin(player)
ConsPrint(player, "\x82" .. "Admin Only:\x80 Try increasing maxplayers or disabling ai_reserveslot")
end
return
end
end
--Use logical defaults in singleplayer
if color
color = R_GetColorByName($)
end
if not (netgame or splitscreen)
--Figure out skins in use
local skinsinuse = {}
for p in players.iterate
if p.realmo and p.realmo.valid
skinsinuse[p.realmo.skin] = true
end
end
--Default to next available unlocked skin
if not (skin and skins[skin])
for s in skins.iterate
if not skinsinuse[s.name]
and R_SkinUsable(player, s.name)
skin = s.name
break
end
end
end
--Default to skin's prefcolor / realname
if skin and skins[skin]
and not skinsinuse[skin]
if not color
color = skins[skin].prefcolor
end
if not name or name == ""
name = skins[skin].realname
end
end
end
--Validate skin
if not (skin and skins[skin])
local rs = {}
for s in skins.iterate
if R_SkinUsable(player, s.name)
table.insert(rs, s.name)
end
end
local i = P_RandomKey(table.maxn(rs)) + 1
skin = rs[i]
end
--Validate color
if not color
color = P_RandomRange(1, 68)
end
--Validate name
if not name or name == ""
name = BotlessName(player) .. "Bot"
end
local i = 0
local n = name
for p in players.iterate
if BotlessName(p) == n
i = $ + 1
n = name .. i
end
end
name = n
--Validate type
type = tonumber($)
if type != nil
type = min(max($, BOT_NONE), BOT_MPAI)
elseif netgame or splitscreen
type = BOT_MPAI
else
type = BOT_2PAI
end
--Dedicated servers will crash adding a BOT_NONE bot to slot 0
--Instead, work around this by adding a proxy BOT_MPAI bot there for a second
local sbot = nil
if type == BOT_NONE and not (players[0] and players[0].valid)
sbot = G_AddPlayer("tails", 8, "Server Proxy Bot", BOT_MPAI)
end
--Add that bot!
--Manually set our skin later, since G_AddPlayer throws error for hidden skins on BOT_NONE bot
local pbot = G_AddPlayer("sonic", color, name, type)
if pbot and pbot.valid
ConsPrint(player, "Adding " .. BotType(pbot) .. " " .. pbot.name .. " / " .. skins[skin].name .. " / " .. R_GetNameByColor(color))
--Set our skin if usable
if R_SkinUsable(pbot, skin)
R_SetPlayerSkin(pbot, skin)
end
--Force color in singleplayer
pbot.skincolor = color
--Set that bot! And figure out authority owner
SetBot(pbot, #player)
RegisterOwner(player, pbot)
--All summoned bots should disconnect when stopped, except SP bots
if pbot.ai and not SPBot(pbot)
pbot.ai.ronin = true
end
else
ConsPrint(player, "Unable to add bot!")
end
--Remove server proxy bot (if applicable)
if sbot and sbot.valid
G_RemovePlayer(#sbot)
end
end
COM_AddCommand("ADDBOT2", AddBot, COM_SPLITSCREEN)
COM_AddCommand("ADDBOT", AddBot, 0)
--Alter player bot's skin, etc.