]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/bot/bot.qc
fd9fe0a5d3f6ab01e88ad655f315515856d2cc82
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / bot / bot.qc
1 #include "bot.qh"
2
3 #include "aim.qh"
4 #include "navigation.qh"
5 #include "scripting.qh"
6 #include "waypoints.qh"
7
8 #include "havocbot/havocbot.qh"
9 #include "havocbot/scripting.qh"
10
11 #include "../teamplay.qh"
12
13 #include "../antilag.qh"
14 #include "../autocvars.qh"
15 #include "../campaign.qh"
16 #include "../cl_client.qh"
17 #include "../constants.qh"
18 #include "../defs.qh"
19 #include "../race.qh"
20 #include "../t_items.qh"
21
22 #include "../mutators/all.qh"
23
24 #include "../weapons/accuracy.qh"
25
26 #include "../../common/constants.qh"
27 #include "../../common/mapinfo.qh"
28 #include "../../common/teams.qh"
29 #include "../../common/util.qh"
30
31 #include "../../common/weapons/all.qh"
32
33 #include "../../lib/csqcmodel/sv_model.qh"
34
35 #include "../../lib/warpzone/common.qh"
36 #include "../../lib/warpzone/util_server.qh"
37
38 entity bot_spawn()
39 {SELFPARAM();
40         entity bot = spawnclient();
41         if (bot)
42         {
43                 currentbots = currentbots + 1;
44                 setself(bot);
45                 bot_setnameandstuff();
46                 ClientConnect();
47                 PutClientInServer();
48                 setself(this);
49         }
50         return bot;
51 }
52
53 void bot_think()
54 {SELFPARAM();
55         if (self.bot_nextthink > time)
56                 return;
57
58         self.flags &= ~FL_GODMODE;
59         if(autocvar_bot_god)
60                 self.flags |= FL_GODMODE;
61
62         self.bot_nextthink = self.bot_nextthink + autocvar_bot_ai_thinkinterval * pow(0.5, self.bot_aiskill);
63         //if (self.bot_painintensity > 0)
64         //      self.bot_painintensity = self.bot_painintensity - (skill + 1) * 40 * frametime;
65
66         //self.bot_painintensity = self.bot_painintensity + self.bot_oldhealth - self.health;
67         //self.bot_painintensity = bound(0, self.bot_painintensity, 100);
68
69         if (!IS_PLAYER(self) || (autocvar_g_campaign && !campaign_bots_may_start))
70         {
71                 self.bot_nextthink = time + 0.5;
72                 return;
73         }
74
75         if (self.fixangle)
76         {
77                 self.v_angle = self.angles;
78                 self.v_angle_z = 0;
79                 self.fixangle = false;
80         }
81
82         self.dmg_take = 0;
83         self.dmg_save = 0;
84         self.dmg_inflictor = world;
85
86         // calculate an aiming latency based on the skill setting
87         // (simulated network latency + naturally delayed reflexes)
88         //self.ping = 0.7 - bound(0, 0.05 * skill, 0.5); // moved the reflexes to bot_aimdir (under the name 'think')
89         // minimum ping 20+10 random
90         self.ping = bound(0,0.07 - bound(0, (skill + self.bot_pingskill) * 0.005,0.05)+random()*0.01,0.65); // Now holds real lag to server, and higer skill players take a less laggy server
91         // skill 10 = ping 0.2 (adrenaline)
92         // skill 0 = ping 0.7 (slightly drunk)
93
94         // clear buttons
95         self.BUTTON_ATCK = 0;
96         self.button1 = 0;
97         self.BUTTON_JUMP = 0;
98         self.BUTTON_ATCK2 = 0;
99         self.BUTTON_ZOOM = 0;
100         self.BUTTON_CROUCH = 0;
101         self.BUTTON_HOOK = 0;
102         self.BUTTON_INFO = 0;
103         self.button8 = 0;
104         self.BUTTON_CHAT = 0;
105         self.BUTTON_USE = 0;
106
107         if (time < game_starttime)
108         {
109                 // block the bot during the countdown to game start
110                 self.movement = '0 0 0';
111                 self.bot_nextthink = game_starttime;
112                 return;
113         }
114
115         // if dead, just wait until we can respawn
116         if (self.deadflag)
117         {
118                 if (self.deadflag == DEAD_DEAD)
119                 {
120                         self.BUTTON_JUMP = 1; // press jump to respawn
121                         self.bot_strategytime = 0;
122                 }
123         }
124         else if(self.aistatus & AI_STATUS_STUCK)
125                 navigation_unstuck();
126
127         // now call the current bot AI (havocbot for example)
128         self.bot_ai();
129 }
130
131 void bot_setnameandstuff()
132 {SELFPARAM();
133         string readfile, s;
134         float file, tokens, prio;
135         entity p;
136
137         string bot_name, bot_model, bot_skin, bot_shirt, bot_pants;
138         string name, prefix, suffix;
139
140         if(autocvar_g_campaign)
141         {
142                 prefix = "";
143                 suffix = "";
144         }
145         else
146         {
147                 prefix = autocvar_bot_prefix;
148                 suffix = autocvar_bot_suffix;
149         }
150
151         file = fopen(autocvar_bot_config_file, FILE_READ);
152
153         if(file < 0)
154         {
155                 LOG_INFO(strcat("Error: Can not open the bot configuration file '",autocvar_bot_config_file,"'\n"));
156                 readfile = "";
157         }
158         else
159         {
160                 RandomSelection_Init();
161                 while((readfile = fgets(file)))
162                 {
163                         if(substring(readfile, 0, 2) == "//")
164                                 continue;
165                         if(substring(readfile, 0, 1) == "#")
166                                 continue;
167                         tokens = tokenizebyseparator(readfile, "\t");
168                         if(tokens == 0)
169                                 continue;
170                         s = argv(0);
171                         prio = 1;
172                         FOR_EACH_CLIENT(p)
173                         {
174                                 if(IS_BOT_CLIENT(p))
175                                 if(s == p.cleanname)
176                                 {
177                                         prio = 0;
178                                         break;
179                                 }
180                         }
181                         RandomSelection_Add(world, 0, readfile, 1, prio);
182                 }
183                 readfile = RandomSelection_chosen_string;
184                 fclose(file);
185         }
186
187         tokens = tokenizebyseparator(readfile, "\t");
188         if(argv(0) != "") bot_name = argv(0);
189         else bot_name = "Bot";
190
191         if(argv(1) != "") bot_model = argv(1);
192         else bot_model = "";
193
194         if(argv(2) != "") bot_skin = argv(2);
195         else bot_skin = "0";
196
197         if(argv(3) != "" && stof(argv(3)) >= 0) bot_shirt = argv(3);
198         else bot_shirt = ftos(floor(random() * 15));
199
200         if(argv(4) != "" && stof(argv(4)) >= 0) bot_pants = argv(4);
201         else bot_pants = ftos(floor(random() * 15));
202
203         self.bot_forced_team = stof(argv(5));
204
205         prio = 6;
206
207         #define READSKILL(f,w,r) if(argv(prio) != "") self.f = stof(argv(prio)) * (w); else self.f = (!autocvar_g_campaign) * (2 * random() - 1) * (r) * (w); ++prio
208         //print(bot_name, ": ping=", argv(9), "\n");
209
210         READSKILL(havocbot_keyboardskill, 0.5, 0.5); // keyboard skill
211         READSKILL(bot_moveskill, 2, 0); // move skill
212         READSKILL(bot_dodgeskill, 2, 0); // dodge skill
213
214         READSKILL(bot_pingskill, 0.5, 0); // ping skill
215
216         READSKILL(bot_weaponskill, 2, 0); // weapon skill
217         READSKILL(bot_aggresskill, 1, 0); // aggre skill
218         READSKILL(bot_rangepreference, 1, 0); // read skill
219
220         READSKILL(bot_aimskill, 2, 0); // aim skill
221         READSKILL(bot_offsetskill, 2, 0.5); // offset skill
222         READSKILL(bot_mouseskill, 1, 0.5); // mouse skill
223
224         READSKILL(bot_thinkskill, 1, 0.5); // think skill
225         READSKILL(bot_aiskill, 2, 0); // "ai" skill
226
227         self.bot_config_loaded = true;
228
229         // this is really only a default, JoinBestTeam is called later
230         setcolor(self, stof(bot_shirt) * 16 + stof(bot_pants));
231         self.bot_preferredcolors = self.clientcolors;
232
233         // pick the name
234         if (autocvar_bot_usemodelnames)
235                 name = bot_model;
236         else
237                 name = bot_name;
238
239         // number bots with identical names
240         float i;
241         i = 0;
242         FOR_EACH_CLIENT(p)
243         {
244                 if(IS_BOT_CLIENT(p))
245                         if(p.cleanname == name)
246                                 ++i;
247         }
248         if (i)
249                 self.netname = self.netname_freeme = strzone(strcat(prefix, name, "(", ftos(i), ")", suffix));
250         else
251                 self.netname = self.netname_freeme = strzone(strcat(prefix, name, suffix));
252
253         self.cleanname = strzone(name);
254
255         // pick the model and skin
256         if(substring(bot_model, -4, 1) != ".")
257                 bot_model = strcat(bot_model, ".iqm");
258         self.playermodel = self.playermodel_freeme = strzone(strcat("models/player/", bot_model));
259         self.playerskin = self.playerskin_freeme = strzone(bot_skin);
260
261         self.cvar_cl_accuracy_data_share = 1;  // share the bots weapon accuracy data with the world
262         self.cvar_cl_accuracy_data_receive = 0;  // don't receive any weapon accuracy data
263 }
264
265 void bot_custom_weapon_priority_setup()
266 {
267         float tokens, i, w;
268
269         bot_custom_weapon = false;
270
271         if(     autocvar_bot_ai_custom_weapon_priority_far == "" ||
272                 autocvar_bot_ai_custom_weapon_priority_mid == "" ||
273                 autocvar_bot_ai_custom_weapon_priority_close == "" ||
274                 autocvar_bot_ai_custom_weapon_priority_distances == ""
275         )
276                 return;
277
278         // Parse distances
279         tokens = tokenizebyseparator(autocvar_bot_ai_custom_weapon_priority_distances," ");
280
281         if (tokens!=2)
282                 return;
283
284         bot_distance_far = stof(argv(0));
285         bot_distance_close = stof(argv(1));
286
287         if(bot_distance_far < bot_distance_close){
288                 bot_distance_far = stof(argv(1));
289                 bot_distance_close = stof(argv(0));
290         }
291
292         // Initialize list of weapons
293         bot_weapons_far[0] = -1;
294         bot_weapons_mid[0] = -1;
295         bot_weapons_close[0] = -1;
296
297         // Parse far distance weapon priorities
298         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_far)," ");
299
300         int c = 0;
301         for(i=0; i < tokens && c < Weapons_COUNT; ++i){
302                 w = stof(argv(i));
303                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
304                         bot_weapons_far[c] = w;
305                         ++c;
306                 }
307         }
308         if(c < Weapons_COUNT)
309                 bot_weapons_far[c] = -1;
310
311         // Parse mid distance weapon priorities
312         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_mid)," ");
313
314         c = 0;
315         for(i=0; i < tokens && c < Weapons_COUNT; ++i){
316                 w = stof(argv(i));
317                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
318                         bot_weapons_mid[c] = w;
319                         ++c;
320                 }
321         }
322         if(c < Weapons_COUNT)
323                 bot_weapons_mid[c] = -1;
324
325         // Parse close distance weapon priorities
326         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_close)," ");
327
328         c = 0;
329         for(i=0; i < tokens && i < Weapons_COUNT; ++i){
330                 w = stof(argv(i));
331                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
332                         bot_weapons_close[c] = w;
333                         ++c;
334                 }
335         }
336         if(c < Weapons_COUNT)
337                 bot_weapons_close[c] = -1;
338
339         bot_custom_weapon = true;
340 }
341
342 void bot_endgame()
343 {
344         entity e;
345         //dprint("bot_endgame\n");
346         e = bot_list;
347         while (e)
348         {
349                 setcolor(e, e.bot_preferredcolors);
350                 e = e.nextbot;
351         }
352         // if dynamic waypoints are ever implemented, save them here
353 }
354
355 void bot_relinkplayerlist()
356 {
357         entity e;
358         entity prevbot;
359         player_count = 0;
360         currentbots = 0;
361         player_list = e = findchainflags(flags, FL_CLIENT);
362         bot_list = world;
363         prevbot = world;
364         while (e)
365         {
366                 player_count = player_count + 1;
367                 e.nextplayer = e.chain;
368                 if (IS_BOT_CLIENT(e))
369                 {
370                         if (prevbot)
371                                 prevbot.nextbot = e;
372                         else
373                         {
374                                 bot_list = e;
375                                 bot_list.nextbot = world;
376                         }
377                         prevbot = e;
378                         currentbots = currentbots + 1;
379                 }
380                 e = e.chain;
381         }
382         LOG_TRACE(strcat("relink: ", ftos(currentbots), " bots seen.\n"));
383         bot_strategytoken = bot_list;
384         bot_strategytoken_taken = true;
385 }
386
387 void bot_clientdisconnect()
388 {SELFPARAM();
389         if (!IS_BOT_CLIENT(self))
390                 return;
391         bot_clearqueue(self);
392         if(self.cleanname)
393                 strunzone(self.cleanname);
394         if(self.netname_freeme)
395                 strunzone(self.netname_freeme);
396         if(self.playermodel_freeme)
397                 strunzone(self.playermodel_freeme);
398         if(self.playerskin_freeme)
399                 strunzone(self.playerskin_freeme);
400         self.cleanname = string_null;
401         self.netname_freeme = string_null;
402         self.playermodel_freeme = string_null;
403         self.playerskin_freeme = string_null;
404         if(self.bot_cmd_current)
405                 remove(self.bot_cmd_current);
406         if(bot_waypoint_queue_owner==self)
407                 bot_waypoint_queue_owner = world;
408 }
409
410 void bot_clientconnect(entity this)
411 {
412         if (!IS_BOT_CLIENT(this)) return;
413         self.bot_preferredcolors = self.clientcolors;
414         self.bot_nextthink = time - random();
415         self.lag_func = bot_lagfunc;
416         self.isbot = true;
417         self.createdtime = self.bot_nextthink;
418
419         if(!self.bot_config_loaded) // This is needed so team overrider doesn't break between matches
420                 bot_setnameandstuff();
421
422         if(self.bot_forced_team==1)
423                 self.team = NUM_TEAM_1;
424         else if(self.bot_forced_team==2)
425                 self.team = NUM_TEAM_2;
426         else if(self.bot_forced_team==3)
427                 self.team = NUM_TEAM_3;
428         else if(self.bot_forced_team==4)
429                 self.team = NUM_TEAM_4;
430         else
431                 JoinBestTeam(self, false, true);
432
433         havocbot_setupbot();
434 }
435
436 void bot_removefromlargestteam()
437 {
438         float besttime, bestcount, thiscount;
439         entity best, head;
440         CheckAllowedTeams(world);
441         GetTeamCounts(world);
442         head = findchainfloat(isbot, true);
443         if (!head)
444                 return;
445         best = head;
446         besttime = head.createdtime;
447         bestcount = 0;
448         while (head)
449         {
450                 if(head.team == NUM_TEAM_1)
451                         thiscount = c1;
452                 else if(head.team == NUM_TEAM_2)
453                         thiscount = c2;
454                 else if(head.team == NUM_TEAM_3)
455                         thiscount = c3;
456                 else if(head.team == NUM_TEAM_4)
457                         thiscount = c4;
458                 else
459                         thiscount = 0;
460                 if (thiscount > bestcount)
461                 {
462                         bestcount = thiscount;
463                         besttime = head.createdtime;
464                         best = head;
465                 }
466                 else if (thiscount == bestcount && besttime < head.createdtime)
467                 {
468                         besttime = head.createdtime;
469                         best = head;
470                 }
471                 head = head.chain;
472         }
473         currentbots = currentbots - 1;
474         dropclient(best);
475 }
476
477 void bot_removenewest()
478 {
479         float besttime;
480         entity best, head;
481
482         if(teamplay)
483         {
484                 bot_removefromlargestteam();
485                 return;
486         }
487
488         head = findchainfloat(isbot, true);
489         if (!head)
490                 return;
491         best = head;
492         besttime = head.createdtime;
493         while (head)
494         {
495                 if (besttime < head.createdtime)
496                 {
497                         besttime = head.createdtime;
498                         best = head;
499                 }
500                 head = head.chain;
501         }
502         currentbots = currentbots - 1;
503         dropclient(best);
504 }
505
506 void autoskill(float factor)
507 {
508         float bestbot;
509         float bestplayer;
510
511         bestbot = -1;
512         bestplayer = -1;
513         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
514                 if(IS_REAL_CLIENT(it))
515                         bestplayer = max(bestplayer, it.totalfrags - it.totalfrags_lastcheck);
516                 else
517                         bestbot = max(bestbot, it.totalfrags - it.totalfrags_lastcheck);
518         ));
519
520         LOG_TRACE("autoskill: best player got ", ftos(bestplayer), ", ");
521         LOG_TRACE("best bot got ", ftos(bestbot), "; ");
522         if(bestbot < 0 || bestplayer < 0)
523         {
524                 LOG_TRACE("not doing anything\n");
525                 // don't return, let it reset all counters below
526         }
527         else if(bestbot <= bestplayer * factor - 2)
528         {
529                 if(autocvar_skill < 17)
530                 {
531                         LOG_TRACE("2 frags difference, increasing skill\n");
532                         cvar_set("skill", ftos(autocvar_skill + 1));
533                         bprint("^2SKILL UP!^7 Now at level ", ftos(autocvar_skill), "\n");
534                 }
535         }
536         else if(bestbot >= bestplayer * factor + 2)
537         {
538                 if(autocvar_skill > 0)
539                 {
540                         LOG_TRACE("2 frags difference, decreasing skill\n");
541                         cvar_set("skill", ftos(autocvar_skill - 1));
542                         bprint("^1SKILL DOWN!^7 Now at level ", ftos(autocvar_skill), "\n");
543                 }
544         }
545         else
546         {
547                 LOG_TRACE("not doing anything\n");
548                 return;
549                 // don't reset counters, wait for them to accumulate
550         }
551
552         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(it.totalfrags_lastcheck = it.totalfrags));
553 }
554
555 void bot_calculate_stepheightvec()
556 {
557         stepheightvec = autocvar_sv_stepheight * '0 0 1';
558         jumpstepheightvec = stepheightvec +
559                 ((autocvar_sv_jumpvelocity * autocvar_sv_jumpvelocity) / (2 * autocvar_sv_gravity)) * '0 0 0.85';
560                 // 0.75 factor is for safety to make the jumps easy
561 }
562
563 float bot_fixcount()
564 {
565         int activerealplayers = 0;
566         int realplayers = 0;
567         if (MUTATOR_CALLHOOK(Bot_FixCount, activerealplayers, realplayers)) {
568                 activerealplayers = bot_activerealplayers;
569                 realplayers = bot_realplayers;
570         } else {
571                 FOREACH_CLIENT(IS_REAL_CLIENT(it), LAMBDA(
572                         if(IS_PLAYER(it))
573                                 ++activerealplayers;
574                         ++realplayers;
575                 ));
576         }
577
578         int bots;
579         // add/remove bots if needed to make sure there are at least
580         // minplayers+bot_number, or remove all bots if no one is playing
581         // But don't remove bots immediately on level change, as the real players
582         // usually haven't rejoined yet
583         bots_would_leave = false;
584         if (teamplay && autocvar_bot_vs_human && (c3==-1 && c4==-1))
585                 bots = min(ceil(fabs(autocvar_bot_vs_human) * activerealplayers), maxclients - realplayers);
586         else if ((realplayers || autocvar_bot_join_empty || (currentbots > 0 && time < 5)))
587         {
588                 float realminplayers, minplayers;
589                 realminplayers = autocvar_minplayers;
590                 minplayers = max(0, floor(realminplayers));
591
592                 float realminbots, minbots;
593                 realminbots = autocvar_bot_number;
594                 minbots = max(0, floor(realminbots));
595
596                 bots = min(max(minbots, minplayers - activerealplayers), maxclients - realplayers);
597                 if(bots > minbots)
598                         bots_would_leave = true;
599         }
600         else
601         {
602                 // if there are no players, remove bots
603                 bots = 0;
604         }
605
606         // only add one bot per frame to avoid utter chaos
607         if(time > botframe_nextthink)
608         {
609                 //dprint(ftos(bots), " ? ", ftos(currentbots), "\n");
610                 while (currentbots < bots)
611                 {
612                         if (bot_spawn() == world)
613                         {
614                                 bprint("Can not add bot, server full.\n");
615                                 return false;
616                         }
617                 }
618                 while (currentbots > bots)
619                         bot_removenewest();
620         }
621
622         return true;
623 }
624
625 void bot_serverframe()
626 {
627         if (intermission_running)
628                 return;
629
630         if (time < 2)
631                 return;
632
633         bot_calculate_stepheightvec();
634         bot_navigation_movemode = ((autocvar_bot_navigation_ignoreplayers) ? MOVE_NOMONSTERS : MOVE_NORMAL);
635
636         if(time > autoskill_nextthink)
637         {
638                 float a;
639                 a = autocvar_skill_auto;
640                 if(a)
641                         autoskill(a);
642                 autoskill_nextthink = time + 5;
643         }
644
645         if(time > botframe_nextthink)
646         {
647                 if(!bot_fixcount())
648                         botframe_nextthink = time + 10;
649         }
650
651         bot_ignore_bots = autocvar_bot_ignore_bots;
652
653         if(botframe_spawnedwaypoints)
654         {
655                 if(autocvar_waypoint_benchmark)
656                         localcmd("quit\n");
657         }
658
659         if (currentbots > 0 || autocvar_g_waypointeditor || autocvar_g_waypointeditor_auto)
660         if (botframe_spawnedwaypoints)
661         {
662                 if(botframe_cachedwaypointlinks)
663                 {
664                         if(!botframe_loadedforcedlinks)
665                                 waypoint_load_links_hardwired();
666                 }
667                 else
668                 {
669                         // TODO: Make this check cleaner
670                         entity wp = findchain(classname, "waypoint");
671                         if(time - wp.nextthink > 10)
672                                 waypoint_save_links();
673                 }
674         }
675         else
676         {
677                 botframe_spawnedwaypoints = true;
678                 waypoint_loadall();
679                 if(!waypoint_load_links())
680                         waypoint_schedulerelinkall();
681         }
682
683         if (bot_list)
684         {
685                 // cycle the goal token from one bot to the next each frame
686                 // (this prevents them from all doing spawnfunc_waypoint searches on the same
687                 //  frame, which causes choppy framerates)
688                 if (bot_strategytoken_taken)
689                 {
690                         bot_strategytoken_taken = false;
691                         if (bot_strategytoken)
692                                 bot_strategytoken = bot_strategytoken.nextbot;
693                         if (!bot_strategytoken)
694                                 bot_strategytoken = bot_list;
695                 }
696
697                 if (botframe_nextdangertime < time)
698                 {
699                         float interval;
700                         interval = autocvar_bot_ai_dangerdetectioninterval;
701                         if (botframe_nextdangertime < time - interval * 1.5)
702                                 botframe_nextdangertime = time;
703                         botframe_nextdangertime = botframe_nextdangertime + interval;
704                         botframe_updatedangerousobjects(autocvar_bot_ai_dangerdetectionupdates);
705                 }
706         }
707
708         if (autocvar_g_waypointeditor)
709                 botframe_showwaypointlinks();
710
711         if (autocvar_g_waypointeditor_auto)
712                 botframe_autowaypoints();
713
714         if(time > bot_cvar_nextthink)
715         {
716                 if(currentbots>0)
717                         bot_custom_weapon_priority_setup();
718                 bot_cvar_nextthink = time + 5;
719         }
720 }