3 #include <common/deathtypes/all.qh>
4 #include <common/gamemodes/_mod.qh>
5 #include <common/teams.qh>
6 #include <server/bot/api.qh>
7 #include <server/bot/default/cvars.qh>
8 #include <server/campaign.qh>
9 #include <server/client.qh>
10 #include <server/command/vote.qh>
11 #include <server/damage.qh>
12 #include <server/gamelog.qh>
13 #include <server/mutators/_mod.qh>
14 #include <server/race.qh>
15 #include <server/scores.qh>
16 #include <server/scores_rules.qh>
18 /// \brief Describes a state of team balance entity.
21 TEAM_BALANCE_UNINITIALIZED, ///< The team balance has not been initialized.
22 /// \brief TeamBalance_CheckAllowedTeams has been called.
23 TEAM_BALANCE_TEAMS_CHECKED,
24 /// \brief TeamBalance_GetTeamCounts has been called.
25 TEAM_BALANCE_TEAM_COUNTS_FILLED
28 /// \brief Indicates that the player is not allowed to join a team.
29 const int TEAM_NOT_ALLOWED = -1;
31 .int m_team_balance_state; ///< Holds the state of the team balance entity.
32 .entity m_team_balance_team[NUM_TEAMS]; ///< ???
34 .float m_team_score; ///< The score of the team.
35 .int m_num_players; ///< Number of players (both humans and bots) in a team.
36 .int m_num_bots; ///< Number of bots in a team.
37 .int m_num_players_alive; ///< Number of alive players in a team.
38 .int m_num_owned_items; ///< Number of items owned by a team.
40 string autocvar_g_forced_team_red;
41 string autocvar_g_forced_team_blue;
42 string autocvar_g_forced_team_yellow;
43 string autocvar_g_forced_team_pink;
45 entity g_team_entities[NUM_TEAMS]; ///< Holds global team entities.
49 if (g_team_entities[0])
51 for (int i = 0; i < NUM_TEAMS; ++i)
53 g_team_entities[i] = new_pure(team_entity);
57 entity Team_GetTeamFromIndex(int index)
59 if (!Team_IsValidIndex(index))
61 LOG_FATALF("Index is invalid: %f", index);
63 return g_team_entities[index - 1];
66 entity Team_GetTeam(int team_num)
68 if (!Team_IsValidTeam(team_num))
70 LOG_FATALF("Value is invalid: %f", team_num);
72 return g_team_entities[Team_TeamToIndex(team_num) - 1];
75 float Team_GetTeamScore(entity team_ent)
77 return team_ent.m_team_score;
80 void Team_SetTeamScore(entity team_ent, float score)
82 team_ent.m_team_score = score;
85 int Team_GetNumberOfAlivePlayers(entity team_ent)
87 return team_ent.m_num_players_alive;
90 void Team_SetNumberOfAlivePlayers(entity team_ent, int number)
92 team_ent.m_num_players_alive = number;
95 int Team_GetWinnerAliveTeam()
98 for (int i = 0; i < NUM_TEAMS; ++i)
100 if (g_team_entities[i].m_num_players_alive > 0)
104 winner = Team_IndexToTeam(i + 1);
107 return (winner ? winner : -1);
110 int Team_GetNumberOfAliveTeams()
113 for (int i = 0; i < NUM_TEAMS; ++i)
115 if (g_team_entities[i].m_num_players_alive > 0)
123 int Team_GetWinnerTeam_WithOwnedItems(int min_control_points)
126 for (int i = 0; i < NUM_TEAMS; ++i)
128 if (g_team_entities[i].m_num_owned_items >= min_control_points)
132 winner = Team_IndexToTeam(i + 1);
135 return (winner ? winner : -1);
138 int Team_GetNumberOfOwnedItems(entity team_ent)
140 return team_ent.m_num_owned_items;
143 void Team_SetNumberOfOwnedItems(entity team_ent, int number)
145 team_ent.m_num_owned_items = number;
148 int Team_GetNumberOfTeamsWithOwnedItems()
151 for (int i = 0; i < NUM_TEAMS; ++i)
153 if (g_team_entities[i].m_num_owned_items > 0)
161 void setcolor(entity this, int clr)
164 this.clientcolors = clr;
165 this.team = (clr & 15) + 1;
167 builtin_setcolor(this, clr);
171 bool Entity_HasValidTeam(entity this)
173 return Team_IsValidTeam(this.team);
176 int Entity_GetTeamIndex(entity this)
178 return Team_TeamToIndex(this.team);
181 entity Entity_GetTeam(entity this)
183 int index = Entity_GetTeamIndex(this);
184 if (!Team_IsValidIndex(index))
188 return Team_GetTeamFromIndex(index);
191 void SetPlayerColors(entity player, float _color)
193 float pants = _color & 0x0F;
194 float shirt = _color & 0xF0;
197 setcolor(player, 16 * pants + pants);
201 setcolor(player, shirt + pants);
205 bool Player_SetTeamIndex(entity player, int index)
207 int new_team = Team_IndexToTeam(index);
208 if (player.team == new_team)
212 // This is important when players join the game and one of their
213 // color matches the team color while other doesn't. For example
214 // [BOT]Lion: color 0 4.
215 SetPlayerColors(player, new_team - 1);
219 int old_index = Team_TeamToIndex(player.team);
220 if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, old_index, index) == true)
222 // Mutator has blocked team change.
231 SetPlayerColors(player, new_team - 1);
233 MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_index, index);
237 /** Returns true when enough players are queued that the next will join directly
238 * to the only available team (also triggering the joins of the queued players).
239 * Optionally only counts players who selected a specific team when joining the queue.
241 bool QueuedPlayersReady(entity this, bool checkspecificteam)
243 int numplayersqueued = 0;
245 FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != this
246 && (checkspecificteam ? it.wants_join > 0 : it.wants_join),
248 LOG_DEBUGF("Player %s is waiting to join team %d", it.netname, it.wants_join);
250 if (numplayersqueued >= AVAILABLE_TEAMS - 1)
254 LOG_DEBUG("No players waiting to join.");
258 bool SetPlayerTeam(entity player, int team_index, int type)
260 int old_team_index = Entity_GetTeamIndex(player);
262 if (!Player_SetTeamIndex(player, team_index))
265 LogTeamChange(player.playerid, player.team, type);
267 if (team_index != old_team_index)
269 KillPlayerForTeamChange(player);
270 PlayerScore_Clear(player); // works only in game modes without teams
272 if (!IS_BOT_CLIENT(player))
273 TeamBalance_AutoBalanceBots();
275 if (team_index != -1)
277 if (!queuePlayer(player, team_index))
279 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(player.team, INFO_JOIN_PLAY_TEAM), player.netname);
280 player.team_selected = true; // no autoselect in Join()
285 if (team_index == -1)
287 if (autocvar_sv_maxidle_playertospectator > 0 && CS(player).idlekick_lasttimeleft)
289 // this done here so it happens even when manually speccing during the countdown
290 Kill_Notification(NOTIF_ONE_ONLY, player, MSG_CENTER, CPID_IDLING);
291 CS(player).idlekick_lasttimeleft = 0;
293 else if (!CS(player).just_joined && player.frags != FRAGS_SPECTATOR)
295 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_SPECTATE, player.netname);
302 void Player_SetTeamIndexChecked(entity player, int team_index)
308 if (!Team_IsValidIndex(team_index))
312 if ((autocvar_g_campaign) || (autocvar_g_changeteam_banned &&
313 CS(player).wasplayer))
315 Send_Notification(NOTIF_ONE, player, MSG_INFO,
316 INFO_TEAMCHANGE_NOTALLOWED);
319 entity balance = TeamBalance_CheckAllowedTeams(player);
320 if (team_index == 1 && !TeamBalance_IsTeamAllowedInternal(balance, 1))
324 if (team_index == 4 && !TeamBalance_IsTeamAllowedInternal(balance, 4))
328 if (team_index == 3 && !TeamBalance_IsTeamAllowedInternal(balance, 3))
332 if (team_index == 2 && !TeamBalance_IsTeamAllowedInternal(balance, 2))
336 // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
337 if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
339 TeamBalance_GetTeamCounts(balance, player);
340 if ((Team_IndexToBit(team_index) & TeamBalance_FindBestTeams(balance,
341 player, false)) == 0)
343 Send_Notification(NOTIF_ONE, player, MSG_INFO,
344 INFO_TEAMCHANGE_LARGERTEAM);
345 TeamBalance_Destroy(balance);
349 TeamBalance_Destroy(balance);
351 // g_balance_teams_queue: before joining the queue,
352 // check if a queued player already chose the selected team
353 if (!IS_BOT_CLIENT(player) && IS_QUEUE_NEEDED(player))
355 FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != player && it.wants_join == team_index,
357 Send_Notification(NOTIF_ONE, player, MSG_CENTER, APP_TEAM_NUM(Team_IndexToTeam(team_index), CENTER_JOIN_PREVENT_QUEUE_TEAM_FAIL), it.netname);
358 player.team_selected = false;
363 SetPlayerTeam(player, team_index, TEAM_CHANGE_MANUAL);
366 bool MoveToTeam(entity client, int team_index, int type)
368 //PrintToChatAll(sprintf("MoveToTeam: %s, %f", client.netname, team_index));
369 int lockteams_backup = lockteams; // backup any team lock
370 lockteams = 0; // disable locked teams
371 if (!SetPlayerTeam(client, team_index, type))
373 lockteams = lockteams_backup; // restore the team lock
376 lockteams = lockteams_backup; // restore the team lock
380 bool Player_HasRealForcedTeam(entity player)
382 return player.team_forced > TEAM_FORCE_DEFAULT;
385 int Player_GetForcedTeamIndex(entity player)
387 return player.team_forced;
390 void Player_SetForcedTeamIndex(entity player, int team_index)
394 case TEAM_FORCE_SPECTATOR:
395 case TEAM_FORCE_DEFAULT:
397 player.team_forced = team_index;
402 if (!Team_IsValidIndex(team_index))
404 LOG_FATAL("Invalid team index.");
408 player.team_forced = team_index;
415 void Player_DetermineForcedTeam(entity player)
417 if (autocvar_g_campaign)
419 if (IS_REAL_CLIENT(player)) // only players, not bots
421 if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
423 player.team_forced = autocvar_g_campaign_forceteam;
427 player.team_forced = TEAM_FORCE_DEFAULT;
431 else if (PlayerInList(player, autocvar_g_forced_team_red))
433 player.team_forced = 1;
435 else if (PlayerInList(player, autocvar_g_forced_team_blue))
437 player.team_forced = 2;
439 else if (PlayerInList(player, autocvar_g_forced_team_yellow))
441 player.team_forced = 3;
443 else if (PlayerInList(player, autocvar_g_forced_team_pink))
445 player.team_forced = 4;
449 switch (autocvar_g_forced_team_otherwise)
453 player.team_forced = 1;
458 player.team_forced = 2;
463 player.team_forced = 3;
468 player.team_forced = 4;
474 player.team_forced = TEAM_FORCE_SPECTATOR;
479 player.team_forced = TEAM_FORCE_DEFAULT;
484 if (!teamplay && Player_HasRealForcedTeam(player))
486 player.team_forced = TEAM_FORCE_DEFAULT;
490 void TeamBalance_JoinBestTeam(entity player)
492 //PrintToChatAll(sprintf("TeamBalance_JoinBestTeam: %s", player.netname));
497 if (player.bot_forced_team)
501 entity balance = TeamBalance_CheckAllowedTeams(player);
502 if (Player_HasRealForcedTeam(player))
504 int forced_team_index = player.team_forced;
505 bool is_team_allowed = TeamBalance_IsTeamAllowedInternal(balance,
507 TeamBalance_Destroy(balance);
508 if (!is_team_allowed)
512 if (!SetPlayerTeam(player, forced_team_index, TEAM_CHANGE_AUTO))
518 int best_team_index = TeamBalance_FindBestTeam(balance, player, true);
519 TeamBalance_Destroy(balance);
520 if (!SetPlayerTeam(player, best_team_index, TEAM_CHANGE_AUTO))
526 entity TeamBalance_CheckAllowedTeams(entity for_whom)
528 entity balance = spawn();
529 for (int i = 0; i < NUM_TEAMS; ++i)
531 entity team_ent = balance.m_team_balance_team[i] = spawn();
532 team_ent.m_team_score = g_team_entities[i].m_team_score;
533 team_ent.m_num_players = TEAM_NOT_ALLOWED;
534 team_ent.m_num_bots = 0;
536 setthink(balance, TeamBalance_Destroy);
537 balance.nextthink = time;
540 string teament_name = string_null;
541 bool mutator_returnvalue = MUTATOR_CALLHOOK(TeamBalance_CheckAllowedTeams,
542 teams_mask, teament_name, for_whom);
543 teams_mask = M_ARGV(0, float);
544 teament_name = M_ARGV(1, string);
545 if (mutator_returnvalue)
547 for (int i = 0; i < NUM_TEAMS; ++i)
549 if (teams_mask & BIT(i))
551 balance.m_team_balance_team[i].m_num_players = 0;
558 entity head = find(NULL, classname, teament_name);
561 if (Team_IsValidTeam(head.team))
563 TeamBalance_GetTeam(balance, head.team).m_num_players = 0;
565 head = find(head, classname, teament_name);
569 // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
570 if (autocvar_bot_vs_human && AVAILABLE_TEAMS == 2 && for_whom)
572 if (autocvar_bot_vs_human > 0)
574 // find last team available
575 if (IS_BOT_CLIENT(for_whom))
577 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
579 TeamBalance_BanTeamsExcept(balance, 4);
581 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
583 TeamBalance_BanTeamsExcept(balance, 3);
587 TeamBalance_BanTeamsExcept(balance, 2);
589 // no further cases, we know at least 2 teams exist
593 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
595 TeamBalance_BanTeamsExcept(balance, 1);
597 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
599 TeamBalance_BanTeamsExcept(balance, 2);
603 TeamBalance_BanTeamsExcept(balance, 3);
605 // no further cases, bots have one of the teams
610 // find first team available
611 if (IS_BOT_CLIENT(for_whom))
613 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
615 TeamBalance_BanTeamsExcept(balance, 1);
617 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
619 TeamBalance_BanTeamsExcept(balance, 2);
623 TeamBalance_BanTeamsExcept(balance, 3);
625 // no further cases, we know at least 2 teams exist
629 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
631 TeamBalance_BanTeamsExcept(balance, 4);
633 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
635 TeamBalance_BanTeamsExcept(balance, 3);
639 TeamBalance_BanTeamsExcept(balance, 2);
641 // no further cases, bots have one of the teams
648 balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
652 // if player has a forced team, ONLY allow that one
653 for (int i = 1; i <= NUM_TEAMS; ++i)
655 if (for_whom.team_forced == i &&
656 TeamBalance_IsTeamAllowedInternal(balance, i))
658 TeamBalance_BanTeamsExcept(balance, i);
662 balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
666 void TeamBalance_Destroy(entity balance)
672 for (int i = 0; i < NUM_TEAMS; ++i)
674 delete(balance.(m_team_balance_team[i]));
679 int TeamBalance_GetAllowedTeams(entity balance)
683 LOG_FATAL("Team balance entity is NULL.");
685 if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
687 LOG_FATAL("Team balance entity is not initialized.");
690 for (int i = 1; i <= NUM_TEAMS; ++i)
692 if (TeamBalance_IsTeamAllowedInternal(balance, i))
694 result |= Team_IndexToBit(i);
700 bool TeamBalance_AreEqual(entity ignore, bool would_leave)
702 entity balance = TeamBalance_CheckAllowedTeams(ignore);
703 TeamBalance_GetTeamCounts(balance, ignore);
705 bool equality = true;
710 for(int i = 1; i <= AVAILABLE_TEAMS; ++i)
712 total = TeamBalance_GetTeamFromIndex(balance, i).m_num_players;
713 bots += TeamBalance_GetTeamFromIndex(balance, i).m_num_bots;
714 if(i > 1 && total != prev_total)
721 TeamBalance_Destroy(balance);
723 // Ignore if there are "ghost" bots that would leave if anyone joined
724 if (would_leave && bots > autocvar_bot_number)
730 entity remove_countdown;
731 void Remove_Countdown(entity this)
733 if(this.lifetime <= 0 || TeamBalance_AreEqual(NULL, false))
735 if(this.lifetime <= 0)
737 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_MOVETOSPEC_REMOVE, playername(remove_countdown.enemy.netname, remove_countdown.enemy.team, true));
738 PutObserverInServer(remove_countdown.enemy, true, true);
741 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_REMOVE);
744 remove_countdown = NULL;
746 TeamBalance_RemoveExcessPlayers(NULL); // Check again for excess players in case someone also left while in countdown
751 this.nextthink = time + 1;
754 // FIXME: support more than 2 teams, the notification will be... awkward
755 // FIXME: also don't kick the fc/bc/kc lol
756 void TeamBalance_RemoveExcessPlayers(entity ignore)
758 if(AVAILABLE_TEAMS != 2 || autocvar_g_campaign) return;
760 entity balance = TeamBalance_CheckAllowedTeams(ignore);
761 TeamBalance_GetTeamCounts(balance, ignore);
765 for(int i = 1; i <= AVAILABLE_TEAMS; ++i)
767 int cur = TeamBalance_GetTeamFromIndex(balance, i).m_num_players;
768 if(i == 1 || cur < min)
772 for(int tmi = 1; tmi <= AVAILABLE_TEAMS; ++tmi)
774 int cur = TeamBalance_GetTeamFromIndex(balance, tmi).m_num_players;
775 if(cur > 0 && cur > min) // If this team has excess players
779 entity latest_join_pl = NULL;
781 FOREACH_CLIENT(IS_REAL_CLIENT(it) || INGAME(it), {
782 if(it.team == Team_IndexToTeam(tmi) && CS(it).startplaytime > latest_join)
784 latest_join = CS(it).startplaytime;
789 // Force player to spectate
792 // Send player to spectate
793 if(autocvar_g_balance_teams_remove_wait)
795 // Give a warning before moving to spect
796 if (!remove_countdown)
798 remove_countdown = new_pure(remove_countdown);
799 setthink(remove_countdown, Remove_Countdown);
800 remove_countdown.nextthink = time;
801 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_MOVETOSPEC_REMOVE, playername(latest_join_pl.netname, latest_join_pl.team, true), autocvar_g_balance_teams_remove_wait);
803 remove_countdown.enemy = latest_join_pl;
804 remove_countdown.lifetime = autocvar_g_balance_teams_remove_wait;
808 // Move to spects immediately
809 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_MOVETOSPEC_REMOVE, latest_join_pl.netname);
810 PutObserverInServer(latest_join_pl, true, true);
816 TeamBalance_Destroy(balance);
819 bool TeamBalance_QueuedPlayersTagIn(entity ignore)
824 bool balanced = true;
825 int j, teamplayers, teamplayers_max = 0;
826 entity balance = TeamBalance_CheckAllowedTeams(ignore);
828 TeamBalance_GetTeamCounts(balance, ignore);
830 // find the target player count
831 for (j = 1; j <= AVAILABLE_TEAMS; ++j)
833 teamplayers = TeamBalance_GetTeamFromIndex(balance, j).m_num_players;
834 if(teamplayers > teamplayers_max)
835 teamplayers_max = teamplayers;
838 for (j = 1; j <= AVAILABLE_TEAMS; ++j)
840 teamplayers = TeamBalance_GetTeamFromIndex(balance, j).m_num_players;
841 // first pass: find player(s) who want to play on this specific team
842 FOREACH_CLIENT(it != ignore && it.wants_join == j,
844 if (teamplayers >= teamplayers_max)
849 // second pass: find player(s) who want to play on any team
850 FOREACH_CLIENT(it != ignore && it.wants_join < 0,
852 if (teamplayers >= teamplayers_max)
857 if (teamplayers < teamplayers_max)
861 TeamBalance_Destroy(balance);
865 bool TeamBalance_IsTeamAllowed(entity balance, int index)
869 LOG_FATAL("Team balance entity is NULL.");
871 if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
873 LOG_FATAL("Team balance entity is not initialized.");
875 if (!Team_IsValidIndex(index))
877 LOG_FATALF("Team index is invalid: %f",
880 return TeamBalance_IsTeamAllowedInternal(balance, index);
883 void TeamBalance_GetTeamCounts(entity balance, entity ignore)
887 LOG_FATAL("Team balance entity is NULL.");
889 if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
891 LOG_FATAL("Team balance entity is not initialized.");
893 if (MUTATOR_CALLHOOK(TeamBalance_GetTeamCounts) == true)
895 // Mutator has overriden the configuration.
896 for (int i = 1; i <= NUM_TEAMS; ++i)
898 entity team_ent = TeamBalance_GetTeamFromIndex(balance, i);
899 if (TeamBalanceTeam_IsAllowed(team_ent))
901 MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore);
902 team_ent.m_num_players = M_ARGV(2, float);
903 team_ent.m_num_bots = M_ARGV(3, float);
909 // Manually count all players.
918 continue; // Queued players aren't actually in the game.
921 // TODO: Reconsider when the player is truly on the team.
922 if (IS_CLIENT(it) || INGAME(it))
926 else if (Player_HasRealForcedTeam(it))
928 // Do we really need this? Probably not.
929 team_num = Team_IndexToTeam(it.team_forced); // reserve the spot
935 if (!Team_IsValidTeam(team_num))
939 entity team_ent = TeamBalance_GetTeam(balance, team_num);
940 if (!TeamBalanceTeam_IsAllowed(team_ent))
944 ++team_ent.m_num_players;
945 if (IS_BOT_CLIENT(it))
947 ++team_ent.m_num_bots;
952 // if the player who has a forced team has not joined yet, reserve the spot
953 if (autocvar_g_campaign)
955 if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
957 entity team_ent = TeamBalance_GetTeamFromIndex(balance,
958 autocvar_g_campaign_forceteam);
959 if (team_ent.m_num_players == team_ent.m_num_bots)
961 ++team_ent.m_num_players;
965 balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
968 int TeamBalance_GetNumberOfPlayers(entity balance, int index)
972 LOG_FATAL("Team balance entity is NULL.");
974 if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
976 LOG_FATAL("TeamBalance_GetTeamCounts has not been called.");
978 if (!Team_IsValidIndex(index))
980 LOG_FATALF("Team index is invalid: %f", index);
982 return balance.m_team_balance_team[index - 1].m_num_players;
985 int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
989 LOG_FATAL("Team balance entity is NULL.");
991 if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
993 LOG_FATAL("Team balance entity is not initialized.");
995 // count how many players are in each team
998 TeamBalance_GetTeamCounts(balance, player);
1002 TeamBalance_GetTeamCounts(balance, NULL);
1004 int team_bits = TeamBalance_FindBestTeams(balance, player, true);
1007 LOG_FATALF("No teams available for %s\n", GetGametype());
1009 RandomSelection_Init();
1010 for (int i = 1; i <= NUM_TEAMS; ++i)
1012 if (team_bits & Team_IndexToBit(i))
1014 RandomSelection_AddFloat(i, 1, 1);
1017 return RandomSelection_chosen_float;
1020 int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
1022 if (balance == NULL)
1024 LOG_FATAL("Team balance entity is NULL.");
1026 if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
1028 LOG_FATAL("TeamBalance_GetTeamCounts has not been called.");
1030 if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
1032 return M_ARGV(1, float);
1035 int previous_team = 0;
1036 for (int i = 1; i <= NUM_TEAMS; ++i)
1038 if (!TeamBalance_IsTeamAllowedInternal(balance, i))
1042 if (previous_team == 0)
1044 team_bits = Team_IndexToBit(i);
1048 int compare = TeamBalance_CompareTeams(balance, i, previous_team,
1050 if (compare == TEAMS_COMPARE_LESS)
1052 team_bits = Team_IndexToBit(i);
1056 if (compare == TEAMS_COMPARE_EQUAL)
1058 team_bits |= Team_IndexToBit(i);
1065 int TeamBalance_CompareTeams(entity balance, int team_index_a, int team_index_b,
1066 entity player, bool use_score)
1068 if (balance == NULL)
1070 LOG_FATAL("Team balance entity is NULL.");
1072 if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
1074 LOG_FATAL("TeamBalance_GetTeamCounts has not been called.");
1076 if (!Team_IsValidIndex(team_index_a))
1078 LOG_FATALF("team_index_a is invalid: %f",
1081 if (!Team_IsValidIndex(team_index_b))
1083 LOG_FATALF("team_index_b is invalid: %f",
1086 if (team_index_a == team_index_b)
1088 return TEAMS_COMPARE_EQUAL;
1090 entity team_a = TeamBalance_GetTeamFromIndex(balance, team_index_a);
1091 entity team_b = TeamBalance_GetTeamFromIndex(balance, team_index_b);
1092 return TeamBalance_CompareTeamsInternal(team_a, team_b, player, use_score);
1095 void TeamBalance_AutoBalanceBots()
1097 // checks disabled because we always want auto-balanced bots
1098 //if (!(autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance))
1101 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1102 TeamBalance_GetTeamCounts(balance, NULL);
1103 int smallest_team_index = 0;
1104 int smallest_team_player_count = 0;
1105 for (int i = 1; i <= NUM_TEAMS; ++i)
1107 entity team_ = TeamBalance_GetTeamFromIndex(balance, i);
1108 if (!TeamBalanceTeam_IsAllowed(team_))
1112 int playercount = TeamBalanceTeam_GetNumberOfPlayers(team_);
1113 if (smallest_team_index == 0)
1115 smallest_team_index = i;
1116 smallest_team_player_count = playercount;
1118 else if (playercount < smallest_team_player_count)
1120 smallest_team_index = i;
1121 smallest_team_player_count = playercount;
1124 //PrintToChatAll(sprintf("Smallest team: %f", smallest_team_index));
1125 //PrintToChatAll(sprintf("Smallest team players: %f", smallest_team_player_count));
1126 entity switchable_bot = NULL;
1127 int teams = BITS(NUM_TEAMS);
1130 int largest_team_index = TeamBalance_GetLargestTeamIndex(balance,
1132 if (smallest_team_index == largest_team_index)
1134 TeamBalance_Destroy(balance);
1137 entity largest_team = TeamBalance_GetTeamFromIndex(balance,
1138 largest_team_index);
1139 int largest_team_player_count = TeamBalanceTeam_GetNumberOfPlayers(
1141 if (largest_team_player_count - smallest_team_player_count < 2)
1143 TeamBalance_Destroy(balance);
1146 //PrintToChatAll(sprintf("Largest team: %f", largest_team_index));
1147 //PrintToChatAll(sprintf("Largest team players: %f", largest_team_player_count));
1148 switchable_bot = TeamBalance_GetPlayerForTeamSwitch(largest_team_index,
1149 smallest_team_index, true);
1150 if (switchable_bot != NULL)
1154 teams &= ~Team_IndexToBit(largest_team_index);
1156 TeamBalance_Destroy(balance);
1157 if (switchable_bot == NULL)
1159 //PrintToChatAll("No bot found after searching through all the teams");
1162 SetPlayerTeam(switchable_bot, smallest_team_index, TEAM_CHANGE_AUTO);
1165 int TeamBalance_GetLargestTeamIndex(entity balance, int teams)
1167 int largest_team_index = 0;
1168 int largest_team_player_count = 0;
1169 for (int i = 1; i <= NUM_TEAMS; ++i)
1171 if (!(Team_IndexToBit(i) & teams))
1175 entity team_ = TeamBalance_GetTeamFromIndex(balance, i);
1176 if (!TeamBalanceTeam_IsAllowed(team_))
1180 int playercount = TeamBalanceTeam_GetNumberOfPlayers(team_);
1181 if (largest_team_index == 0)
1183 largest_team_index = i;
1184 largest_team_player_count = playercount;
1186 else if (playercount > largest_team_player_count)
1188 largest_team_index = i;
1189 largest_team_player_count = playercount;
1192 return largest_team_index;
1195 entity TeamBalance_GetPlayerForTeamSwitch(int source_team_index,
1196 int destination_team_index, bool is_bot)
1198 if (MUTATOR_CALLHOOK(TeamBalance_GetPlayerForTeamSwitch, source_team_index,
1199 destination_team_index, is_bot))
1201 return M_ARGV(3, entity);
1203 entity lowest_player = NULL;
1204 float lowest_score = FLOAT_MAX;
1205 FOREACH_CLIENT(Entity_GetTeamIndex(it) == source_team_index,
1207 if (IS_BOT_CLIENT(it) != is_bot)
1211 float temp_score = PlayerScore_Get(it, SP_SCORE);
1212 if (temp_score >= lowest_score)
1216 //PrintToChatAll(sprintf(
1217 // "Found %s with lowest score, checking allowed teams", it.netname));
1218 entity balance = TeamBalance_CheckAllowedTeams(it);
1219 if (TeamBalance_IsTeamAllowed(balance, source_team_index))
1221 //PrintToChatAll("Allowed");
1223 lowest_score = temp_score;
1227 //PrintToChatAll("Not allowed");
1229 TeamBalance_Destroy(balance);
1231 return lowest_player;
1234 void LogTeamChange(float player_id, float team_number, int type)
1236 if (!autocvar_sv_eventlog)
1244 GameLogEcho(sprintf(":team:%d:%d:%d", player_id, team_number, type));
1247 void KillPlayerForTeamChange(entity player)
1249 if (IS_DEAD(player))
1253 if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
1257 Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
1258 player.origin, '0 0 0');
1261 bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
1263 return balance.m_team_balance_team[index - 1].m_num_players !=
1267 void TeamBalance_BanTeamsExcept(entity balance, int index)
1269 for (int i = 1; i <= NUM_TEAMS; ++i)
1273 balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
1278 entity TeamBalance_GetTeamFromIndex(entity balance, int index)
1280 if (!Team_IsValidIndex(index))
1282 LOG_FATALF("Index is invalid: %f", index);
1284 return balance.m_team_balance_team[index - 1];
1287 entity TeamBalance_GetTeam(entity balance, int team_num)
1289 return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
1292 bool TeamBalanceTeam_IsAllowed(entity team_ent)
1294 return team_ent.m_num_players != TEAM_NOT_ALLOWED;
1297 int TeamBalanceTeam_GetNumberOfPlayers(entity team_ent)
1299 return team_ent.m_num_players;
1302 int TeamBalanceTeam_GetNumberOfBots(entity team_ent)
1304 return team_ent.m_num_bots;
1307 int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b,
1308 entity player, bool use_score)
1310 if (team_a == team_b)
1312 return TEAMS_COMPARE_EQUAL;
1314 if (!TeamBalanceTeam_IsAllowed(team_a) ||
1315 !TeamBalanceTeam_IsAllowed(team_b))
1317 return TEAMS_COMPARE_INVALID;
1319 int num_players_team_a = team_a.m_num_players;
1320 int num_players_team_b = team_b.m_num_players;
1321 if (IS_REAL_CLIENT(player) && bots_would_leave)
1323 num_players_team_a -= team_a.m_num_bots;
1324 num_players_team_b -= team_b.m_num_bots;
1326 if (num_players_team_a < num_players_team_b)
1328 return TEAMS_COMPARE_LESS;
1330 if (num_players_team_a > num_players_team_b)
1332 return TEAMS_COMPARE_GREATER;
1336 return TEAMS_COMPARE_EQUAL;
1338 if (team_a.m_team_score < team_b.m_team_score)
1340 return TEAMS_COMPARE_LESS;
1342 if (team_a.m_team_score > team_b.m_team_score)
1344 return TEAMS_COMPARE_GREATER;
1346 return TEAMS_COMPARE_EQUAL;
1349 void SV_ChangeTeam(entity player, int new_color)
1353 SetPlayerColors(player, new_color);
1355 if(!IS_CLIENT(player))
1363 Player_SetTeamIndexChecked(player, Team_TeamToIndex((new_color & 0x0F) + 1));