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