]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/bot/default/bot.qc
Update default video settings
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / bot / default / bot.qc
1 #include "bot.qh"
2
3 #include <common/constants.qh>
4 #include <common/mapinfo.qh>
5 #include <common/net_linked.qh>
6 #include <common/physics/player.qh>
7 #include <common/stats.qh>
8 #include <common/teams.qh>
9 #include <common/util.qh>
10 #include <common/weapons/_all.qh>
11 #include <lib/csqcmodel/sv_model.qh>
12 #include <lib/warpzone/common.qh>
13 #include <lib/warpzone/util_server.qh>
14 #include <server/antilag.qh>
15 #include <server/bot/default/aim.qh>
16 #include <server/bot/default/cvars.qh>
17 #include <server/bot/default/havocbot/havocbot.qh>
18 #include <server/bot/default/havocbot/scripting.qh>
19 #include <server/bot/default/navigation.qh>
20 #include <server/bot/default/scripting.qh>
21 #include <server/bot/default/waypoints.qh>
22 #include <server/campaign.qh>
23 #include <server/client.qh>
24 #include <server/damage.qh>
25 #include <server/items/items.qh>
26 #include <server/mutators/_mod.qh>
27 #include <server/race.qh>
28 #include <server/scores_rules.qh>
29 #include <server/teamplay.qh>
30 #include <server/weapons/accuracy.qh>
31 #include <server/weapons/selection.qh>
32 #include <server/world.qh>
33 #include <server/command/vote.qh>
34
35 STATIC_INIT(bot) { bot_calculate_stepheightvec(); }
36
37 // TODO: remove this function! its only purpose is to update these fields since bot_setnameandstuff is called before ClientState
38 void bot_setclientfields(entity this)
39 {
40         CS_CVAR(this).cvar_cl_accuracy_data_share = 1;  // share the bots weapon accuracy data with the world
41         CS_CVAR(this).cvar_cl_accuracy_data_receive = 0;  // don't receive any weapon accuracy data
42 }
43
44 entity bot_spawn()
45 {
46         entity bot = spawnclient();
47         if (bot)
48         {
49                 setItemGroupCount();
50                 currentbots = currentbots + 1;
51                 bot_setnameandstuff(bot);
52                 ClientConnect(bot);
53                 bot_setclientfields(bot);
54                 PutClientInServer(bot);
55         }
56         return bot;
57 }
58
59 void bot_think(entity this)
60 {
61         if (this.bot_nextthink > time)
62                 return;
63
64         this.flags &= ~FL_GODMODE;
65         if(autocvar_bot_god)
66                 this.flags |= FL_GODMODE;
67
68         // if bot skill is high enough don't limit their think frequency
69         if (SUPERBOT)
70                 this.bot_nextthink = max(time, this.bot_nextthink) + 0.005;
71         else
72                 this.bot_nextthink = max(time, this.bot_nextthink) + max(0.01, autocvar_bot_ai_thinkinterval * min(14 / (skill + this.bot_aiskill + 14), 1));
73
74         if (!IS_PLAYER(this) || (autocvar_g_campaign && !campaign_bots_may_start))
75         {
76                 CS(this).movement = '0 0 0';
77                 this.bot_nextthink = time + 0.5;
78                 return;
79         }
80
81         if (this.fixangle)
82         {
83                 this.v_angle = this.angles;
84                 this.v_angle_z = 0;
85                 this.fixangle = false;
86         }
87
88         this.dmg_take = 0;
89         this.dmg_save = 0;
90         this.dmg_inflictor = NULL;
91
92         // if bot skill is high enough don't assign latency to them
93         if (SUPERBOT)
94                 CS(this).ping = 0;
95         else
96         {
97                 // calculate an aiming latency based on the skill setting
98                 // (simulated network latency + naturally delayed reflexes)
99                 //this.ping = 0.7 - bound(0, 0.05 * skill, 0.5); // moved the reflexes to bot_aimdir (under the name 'think')
100                 // minimum ping 20+10 random
101                 CS(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 higher skill players take a less laggy server
102                 // skill 10 = ping 0.2 (adrenaline)
103                 // skill 0 = ping 0.7 (slightly drunk)
104         }
105
106         // clear buttons
107         PHYS_INPUT_BUTTON_ATCK(this) = false;
108         // keep jump button pressed for a short while, useful with ramp jumps
109         PHYS_INPUT_BUTTON_JUMP(this) = (!IS_DEAD(this) && time < this.bot_jump_time + 0.2);
110         PHYS_INPUT_BUTTON_ATCK2(this) = false;
111         PHYS_INPUT_BUTTON_ZOOM(this) = false;
112         PHYS_INPUT_BUTTON_CROUCH(this) = false;
113         PHYS_INPUT_BUTTON_HOOK(this) = false;
114         PHYS_INPUT_BUTTON_INFO(this) = false;
115         PHYS_INPUT_BUTTON_DRAG(this) = false;
116         PHYS_INPUT_BUTTON_CHAT(this) = false;
117         PHYS_INPUT_BUTTON_USE(this) = false;
118
119         if (time < game_starttime)
120         {
121                 // block the bot during the countdown to game start
122                 CS(this).movement = '0 0 0';
123                 return;
124         }
125
126         // if dead, just wait until we can respawn
127         if (IS_DEAD(this) || IS_OBSERVER(this))
128         {
129                 if (bot_waypoint_queue_owner == this)
130                         bot_waypoint_queue_owner = NULL;
131                 this.aistatus = 0;
132                 CS(this).movement = '0 0 0';
133                 if (IS_OBSERVER(this))
134                         return;
135                 if (IS_DEAD(this))
136                 {
137                         if (!navigation_goalrating_timeout(this))
138                                 navigation_goalrating_timeout_force(this);
139                         // jump must not be pressed for at least one frame in order for
140                         // PlayerThink to detect the key down event
141                         if (this.deadflag == DEAD_DYING)
142                                 PHYS_INPUT_BUTTON_JUMP(this) = false;
143                         else if (this.deadflag == DEAD_DEAD)
144                                 PHYS_INPUT_BUTTON_JUMP(this) = true; // press jump to respawn
145                 }
146         }
147         else if(this.aistatus & AI_STATUS_STUCK)
148                 navigation_unstuck(this);
149
150         if (warmup_stage && !this.ready)
151         {
152                 this.ready = true;
153                 ReadyCount(); // this must be delayed until the bot has spawned
154         }
155
156         // now call the current bot AI (havocbot for example)
157         this.bot_ai(this);
158 }
159
160 void bot_setnameandstuff(entity this)
161 {
162         string readfile, s;
163         int file, tokens, prio;
164
165         file = fopen(autocvar_bot_config_file, FILE_READ);
166
167         if(file < 0)
168         {
169                 LOG_INFOF("Error: Can not open the bot configuration file '%s'", autocvar_bot_config_file);
170                 readfile = "";
171         }
172         else
173         {
174                 entity balance = TeamBalance_CheckAllowedTeams(NULL);
175                 TeamBalance_GetTeamCounts(balance, NULL);
176                 int smallest_team = -1;
177                 int smallest_count = -1;
178                 if (teamplay)
179                 {
180                         for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
181                         {
182                                 // NOTE if (autocvar_g_campaign && autocvar_g_campaign_forceteam == i)
183                                 // TeamBalance_GetNumberOfPlayers(balance, i); returns the number of players + 1
184                                 // since it keeps a spot for the real player in the desired team
185                                 int count = TeamBalance_GetNumberOfPlayers(balance, i);
186                                 if (smallest_count < 0 || count < smallest_count)
187                                 {
188                                         smallest_team = i;
189                                         smallest_count = count;
190                                 }
191                         }
192                 }
193                 TeamBalance_Destroy(balance);
194                 RandomSelection_Init();
195                 while((readfile = fgets(file)))
196                 {
197                         if(substring(readfile, 0, 2) == "//")
198                                 continue;
199                         if(substring(readfile, 0, 1) == "#")
200                                 continue;
201                         // NOTE if the line is empty tokenizebyseparator(readfile, "\t")
202                         // will create 1 empty token because there's no separator (bug?)
203                         if (readfile == "")
204                                 continue;
205                         tokens = tokenizebyseparator(readfile, "\t");
206                         if(tokens == 0)
207                                 continue;
208                         s = argv(0);
209                         prio = 0;
210                         bool conflict = false;
211                         FOREACH_CLIENT(IS_BOT_CLIENT(it), {
212                                 if (s == it.cleanname)
213                                 {
214                                         conflict = true;
215                                         break;
216                                 }
217                         });
218                         if (!conflict)
219                                 prio += 1;
220                         if (teamplay && !(autocvar_bot_vs_human && AVAILABLE_TEAMS == 2))
221                         {
222                                 int forced_team = stof(argv(5));
223                                 if (!Team_IsValidIndex(forced_team))
224                                         forced_team = 0;
225                                 if (!forced_team || forced_team == smallest_team)
226                                         prio += 2;
227                         }
228                         RandomSelection_AddString(readfile, 1, prio);
229                 }
230                 readfile = RandomSelection_chosen_string;
231                 fclose(file);
232         }
233
234         string bot_name, bot_model, bot_skin, bot_shirt, bot_pants;
235
236         tokens = tokenizebyseparator(readfile, "\t");
237         if(argv(0) != "") bot_name = argv(0);
238         else bot_name = "Bot";
239
240         if(argv(1) != "") bot_model = argv(1);
241         else bot_model = "";
242
243         if(argv(2) != "") bot_skin = argv(2);
244         else bot_skin = "0";
245
246         if(argv(3) != "" && stof(argv(3)) >= 0) bot_shirt = argv(3);
247         else bot_shirt = ftos(floor(random() * 15));
248
249         if(argv(4) != "" && stof(argv(4)) >= 0) bot_pants = argv(4);
250         else bot_pants = ftos(floor(random() * 15));
251
252         if (teamplay && !(autocvar_bot_vs_human && AVAILABLE_TEAMS == 2))
253         {
254                 this.bot_forced_team = stof(argv(5));
255                 if (!Team_IsValidIndex(this.bot_forced_team))
256                         this.bot_forced_team = 0;
257         }
258         else
259                 this.bot_forced_team = 0;
260
261         prio = 6;
262
263         #define READSKILL(f, w, r) MACRO_BEGIN \
264                 if(argv(prio) != "") \
265                         this.f = stof(argv(prio)) * w; \
266                 else \
267                         this.f = (!autocvar_g_campaign) * (2 * random() - 1) * r * w; \
268                 prio++; \
269         MACRO_END
270         //print(bot_name, ": ping=", argv(9), "\n");
271
272         READSKILL(havocbot_keyboardskill, 0.5, 0.5); // keyboard skill
273         READSKILL(bot_moveskill, 2, 0); // move skill
274         READSKILL(bot_dodgeskill, 2, 0); // dodge skill
275
276         READSKILL(bot_pingskill, 0.5, 0); // ping skill
277
278         READSKILL(bot_weaponskill, 2, 0); // weapon skill
279         READSKILL(bot_aggresskill, 1, 0); // aggre skill
280         READSKILL(bot_rangepreference, 1, 0); // read skill
281
282         READSKILL(bot_aimskill, 2, 0); // aim skill
283         READSKILL(bot_offsetskill, 2, 0.5); // offset skill
284         READSKILL(bot_mouseskill, 1, 0.5); // mouse skill
285
286         READSKILL(bot_thinkskill, 1, 0.5); // think skill
287         READSKILL(bot_aiskill, 2, 0); // "ai" skill
288
289         // if bot skill is high enough don't limit their skill
290         if (SUPERBOT)
291         {
292                 // commented out means they're meaningless with this high skill
293                 // no reason to set them, uncomment if this changes
294                 //this.havocbot_keyboardskill = 10;
295                 //this.bot_moveskill = 10; //midair modifier sets this to 0 to disable bhop
296                 //this.bot_dodgeskill = 10;
297                 //this.bot_pingskill = 10;
298                 //this.bot_weaponskill = 10;
299                 //this.bot_aggresskill = 10;
300                 this.bot_rangepreference = 1; // no range preference modification
301                 //this.bot_aimskill = 10;
302                 //this.bot_offsetskill = 10;
303                 //this.bot_mouseskill = 10;
304                 //this.bot_thinkskill = 10;
305                 //this.bot_aiskill = 10;
306         }
307         if (file >= 0 && argv(prio) != "")
308                 LOG_INFOF("^1Warning^7: too many parameters for bot %s, please check format of %s", bot_name, autocvar_bot_config_file);
309
310         this.bot_config_loaded = true;
311
312         // this is really only a default, TeamBalance_JoinBestTeam is called later
313         setcolor(this, stof(bot_shirt) * 16 + stof(bot_pants));
314         this.bot_preferredcolors = this.clientcolors;
315
316         string prefix = (autocvar_g_campaign ? "" : autocvar_bot_prefix);
317         string suffix = (autocvar_g_campaign ? "" : autocvar_bot_suffix);
318         string name = (autocvar_bot_usemodelnames ? bot_model : bot_name);
319
320         if (name == "")
321         {
322                 name = ftos(etof(this));
323                 this.netname = this.netname_freeme = strzone(strcat(prefix, name, suffix));
324         }
325         else
326         {
327                 // number bots with identical names
328                 int j = 0;
329                 FOREACH_CLIENT(IS_BOT_CLIENT(it), {
330                         if(it.cleanname == name)
331                                 ++j;
332                 });
333                 if (j)
334                         this.netname = this.netname_freeme = strzone(strcat(prefix, name, "(", ftos(j), ")", suffix));
335                 else
336                         this.netname = this.netname_freeme = strzone(strcat(prefix, name, suffix));
337         }
338         this.cleanname = strzone(name);
339
340         // pick the model and skin
341         if(substring(bot_model, -4, 1) != ".")
342                 bot_model = strcat(bot_model, ".iqm");
343         this.playermodel = this.playermodel_freeme = strzone(strcat("models/player/", bot_model));
344         this.playerskin = this.playerskin_freeme = strzone(bot_skin);
345 }
346
347 void bot_custom_weapon_priority_setup()
348 {
349         static string bot_priority_far_prev;
350         static string bot_priority_mid_prev;
351         static string bot_priority_close_prev;
352         static string bot_priority_distances_prev;
353         float tokens, i, w;
354
355         bot_custom_weapon = false;
356
357         if(     autocvar_bot_ai_custom_weapon_priority_far == "" ||
358                 autocvar_bot_ai_custom_weapon_priority_mid == "" ||
359                 autocvar_bot_ai_custom_weapon_priority_close == "" ||
360                 autocvar_bot_ai_custom_weapon_priority_distances == ""
361         )
362                 return;
363
364         if (bot_priority_distances_prev != autocvar_bot_ai_custom_weapon_priority_distances)
365         {
366                 strcpy(bot_priority_distances_prev, autocvar_bot_ai_custom_weapon_priority_distances);
367                 tokens = tokenizebyseparator(autocvar_bot_ai_custom_weapon_priority_distances," ");
368
369                 if (tokens!=2)
370                         return;
371
372                 bot_distance_far = stof(argv(0));
373                 bot_distance_close = stof(argv(1));
374
375                 if(bot_distance_far < bot_distance_close){
376                         bot_distance_far = stof(argv(1));
377                         bot_distance_close = stof(argv(0));
378                 }
379         }
380
381         int c;
382
383         #define PARSE_WEAPON_PRIORITIES(dist) MACRO_BEGIN \
384                 if (bot_priority_##dist##_prev != autocvar_bot_ai_custom_weapon_priority_##dist) { \
385                         strcpy(bot_priority_##dist##_prev, autocvar_bot_ai_custom_weapon_priority_##dist); \
386                         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_##dist)," "); \
387                         bot_weapons_##dist[0] = -1; \
388                         c = 0; \
389                         for(i = 0; i < tokens && c < REGISTRY_COUNT(Weapons); ++i) { \
390                                 w = stof(argv(i)); \
391                                 if (w >= WEP_FIRST && w <= WEP_LAST) { \
392                                         bot_weapons_##dist[c] = w; \
393                                         ++c; \
394                                 } \
395                         } \
396                         if (c < REGISTRY_COUNT(Weapons)) \
397                                 bot_weapons_##dist[c] = -1; \
398                 } \
399         MACRO_END
400
401         PARSE_WEAPON_PRIORITIES(far);
402         PARSE_WEAPON_PRIORITIES(mid);
403         PARSE_WEAPON_PRIORITIES(close);
404
405         bot_custom_weapon = true;
406 }
407
408 void bot_endgame()
409 {
410         bot_relinkplayerlist();
411         entity e = bot_list;
412         while (e)
413         {
414                 setcolor(e, e.bot_preferredcolors);
415                 e = e.nextbot;
416         }
417         // if dynamic waypoints are ever implemented, save them here
418 }
419
420 void bot_relinkplayerlist()
421 {
422         player_count = 0;
423         currentbots = 0;
424         bot_list = NULL;
425
426         entity prevbot = NULL;
427         FOREACH_CLIENT(true,
428         {
429                 ++player_count;
430
431                 if(IS_BOT_CLIENT(it))
432                 {
433                         if (!IS_OBSERVER(it) && !bot_ispaused(it))
434                         {
435                                 if(prevbot)
436                                         prevbot.nextbot = it;
437                                 else
438                                         bot_list = it;
439                                 prevbot = it;
440                         }
441                         ++currentbots;
442                 }
443         });
444         if(prevbot)
445                 prevbot.nextbot = NULL;
446         bot_strategytoken = bot_list;
447         bot_strategytoken_taken = true;
448 }
449
450 void bot_clientdisconnect(entity this)
451 {
452         if (!IS_BOT_CLIENT(this))
453                 return;
454         bot_clearqueue(this);
455         strfree(this.cleanname);
456         strfree(this.netname_freeme);
457         strfree(this.playermodel_freeme);
458         strfree(this.playerskin_freeme);
459         if(this.bot_cmd_current)
460                 delete(this.bot_cmd_current);
461         if(bot_waypoint_queue_owner == this)
462                 bot_waypoint_queue_owner = NULL;
463 }
464
465 void bot_clientconnect(entity this)
466 {
467         if (!IS_BOT_CLIENT(this)) return;
468         this.bot_preferredcolors = this.clientcolors;
469         this.bot_nextthink = time - random();
470         this.isbot = true;
471         this.createdtime = this.bot_nextthink;
472
473         if(!this.bot_config_loaded) // This is needed so team overrider doesn't break between matches
474         {
475                 bot_setnameandstuff(this);
476                 bot_setclientfields(this);
477         }
478
479         havocbot_setupbot(this);
480 }
481
482 void bot_removefromlargestteam()
483 {
484         entity balance = TeamBalance_CheckAllowedTeams(NULL);
485         TeamBalance_GetTeamCounts(balance, NULL);
486
487         entity best = NULL;
488         float besttime = 0;
489         int bestcount = 0;
490
491         int bcount = 0;
492         FOREACH_CLIENT(it.isbot,
493         {
494                 ++bcount;
495
496                 if(!best)
497                 {
498                         best = it;
499                         besttime = it.createdtime;
500                 }
501
502                 int thiscount = 0;
503
504                 if (Team_IsValidTeam(it.team))
505                 {
506                         thiscount = TeamBalance_GetNumberOfPlayers(balance,
507                                 Team_TeamToIndex(it.team));
508                 }
509
510                 if(thiscount > bestcount)
511                 {
512                         bestcount = thiscount;
513                         besttime = it.createdtime;
514                         best = it;
515                 }
516                 else if(thiscount == bestcount && besttime < it.createdtime)
517                 {
518                         besttime = it.createdtime;
519                         best = it;
520                 }
521         });
522         TeamBalance_Destroy(balance);
523         if(!bcount)
524                 return; // no bots to remove
525         currentbots = currentbots - 1;
526         dropclient(best);
527 }
528
529 void bot_removenewest()
530 {
531         if(teamplay)
532         {
533                 bot_removefromlargestteam();
534                 return;
535         }
536
537         float besttime = 0;
538         entity best = NULL;
539         int bcount = 0;
540
541         FOREACH_CLIENT(it.isbot,
542         {
543                 ++bcount;
544
545                 if(!best)
546                 {
547                         best = it;
548                         besttime = it.createdtime;
549                 }
550
551                 if(besttime < it.createdtime)
552                 {
553                         besttime = it.createdtime;
554                         best = it;
555                 }
556         });
557
558         if(!bcount)
559                 return; // no bots to remove
560
561         currentbots = currentbots - 1;
562         dropclient(best);
563 }
564
565 void autoskill(float factor)
566 {
567         int bestbot = -1;
568         int bestplayer = -1;
569         FOREACH_CLIENT(IS_PLAYER(it), {
570                 if(IS_REAL_CLIENT(it))
571                         bestplayer = max(bestplayer, it.totalfrags - it.totalfrags_lastcheck);
572                 else
573                         bestbot = max(bestbot, it.totalfrags - it.totalfrags_lastcheck);
574         });
575
576         string msg = strcat("autoskill: best player got ", ftos(bestplayer), ", ""best bot got ", ftos(bestbot), "; ");
577         if(bestbot < 0 || bestplayer < 0)
578         {
579                 msg = strcat(msg, "not doing anything");
580                 // don't return, let it reset all counters below
581         }
582         else if(bestbot <= bestplayer * factor - 2)
583         {
584                 if(autocvar_skill < 17)
585                 {
586                         msg = strcat(msg, "2 frags difference, increasing skill");
587                         cvar_set("skill", ftos(autocvar_skill + 1));
588                         bprint("^2BOT SKILL UP!^7 Now at level ", ftos(autocvar_skill), "\n");
589                 }
590         }
591         else if(bestbot >= bestplayer * factor + 2)
592         {
593                 if(autocvar_skill > 0)
594                 {
595                         msg = strcat(msg, "2 frags difference, decreasing skill");
596                         cvar_set("skill", ftos(autocvar_skill - 1));
597                         bprint("^1BOT SKILL DOWN!^7 Now at level ", ftos(autocvar_skill), "\n");
598                 }
599         }
600         else
601         {
602                 msg = strcat(msg, "not doing anything");
603                 return;
604                 // don't reset counters, wait for them to accumulate
605         }
606         LOG_DEBUG(msg);
607
608         FOREACH_CLIENT(IS_PLAYER(it), { it.totalfrags_lastcheck = it.totalfrags; });
609 }
610
611 void bot_calculate_stepheightvec()
612 {
613         stepheightvec = autocvar_sv_stepheight * '0 0 1';
614         jumpheight_vec = (autocvar_sv_jumpvelocity ** 2) / (2 * autocvar_sv_gravity) * '0 0 1';
615         jumpstepheightvec = stepheightvec + jumpheight_vec * 0.85; // reduce it a bit to make the jumps easy
616         jumpheight_time = autocvar_sv_jumpvelocity / autocvar_sv_gravity;
617 }
618
619 bool bot_fixcount(bool multiple_per_frame)
620 {
621         int activerealplayers = 0;
622         int realplayers = 0;
623         if (MUTATOR_CALLHOOK(Bot_FixCount, activerealplayers, realplayers)) {
624                 activerealplayers = M_ARGV(0, int);
625                 realplayers = M_ARGV(1, int);
626         } else {
627                 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
628                         if(IS_PLAYER(it))
629                                 ++activerealplayers;
630                         ++realplayers;
631                 });
632         }
633
634         int bots;
635         // But don't remove bots immediately on level change, as the real players
636         // usually haven't rejoined yet
637         bots_would_leave = false;
638         if (autocvar_bot_vs_human && AVAILABLE_TEAMS == 2)
639                 bots = min(ceil(fabs(autocvar_bot_vs_human) * activerealplayers), maxclients - realplayers);
640         else if ((realplayers || autocvar_bot_join_empty || (currentbots > 0 && time < 5)))
641         {
642                 int minplayers = max(0, floor(autocvar_minplayers));
643                 if (teamplay)
644                         minplayers = max(0, floor(autocvar_minplayers_per_team) * AVAILABLE_TEAMS);
645                 int minbots = max(0, floor(autocvar_bot_number));
646
647                 // add bots to reach minplayers if needed
648                 bots = max(minbots, minplayers - activerealplayers);
649                 // cap bots to the max players allowed by the server
650                 int player_limit = GetPlayerLimit();
651                 if(player_limit)
652                         bots = min(bots, max(player_limit - activerealplayers, 0));
653                 bots = min(bots, maxclients - realplayers);
654
655                 if(bots > minbots)
656                         bots_would_leave = true;
657         }
658         else
659         {
660                 // if there are no players, remove bots
661                 bots = 0;
662         }
663
664         // only add one bot per frame to avoid utter chaos
665         if(time > botframe_nextthink)
666         {
667                 while (currentbots < bots)
668                 {
669                         if (bot_spawn() == NULL)
670                         {
671                                 bprint("Can not add bot, server full.\n");
672                                 return false;
673                         }
674                         if (!multiple_per_frame)
675                         {
676                                 break;
677                         }
678                 }
679                 while (currentbots > bots && bots >= 0)
680                         bot_removenewest();
681         }
682
683         return true;
684 }
685
686 void bot_serverframe()
687 {
688         if (intermission_running && currentbots > 0)
689         {
690                 // after the end of the match all bots stay unless all human players disconnect
691                 int realplayers = 0;
692                 FOREACH_CLIENT(IS_REAL_CLIENT(it), { ++realplayers; });
693                 if (!realplayers)
694                 {
695                         FOREACH_CLIENT(IS_BOT_CLIENT(it), { dropclient(it); });
696                         currentbots = 0;
697                 }
698                 return;
699         }
700
701         if (game_stopped)
702                 return;
703
704         // Added 0.5 to avoid possible addition + immediate removal of bots that would make them appear as
705         // spectators in the scoreboard and never go away. This issue happens at time 2 if map is changed
706         // with the gotomap command, minplayers is > 1 and human clients join as players very soon
707         // either intentionally or automatically (sv_spectate 0)
708         // A working workaround for this bug was implemented in commit fbd145044, see entcs_attach
709         if (time < 2.5)
710         {
711                 currentbots = -1;
712                 return;
713         }
714
715         if (currentbots == -1)
716         {
717                 // count bots already in the server from the previous match
718                 currentbots = 0;
719                 FOREACH_CLIENT(IS_BOT_CLIENT(it), { ++currentbots; });
720         }
721
722         if(autocvar_skill != skill)
723         {
724                 float wpcost_update = false;
725                 if(skill >= autocvar_bot_ai_bunnyhop_skilloffset && autocvar_skill < autocvar_bot_ai_bunnyhop_skilloffset)
726                         wpcost_update = true;
727                 if(skill < autocvar_bot_ai_bunnyhop_skilloffset && autocvar_skill >= autocvar_bot_ai_bunnyhop_skilloffset)
728                         wpcost_update = true;
729
730                 skill = autocvar_skill;
731                 if (wpcost_update)
732                         waypoint_updatecost_foralllinks();
733         }
734
735         bot_calculate_stepheightvec();
736         bot_navigation_movemode = ((autocvar_bot_navigation_ignoreplayers) ? MOVE_NOMONSTERS : MOVE_NORMAL);
737
738         if(time > autoskill_nextthink)
739         {
740                 float a;
741                 a = autocvar_skill_auto;
742                 if(a)
743                         autoskill(a);
744                 autoskill_nextthink = time + 5;
745         }
746
747         if(time > botframe_nextthink)
748         {
749                 if(!bot_fixcount(false))
750                         botframe_nextthink = time + 10;
751         }
752
753         if(botframe_spawnedwaypoints)
754         {
755                 if(autocvar_waypoint_benchmark)
756                         localcmd("quit\n");
757         }
758
759         if (currentbots > 0 || waypointeditor_enabled || autocvar_g_waypointeditor_auto)
760         if (botframe_spawnedwaypoints)
761         {
762                 if(botframe_cachedwaypointlinks)
763                 {
764                         if(!botframe_loadedforcedlinks)
765                                 waypoint_load_hardwiredlinks();
766                 }
767                 else
768                 {
769                         // TODO: Make this check cleaner
770                         IL_EACH(g_waypoints, time - it.nextthink > 10,
771                         {
772                                 waypoint_save_links();
773                                 break;
774                         });
775                 }
776         }
777         else
778         {
779                 botframe_spawnedwaypoints = true;
780                 waypoint_loadall();
781                 waypoint_load_links();
782         }
783
784         if (bot_list)
785         {
786                 // cycle the goal token from one bot to the next each frame
787                 // (this prevents them from all doing spawnfunc_waypoint searches on the same
788                 //  frame, which causes choppy framerates)
789                 if (bot_strategytoken_taken)
790                 {
791                         // give goal token to the first bot without goals; if all bots don't have
792                         // any goal (or are dead/frozen) simply give it to the next one
793                         bot_strategytoken_taken = false;
794                         entity bot_strategytoken_save = bot_strategytoken;
795                         while (true)
796                         {
797                                 if (bot_strategytoken)
798                                         bot_strategytoken = bot_strategytoken.nextbot;
799                                 if (!bot_strategytoken)
800                                         bot_strategytoken = bot_list;
801
802                                 if (!(IS_DEAD(bot_strategytoken) || STAT(FROZEN, bot_strategytoken))
803                                         && !bot_strategytoken.goalcurrent)
804                                         break;
805
806                                 if (!bot_strategytoken_save) // break loop if all the bots are dead or frozen
807                                         break;
808                                 if (bot_strategytoken == bot_strategytoken_save)
809                                         bot_strategytoken_save = NULL; // looped through all the bots
810                         }
811                 }
812
813                 if (botframe_nextdangertime < time)
814                 {
815                         float interval;
816                         interval = autocvar_bot_ai_dangerdetectioninterval;
817                         if (botframe_nextdangertime < time - interval * 1.5)
818                                 botframe_nextdangertime = time;
819                         botframe_nextdangertime = botframe_nextdangertime + interval;
820                         botframe_updatedangerousobjects(autocvar_bot_ai_dangerdetectionupdates);
821                 }
822         }
823
824         if (waypointeditor_enabled)
825                 botframe_showwaypointlinks();
826
827         if (autocvar_g_waypointeditor_auto)
828                 botframe_autowaypoints();
829
830         if (currentbots > 0)
831                 bot_custom_weapon_priority_setup();
832 }