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>
35 STATIC_INIT(bot) { bot_calculate_stepheightvec(); }
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)
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
46 entity bot = spawnclient();
50 currentbots = currentbots + 1;
51 bot_setnameandstuff(bot);
53 bot_setclientfields(bot);
54 PutClientInServer(bot);
59 void bot_think(entity this)
61 if (this.bot_nextthink > time)
64 this.flags &= ~FL_GODMODE;
66 this.flags |= FL_GODMODE;
68 // if bot skill is high enough don't limit their think frequency
70 this.bot_nextthink = max(time, this.bot_nextthink) + 0.005;
72 this.bot_nextthink = max(time, this.bot_nextthink) + max(0.01, autocvar_bot_ai_thinkinterval * min(14 / (skill + this.bot_aiskill + 14), 1));
74 if (!IS_PLAYER(this) || (autocvar_g_campaign && !campaign_bots_may_start))
76 CS(this).movement = '0 0 0';
77 this.bot_nextthink = time + 0.5;
83 this.v_angle = this.angles;
85 this.fixangle = false;
90 this.dmg_inflictor = NULL;
92 // if bot skill is high enough don't assign latency to them
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)
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;
119 if (time < game_starttime)
121 // block the bot during the countdown to game start
122 CS(this).movement = '0 0 0';
126 // if dead, just wait until we can respawn
127 if (IS_DEAD(this) || IS_OBSERVER(this))
129 if (bot_waypoint_queue_owner == this)
130 bot_waypoint_queue_owner = NULL;
132 CS(this).movement = '0 0 0';
133 if (IS_OBSERVER(this))
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
147 else if(this.aistatus & AI_STATUS_STUCK)
148 navigation_unstuck(this);
150 if (warmup_stage && !this.ready)
153 ReadyCount(); // this must be delayed until the bot has spawned
156 // now call the current bot AI (havocbot for example)
160 void bot_setnameandstuff(entity this)
163 int file, tokens, prio;
165 file = fopen(autocvar_bot_config_file, FILE_READ);
169 LOG_INFOF("Error: Can not open the bot configuration file '%s'", autocvar_bot_config_file);
174 entity balance = TeamBalance_CheckAllowedTeams(NULL);
175 TeamBalance_GetTeamCounts(balance, NULL);
176 int smallest_team = -1;
177 int smallest_count = -1;
180 for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
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)
189 smallest_count = count;
193 TeamBalance_Destroy(balance);
194 RandomSelection_Init();
195 while((readfile = fgets(file)))
197 if(substring(readfile, 0, 2) == "//")
199 if(substring(readfile, 0, 1) == "#")
201 // NOTE if the line is empty tokenizebyseparator(readfile, "\t")
202 // will create 1 empty token because there's no separator (bug?)
205 tokens = tokenizebyseparator(readfile, "\t");
210 bool conflict = false;
211 FOREACH_CLIENT(IS_BOT_CLIENT(it), {
212 if (s == it.cleanname)
220 if (teamplay && !(autocvar_bot_vs_human && AVAILABLE_TEAMS == 2))
222 int forced_team = stof(argv(5));
223 if (!Team_IsValidIndex(forced_team))
225 if (!forced_team || forced_team == smallest_team)
228 RandomSelection_AddString(readfile, 1, prio);
230 readfile = RandomSelection_chosen_string;
234 string bot_name, bot_model, bot_skin, bot_shirt, bot_pants;
236 tokens = tokenizebyseparator(readfile, "\t");
237 if(argv(0) != "") bot_name = argv(0);
238 else bot_name = "Bot";
240 if(argv(1) != "") bot_model = argv(1);
243 if(argv(2) != "") bot_skin = argv(2);
246 if(argv(3) != "" && stof(argv(3)) >= 0) bot_shirt = argv(3);
247 else bot_shirt = ftos(floor(random() * 15));
249 if(argv(4) != "" && stof(argv(4)) >= 0) bot_pants = argv(4);
250 else bot_pants = ftos(floor(random() * 15));
252 if (teamplay && !(autocvar_bot_vs_human && AVAILABLE_TEAMS == 2))
254 this.bot_forced_team = stof(argv(5));
255 if (!Team_IsValidIndex(this.bot_forced_team))
256 this.bot_forced_team = 0;
259 this.bot_forced_team = 0;
263 #define READSKILL(f, w, r) MACRO_BEGIN \
264 if(argv(prio) != "") \
265 this.f = stof(argv(prio)) * w; \
267 this.f = (!autocvar_g_campaign) * (2 * random() - 1) * r * w; \
270 //print(bot_name, ": ping=", argv(9), "\n");
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
276 READSKILL(bot_pingskill, 0.5, 0); // ping skill
278 READSKILL(bot_weaponskill, 2, 0); // weapon skill
279 READSKILL(bot_aggresskill, 1, 0); // aggre skill
280 READSKILL(bot_rangepreference, 1, 0); // read skill
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
286 READSKILL(bot_thinkskill, 1, 0.5); // think skill
287 READSKILL(bot_aiskill, 2, 0); // "ai" skill
289 // if bot skill is high enough don't limit their skill
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;
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);
310 this.bot_config_loaded = true;
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;
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);
322 name = ftos(etof(this));
323 this.netname = this.netname_freeme = strzone(strcat(prefix, name, suffix));
327 // number bots with identical names
329 FOREACH_CLIENT(IS_BOT_CLIENT(it), {
330 if(it.cleanname == name)
334 this.netname = this.netname_freeme = strzone(strcat(prefix, name, "(", ftos(j), ")", suffix));
336 this.netname = this.netname_freeme = strzone(strcat(prefix, name, suffix));
338 this.cleanname = strzone(name);
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);
347 void bot_custom_weapon_priority_setup()
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;
355 bot_custom_weapon = false;
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 == ""
364 if (bot_priority_distances_prev != autocvar_bot_ai_custom_weapon_priority_distances)
366 strcpy(bot_priority_distances_prev, autocvar_bot_ai_custom_weapon_priority_distances);
367 tokens = tokenizebyseparator(autocvar_bot_ai_custom_weapon_priority_distances," ");
372 bot_distance_far = stof(argv(0));
373 bot_distance_close = stof(argv(1));
375 if(bot_distance_far < bot_distance_close){
376 bot_distance_far = stof(argv(1));
377 bot_distance_close = stof(argv(0));
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; \
389 for(i = 0; i < tokens && c < REGISTRY_COUNT(Weapons); ++i) { \
391 if (w >= WEP_FIRST && w <= WEP_LAST) { \
392 bot_weapons_##dist[c] = w; \
396 if (c < REGISTRY_COUNT(Weapons)) \
397 bot_weapons_##dist[c] = -1; \
401 PARSE_WEAPON_PRIORITIES(far);
402 PARSE_WEAPON_PRIORITIES(mid);
403 PARSE_WEAPON_PRIORITIES(close);
405 bot_custom_weapon = true;
410 bot_relinkplayerlist();
414 setcolor(e, e.bot_preferredcolors);
417 // if dynamic waypoints are ever implemented, save them here
420 void bot_relinkplayerlist()
426 entity prevbot = NULL;
431 if(IS_BOT_CLIENT(it))
433 if (!IS_OBSERVER(it) && !bot_ispaused(it))
436 prevbot.nextbot = it;
445 prevbot.nextbot = NULL;
446 bot_strategytoken = bot_list;
447 bot_strategytoken_taken = true;
450 void bot_clientdisconnect(entity this)
452 if (!IS_BOT_CLIENT(this))
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;
465 void bot_clientconnect(entity this)
467 if (!IS_BOT_CLIENT(this)) return;
468 this.bot_preferredcolors = this.clientcolors;
469 this.bot_nextthink = time - random();
471 this.createdtime = this.bot_nextthink;
473 if(!this.bot_config_loaded) // This is needed so team overrider doesn't break between matches
475 bot_setnameandstuff(this);
476 bot_setclientfields(this);
479 havocbot_setupbot(this);
482 void bot_removefromlargestteam()
484 entity balance = TeamBalance_CheckAllowedTeams(NULL);
485 TeamBalance_GetTeamCounts(balance, NULL);
492 FOREACH_CLIENT(it.isbot,
499 besttime = it.createdtime;
504 if (Team_IsValidTeam(it.team))
506 thiscount = TeamBalance_GetNumberOfPlayers(balance,
507 Team_TeamToIndex(it.team));
510 if(thiscount > bestcount)
512 bestcount = thiscount;
513 besttime = it.createdtime;
516 else if(thiscount == bestcount && besttime < it.createdtime)
518 besttime = it.createdtime;
522 TeamBalance_Destroy(balance);
524 return; // no bots to remove
525 currentbots = currentbots - 1;
529 void bot_removenewest()
533 bot_removefromlargestteam();
541 FOREACH_CLIENT(it.isbot,
548 besttime = it.createdtime;
551 if(besttime < it.createdtime)
553 besttime = it.createdtime;
559 return; // no bots to remove
561 currentbots = currentbots - 1;
565 void autoskill(float factor)
569 FOREACH_CLIENT(IS_PLAYER(it), {
570 if(IS_REAL_CLIENT(it))
571 bestplayer = max(bestplayer, it.totalfrags - it.totalfrags_lastcheck);
573 bestbot = max(bestbot, it.totalfrags - it.totalfrags_lastcheck);
576 string msg = strcat("autoskill: best player got ", ftos(bestplayer), ", ""best bot got ", ftos(bestbot), "; ");
577 if(bestbot < 0 || bestplayer < 0)
579 msg = strcat(msg, "not doing anything");
580 // don't return, let it reset all counters below
582 else if(bestbot <= bestplayer * factor - 2)
584 if(autocvar_skill < 17)
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");
591 else if(bestbot >= bestplayer * factor + 2)
593 if(autocvar_skill > 0)
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");
602 msg = strcat(msg, "not doing anything");
604 // don't reset counters, wait for them to accumulate
608 FOREACH_CLIENT(IS_PLAYER(it), { it.totalfrags_lastcheck = it.totalfrags; });
611 void bot_calculate_stepheightvec()
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;
619 bool bot_fixcount(bool multiple_per_frame)
621 int activerealplayers = 0;
623 if (MUTATOR_CALLHOOK(Bot_FixCount, activerealplayers, realplayers)) {
624 activerealplayers = M_ARGV(0, int);
625 realplayers = M_ARGV(1, int);
627 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
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)))
642 int minplayers = max(0, floor(autocvar_minplayers));
644 minplayers = max(0, floor(autocvar_minplayers_per_team) * AVAILABLE_TEAMS);
645 int minbots = max(0, floor(autocvar_bot_number));
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();
652 bots = min(bots, max(player_limit - activerealplayers, 0));
653 bots = min(bots, maxclients - realplayers);
656 bots_would_leave = true;
660 // if there are no players, remove bots
664 // only add one bot per frame to avoid utter chaos
665 if(time > botframe_nextthink)
667 while (currentbots < bots)
669 if (bot_spawn() == NULL)
671 bprint("Can not add bot, server full.\n");
674 if (!multiple_per_frame)
679 while (currentbots > bots && bots >= 0)
686 void bot_serverframe()
688 if (intermission_running && currentbots > 0)
690 // after the end of the match all bots stay unless all human players disconnect
692 FOREACH_CLIENT(IS_REAL_CLIENT(it), { ++realplayers; });
695 FOREACH_CLIENT(IS_BOT_CLIENT(it), { dropclient(it); });
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
715 if (currentbots == -1)
717 // count bots already in the server from the previous match
719 FOREACH_CLIENT(IS_BOT_CLIENT(it), { ++currentbots; });
722 if(autocvar_skill != skill)
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;
730 skill = autocvar_skill;
732 waypoint_updatecost_foralllinks();
735 bot_calculate_stepheightvec();
736 bot_navigation_movemode = ((autocvar_bot_navigation_ignoreplayers) ? MOVE_NOMONSTERS : MOVE_NORMAL);
738 if(time > autoskill_nextthink)
741 a = autocvar_skill_auto;
744 autoskill_nextthink = time + 5;
747 if(time > botframe_nextthink)
749 if(!bot_fixcount(false))
750 botframe_nextthink = time + 10;
753 if(botframe_spawnedwaypoints)
755 if(autocvar_waypoint_benchmark)
759 if (currentbots > 0 || waypointeditor_enabled || autocvar_g_waypointeditor_auto)
760 if (botframe_spawnedwaypoints)
762 if(botframe_cachedwaypointlinks)
764 if(!botframe_loadedforcedlinks)
765 waypoint_load_hardwiredlinks();
769 // TODO: Make this check cleaner
770 IL_EACH(g_waypoints, time - it.nextthink > 10,
772 waypoint_save_links();
779 botframe_spawnedwaypoints = true;
781 waypoint_load_links();
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)
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;
797 if (bot_strategytoken)
798 bot_strategytoken = bot_strategytoken.nextbot;
799 if (!bot_strategytoken)
800 bot_strategytoken = bot_list;
802 if (!(IS_DEAD(bot_strategytoken) || STAT(FROZEN, bot_strategytoken))
803 && !bot_strategytoken.goalcurrent)
806 if (!bot_strategytoken_save) // break loop if all the bots are dead or frozen
808 if (bot_strategytoken == bot_strategytoken_save)
809 bot_strategytoken_save = NULL; // looped through all the bots
813 if (botframe_nextdangertime < time)
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);
824 if (waypointeditor_enabled)
825 botframe_showwaypointlinks();
827 if (autocvar_g_waypointeditor_auto)
828 botframe_autowaypoints();
831 bot_custom_weapon_priority_setup();