]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blobdiff - qcsrc/server/teamplay.qc
Teamplay: Made team balance entities destroy themselves on the next frame.
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / teamplay.qc
index 8b92f86b29d97874f7d96a009561c6b1015f7186..25acdd3e01595b82a8f584c44bb8f8a72bf1e2d0 100644 (file)
@@ -9,29 +9,42 @@
 
 #include "command/vote.qh"
 
-#include "mutators/_mod.qh"
+#include <server/mutators/_mod.qh>
 
 #include "../common/deathtypes/all.qh"
-#include "../common/gamemodes/_mod.qh"
+#include <common/gamemodes/_mod.qh>
 #include "../common/teams.qh"
 
+/// \brief Describes a state of team balance entity.
+enum
+{
+       TEAM_BALANCE_UNINITIALIZED, ///< The team balance has not been initialized.
+       /// \brief TeamBalance_CheckAllowedTeams has been called.
+       TEAM_BALANCE_TEAMS_CHECKED,
+       /// \brief TeamBalance_GetTeamCounts has been called.
+       TEAM_BALANCE_TEAM_COUNTS_FILLED
+};
+
 /// \brief Indicates that the player is not allowed to join a team.
 const int TEAM_NOT_ALLOWED = -1;
 
+.int m_team_balance_state; ///< Holds the state of the team balance entity.
+.entity m_team_balance_team[NUM_TEAMS]; ///< ???
+
 .float m_team_score; ///< The score of the team.
 .int m_num_players; ///< Number of players (both humans and bots) in a team.
 .int m_num_bots; ///< Number of bots in a team.
-.entity m_lowest_human; ///< Human with the lowest score in a team.
-.entity m_lowest_bot; ///< Bot with the lowest score in a team.
+.int m_num_players_alive; ///< Number of alive players in a team.
+.int m_num_control_points; ///< Number of control points owned by a team.
 
-entity g_team_entities[4]; ///< Holds global team entities.
+entity g_team_entities[NUM_TEAMS]; ///< Holds global team entities.
 
 STATIC_INIT(g_team_entities)
 {
-       g_team_entities[0] = spawn();
-       g_team_entities[1] = spawn();
-       g_team_entities[2] = spawn();
-       g_team_entities[3] = spawn();
+       for (int i = 0; i < NUM_TEAMS; ++i)
+       {
+               g_team_entities[i] = spawn();
+       }
 }
 
 entity Team_GetTeamFromIndex(int index)
@@ -49,47 +62,227 @@ entity Team_GetTeam(int team_num)
        {
                LOG_FATALF("Team_GetTeam: Value is invalid: %f", team_num);
        }
-       return g_team_entities[Team_TeamToNumber(team_num) - 1];
+       return g_team_entities[Team_TeamToIndex(team_num) - 1];
+}
+
+float Team_GetTeamScore(entity team_ent)
+{
+       return team_ent.m_team_score;
+}
+
+void Team_SetTeamScore(entity team_ent, float score)
+{
+       team_ent.m_team_score = score;
+}
+
+int Team_GetNumberOfAlivePlayers(entity team_ent)
+{
+       return team_ent.m_num_players_alive;
+}
+
+void Team_SetNumberOfAlivePlayers(entity team_ent, int number)
+{
+       team_ent.m_num_players_alive = number;
+}
+
+int Team_GetNumberOfAliveTeams()
+{
+       int result = 0;
+       for (int i = 0; i < NUM_TEAMS; ++i)
+       {
+               if (g_team_entities[i].m_num_players_alive > 0)
+               {
+                       ++result;
+               }
+       }
+       return result;
+}
+
+int Team_GetNumberOfControlPoints(entity team_ent)
+{
+       return team_ent.m_num_control_points;
+}
+
+void Team_SetNumberOfControlPoints(entity team_ent, int number)
+{
+       team_ent.m_num_control_points = number;
+}
+
+int Team_GetNumberOfTeamsWithControlPoints()
+{
+       int result = 0;
+       for (int i = 0; i < NUM_TEAMS; ++i)
+       {
+               if (g_team_entities[i].m_num_control_points > 0)
+               {
+                       ++result;
+               }
+       }
+       return result;
 }
 
-float Team_GetTeamScore(entity team_)
+void setcolor(entity this, int clr)
 {
-       return team_.m_team_score;
+#if 0
+       this.clientcolors = clr;
+       this.team = (clr & 15) + 1;
+#else
+       builtin_setcolor(this, clr);
+#endif
+}
+
+bool Entity_HasValidTeam(entity this)
+{
+       return Team_IsValidTeam(this.team);
 }
 
-void Team_SetTeamScore(entity team_, float score)
+int Entity_GetTeamIndex(entity this)
 {
-       team_.m_team_score = score;
+       return Team_TeamToIndex(this.team);
 }
 
-void CheckAllowedTeams(entity for_whom)
+entity Entity_GetTeam(entity this)
 {
-       for (int i = 0; i < 4; ++i)
+       int index = Entity_GetTeamIndex(this);
+       if (!Team_IsValidIndex(index))
        {
-               g_team_entities[i].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[i].m_num_bots = 0;
-               g_team_entities[i].m_lowest_human = NULL;
-               g_team_entities[i].m_lowest_bot = NULL;
+               return NULL;
+       }
+       return Team_GetTeamFromIndex(index);
+}
+
+void SetPlayerColors(entity player, float _color)
+{
+       float pants = _color & 0x0F;
+       float shirt = _color & 0xF0;
+       if (teamplay)
+       {
+               setcolor(player, 16 * pants + pants);
        }
+       else
+       {
+               setcolor(player, shirt + pants);
+       }
+}
+
+bool Player_SetTeamIndex(entity player, int index)
+{
+       int new_team = Team_IndexToTeam(index);
+       if (player.team == new_team)
+       {
+               if (new_team != -1)
+               {
+                       // This is important when players join the game and one of their
+                       // color matches the team color while other doesn't. For example
+                       // [BOT]Lion.
+                       SetPlayerColors(player, new_team - 1);
+               }
+               return true;
+       }
+       int old_index = Team_TeamToIndex(player.team);
+       if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, old_index, index) == true)
+       {
+               // Mutator has blocked team change.
+               return false;
+       }
+       if (new_team == -1)
+       {
+               player.team = -1;
+       }
+       else
+       {
+               SetPlayerColors(player, new_team - 1);
+       }
+       MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_index, index);
+       return true;
+}
+
+bool SetPlayerTeam(entity player, int team_index, int type)
+{
+       int old_team_index = Entity_GetTeamIndex(player);
+       if (!Player_SetTeamIndex(player, team_index))
+       {
+               return false;
+       }
+       LogTeamchange(player.playerid, player.team, type);
+       if (team_index != old_team_index)
+       {
+               Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(player.team,
+                       INFO_JOIN_PLAY_TEAM), player.netname);
+               KillPlayerForTeamChange(player);
+       }
+       return true;
+}
+
+bool MoveToTeam(entity client, int team_index, int type)
+{
+       //PrintToChatAll(sprintf("MoveToTeam: %s, %f", client.netname, team_index));
+       int lockteams_backup = lockteams;  // backup any team lock
+       lockteams = 0;  // disable locked teams
+       PlayerScore_Clear(client);
+       if (!SetPlayerTeam(client, team_index, type))
+       {
+               lockteams = lockteams_backup;  // restore the team lock
+               return false;
+       }
+       lockteams = lockteams_backup;  // restore the team lock
+       return true;
+}
+
+void KillPlayerForTeamChange(entity player)
+{
+       if (IS_DEAD(player))
+       {
+               return;
+       }
+       if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
+       {
+               return;
+       }
+       Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
+               player.origin, '0 0 0');
+}
+
+void LogTeamchange(float player_id, float team_number, int type)
+{
+       if(!autocvar_sv_eventlog)
+               return;
+
+       if(player_id < 1)
+               return;
+
+       GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
+}
+
+entity TeamBalance_CheckAllowedTeams(entity for_whom)
+{
+       entity balance = spawn();
+       for (int i = 0; i < NUM_TEAMS; ++i)
+       {
+               entity team_ent = balance.m_team_balance_team[i] = spawn();
+               team_ent.m_team_score = g_team_entities[i].m_team_score;
+               team_ent.m_num_players = TEAM_NOT_ALLOWED;
+               team_ent.m_num_bots = 0;
+       }
+       setthink(balance, TeamBalance_Destroy);
        
        int teams_mask = 0;     
        string teament_name = string_null;
-       bool mutator_returnvalue = MUTATOR_CALLHOOK(CheckAllowedTeams, teams_mask,
-               teament_name, for_whom);
+       bool mutator_returnvalue = MUTATOR_CALLHOOK(TeamBalance_CheckAllowedTeams,
+               teams_mask, teament_name, for_whom);
        teams_mask = M_ARGV(0, float);
        teament_name = M_ARGV(1, string);
        if (mutator_returnvalue)
        {
-               for (int i = 0; i < 4; ++i)
+               for (int i = 0; i < NUM_TEAMS; ++i)
                {
                        if (teams_mask & BIT(i))
                        {
-                               g_team_entities[i].m_num_players = 0;
+                               balance.m_team_balance_team[i].m_num_players = 0;
                        }
                }
        }
 
-       // find out what teams are allowed if necessary
        if (teament_name)
        {
                entity head = find(NULL, classname, teament_name);
@@ -97,7 +290,7 @@ void CheckAllowedTeams(entity for_whom)
                {
                        if (Team_IsValidTeam(head.team))
                        {
-                               Team_GetTeam(head.team).m_num_players = 0;
+                               TeamBalance_GetTeam(balance, head.team).m_num_players = 0;
                        }
                        head = find(head, classname, teament_name);
                }
@@ -112,45 +305,33 @@ void CheckAllowedTeams(entity for_whom)
                        // find last team available
                        if (IS_BOT_CLIENT(for_whom))
                        {
-                               if (Team_IsAllowed(g_team_entities[3]))
+                               if (TeamBalance_IsTeamAllowedInternal(balance, 4))
                                {
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 4);
                                }
-                               else if (Team_IsAllowed(g_team_entities[2]))
+                               else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
                                {
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 3);
                                }
                                else
                                {
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 2);
                                }
                                // no further cases, we know at least 2 teams exist
                        }
                        else
                        {
-                               if (Team_IsAllowed(g_team_entities[0]))
+                               if (TeamBalance_IsTeamAllowedInternal(balance, 1))
                                {
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 1);
                                }
-                               else if (Team_IsAllowed(g_team_entities[1]))
+                               else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
                                {
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 2);
                                }
                                else
                                {
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 3);
                                }
                                // no further cases, bots have one of the teams
                        }
@@ -160,45 +341,33 @@ void CheckAllowedTeams(entity for_whom)
                        // find first team available
                        if (IS_BOT_CLIENT(for_whom))
                        {
-                               if (Team_IsAllowed(g_team_entities[0]))
+                               if (TeamBalance_IsTeamAllowedInternal(balance, 1))
                                {
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 1);
                                }
-                               else if (Team_IsAllowed(g_team_entities[1]))
+                               else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
                                {
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 2);
                                }
                                else
                                {
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 3);
                                }
                                // no further cases, we know at least 2 teams exist
                        }
                        else
                        {
-                               if (Team_IsAllowed(g_team_entities[3]))
+                               if (TeamBalance_IsTeamAllowedInternal(balance, 4))
                                {
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 4);
                                }
-                               else if (Team_IsAllowed(g_team_entities[2]))
+                               else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
                                {
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 3);
                                }
                                else
                                {
-                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       TeamBalance_BanTeamsExcept(balance, 2);
                                }
                                // no further cases, bots have one of the teams
                        }
@@ -207,75 +376,100 @@ void CheckAllowedTeams(entity for_whom)
 
        if (!for_whom)
        {
-               return;
+               balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
+               return balance;
        }
 
        // if player has a forced team, ONLY allow that one
-       if (for_whom.team_forced == NUM_TEAM_1 && Team_IsAllowed(
-               g_team_entities[0]))
-       {
-               g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
-       }
-       else if (for_whom.team_forced == NUM_TEAM_2 && Team_IsAllowed(
-               g_team_entities[1]))
+       for (int i = 1; i <= NUM_TEAMS; ++i)
        {
-               g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+               if (for_whom.team_forced == Team_IndexToTeam(i) &&
+                       TeamBalance_IsTeamAllowedInternal(balance, i))
+               {
+                       TeamBalance_BanTeamsExcept(balance, i);
+               }
+               break;
        }
-       else if (for_whom.team_forced == NUM_TEAM_3 && Team_IsAllowed(
-               g_team_entities[2]))
+       balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
+       return balance;
+}
+
+void TeamBalance_Destroy(entity balance)
+{
+       if (balance == NULL)
        {
-               g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+               return;
        }
-       else if (for_whom.team_forced == NUM_TEAM_4 && Team_IsAllowed(
-               g_team_entities[3]))
+       for (int i = 0; i < NUM_TEAMS; ++i)
        {
-               g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
-               g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+               delete(balance.(m_team_balance_team[i]));
        }
+       delete(balance);
 }
 
-int GetAllowedTeams()
+int TeamBalance_GetAllowedTeams(entity balance)
 {
+       if (balance == NULL)
+       {
+               LOG_FATAL("TeamBalance_GetAllowedTeams: Team balance entity is NULL.");
+       }
+       if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
+       {
+               LOG_FATAL("TeamBalance_GetAllowedTeams: "
+                       "Team balance entity is not initialized.");
+       }
        int result = 0;
-       for (int i = 0; i < 4; ++i)
+       for (int i = 1; i <= NUM_TEAMS; ++i)
        {
-               if (Team_IsAllowed(g_team_entities[i]))
+               if (TeamBalance_IsTeamAllowedInternal(balance, i))
                {
-                       result |= BIT(i);
+                       result |= Team_IndexToBit(i);
                }
        }
        return result;
 }
 
-bool Team_IsAllowed(entity team_)
+bool TeamBalance_IsTeamAllowed(entity balance, int index)
 {
-       return team_.m_num_players != TEAM_NOT_ALLOWED;
+       if (balance == NULL)
+       {
+               LOG_FATAL("TeamBalance_IsTeamAllowed: Team balance entity is NULL.");
+       }
+       if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
+       {
+               LOG_FATAL("TeamBalance_IsTeamAllowed: "
+                       "Team balance entity is not initialized.");
+       }
+       if (!Team_IsValidIndex(index))
+       {
+               LOG_FATALF("TeamBalance_IsTeamAllowed: Team index is invalid: %f",
+                       index);
+       }
+       return TeamBalance_IsTeamAllowedInternal(balance, index);
 }
 
-void GetTeamCounts(entity ignore)
+void TeamBalance_GetTeamCounts(entity balance, entity ignore)
 {
-       if (MUTATOR_CALLHOOK(GetTeamCounts) == true)
+       if (balance == NULL)
+       {
+               LOG_FATAL("TeamBalance_GetTeamCounts: Team balance entity is NULL.");
+       }
+       if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
+       {
+               LOG_FATAL("TeamBalance_GetTeamCounts: "
+                       "Team balance entity is not initialized.");
+       }
+       if (MUTATOR_CALLHOOK(TeamBalance_GetTeamCounts) == true)
        {
                // Mutator has overriden the configuration.
-               for (int i = 0; i < 4; ++i)
+               for (int i = 1; i <= NUM_TEAMS; ++i)
                {
-                       entity team_ = g_team_entities[i];
-                       if (Team_IsAllowed(team_))
+                       entity team_ent = TeamBalance_GetTeamFromIndex(balance, i);
+                       if (TeamBalanceTeam_IsAllowed(team_ent))
                        {
-                               MUTATOR_CALLHOOK(GetTeamCount, Team_NumberToTeam(i + 1), ignore,
-                                       team_.m_num_players, team_.m_num_bots, team_.m_lowest_human,
-                                       team_.m_lowest_bot);
-                               team_.m_num_players = M_ARGV(2, float);
-                               team_.m_num_bots = M_ARGV(3, float);
-                               team_.m_lowest_human = M_ARGV(4, entity);
-                               team_.m_lowest_bot = M_ARGV(5, entity);
+                               MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore);
+                               team_ent.m_num_players = M_ARGV(2, float);
+                               team_ent.m_num_bots = M_ARGV(3, float);
                        }
                }
        }
@@ -305,39 +499,15 @@ void GetTeamCounts(entity ignore)
                        {
                                continue;
                        }
-                       entity team_ = Team_GetTeam(team_num);
-                       if (!Team_IsAllowed(team_))
+                       entity team_ent = TeamBalance_GetTeam(balance, team_num);
+                       if (!TeamBalanceTeam_IsAllowed(team_ent))
                        {
                                continue;
                        }
-                       ++team_.m_num_players;
+                       ++team_ent.m_num_players;
                        if (IS_BOT_CLIENT(it))
                        {
-                               ++team_.m_num_bots;
-                       }
-                       float temp_score = PlayerScore_Get(it, SP_SCORE);
-                       if (!IS_BOT_CLIENT(it))
-                       {
-                               if (team_.m_lowest_human == NULL)
-                               {
-                                       team_.m_lowest_human = it;
-                                       continue;
-                               }
-                               if (temp_score < PlayerScore_Get(team_.m_lowest_human,
-                                       SP_SCORE))
-                               {
-                                       team_.m_lowest_human = it;
-                               }
-                               continue;
-                       }
-                       if (team_.m_lowest_bot == NULL)
-                       {
-                               team_.m_lowest_bot = it;
-                               continue;
-                       }
-                       if (temp_score < PlayerScore_Get(team_.m_lowest_bot, SP_SCORE))
-                       {
-                               team_.m_lowest_bot = it;
+                               ++team_ent.m_num_bots;
                        }
                });
        }
@@ -347,499 +517,368 @@ void GetTeamCounts(entity ignore)
        {
                if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
                {
-                       entity team_ = Team_GetTeamFromIndex(autocvar_g_campaign_forceteam);
-                       if (team_.m_num_players == team_.m_num_bots)
+                       entity team_ent = TeamBalance_GetTeamFromIndex(balance,
+                               autocvar_g_campaign_forceteam);
+                       if (team_ent.m_num_players == team_ent.m_num_bots)
                        {
-                               ++team_.m_num_players;
+                               ++team_ent.m_num_players;
                        }
                }
        }
+       balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
 }
 
-int Team_GetNumberOfPlayers(entity team_)
-{
-       return team_.m_num_players;
-}
-
-int Team_GetNumberOfBots(entity team_)
-{
-       return team_.m_num_bots;
-}
-
-entity Team_GetLowestHuman(entity team_)
-{
-       return team_.m_lowest_human;
-}
-
-entity Team_GetLowestBot(entity team_)
-{
-       return team_.m_lowest_bot;
-}
-
-void TeamchangeFrags(entity e)
-{
-       PlayerScore_Clear(e);
-}
-
-void LogTeamchange(float player_id, float team_number, float type)
-{
-       if(!autocvar_sv_eventlog)
-               return;
-
-       if(player_id < 1)
-               return;
-
-       GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
-}
-
-void default_delayedinit(entity this)
-{
-       if(!scores_initialized)
-               ScoreRules_generic();
-}
-
-void InitGameplayMode()
+int TeamBalance_GetNumberOfPlayers(entity balance, int index)
 {
-       VoteReset();
-
-       // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
-       get_mi_min_max(1);
-       // assign reflectively to avoid "assignment to world" warning
-       int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
-           string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
-           if (v) {
-            putentityfieldstring(i, world, sprintf("%v", v));
-            if (++done == 2) break;
-        }
+       if (balance == NULL)
+       {
+               LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
+                       "Team balance entity is NULL.");
        }
-       // currently, NetRadiant's limit is 131072 qu for each side
-       // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
-       // set the distance according to map size but don't go over the limit to avoid issues with float precision
-       // in case somebody makes extremely large maps
-       max_shot_distance = min(230000, vlen(world.maxs - world.mins));
-
-       MapInfo_LoadMapSettings(mapname);
-       GameRules_teams(false);
-
-       if (!cvar_value_issafe(world.fog))
+       if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
        {
-               LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
-               world.fog = string_null;
+               LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
+                       "TeamBalance_GetTeamCounts has not been called.");
        }
-       if(MapInfo_Map_fog != "")
-               if(MapInfo_Map_fog == "none")
-                       world.fog = string_null;
-               else
-                       world.fog = strzone(MapInfo_Map_fog);
-       clientstuff = strzone(MapInfo_Map_clientstuff);
-
-       MapInfo_ClearTemps();
-
-       gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
-
-       cache_mutatormsg = strzone("");
-       cache_lastmutatormsg = strzone("");
-
-       InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
-}
-
-string GetClientVersionMessage(entity this)
-{
-       if (CS(this).version_mismatch) {
-               if(CS(this).version < autocvar_gameversion) {
-                       return strcat("This is Xonotic ", autocvar_g_xonoticversion,
-                               "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8");
-               } else {
-                       return strcat("This is Xonotic ", autocvar_g_xonoticversion,
-                               "\n^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8");
-               }
-       } else {
-               return strcat("Welcome to Xonotic ", autocvar_g_xonoticversion);
+       if (!Team_IsValidIndex(index))
+       {
+               LOG_FATALF("TeamBalance_GetNumberOfPlayers: Team index is invalid: %f",
+                       index);
        }
+       return balance.m_team_balance_team[index - 1].m_num_players;
 }
 
-string getwelcomemessage(entity this)
+int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
 {
-       MUTATOR_CALLHOOK(BuildMutatorsPrettyString, "");
-       string modifications = M_ARGV(0, string);
-
-       if(g_weaponarena)
+       if (balance == NULL)
        {
-               if(g_weaponarena_random)
-                       modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
-               else
-                       modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
+               LOG_FATAL("TeamBalance_FindBestTeam: Team balance entity is NULL.");
        }
-       else if(cvar("g_balance_blaster_weaponstartoverride") == 0)
-               modifications = strcat(modifications, ", No start weapons");
-       if(cvar("sv_gravity") < stof(cvar_defstring("sv_gravity")))
-               modifications = strcat(modifications, ", Low gravity");
-       if(g_weapon_stay && !g_cts)
-               modifications = strcat(modifications, ", Weapons stay");
-       if(g_jetpack)
-               modifications = strcat(modifications, ", Jet pack");
-       if(autocvar_g_powerups == 0)
-               modifications = strcat(modifications, ", No powerups");
-       if(autocvar_g_powerups > 0)
-               modifications = strcat(modifications, ", Powerups");
-       modifications = substring(modifications, 2, strlen(modifications) - 2);
-
-       string versionmessage = GetClientVersionMessage(this);
-       string s = strcat(versionmessage, "^8\n^8\nmatch type is ^1", gamemode_name, "^8\n");
-
-       if(modifications != "")
-               s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
-
-       if(cache_lastmutatormsg != autocvar_g_mutatormsg)
+       if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
        {
-               if(cache_lastmutatormsg)
-                       strunzone(cache_lastmutatormsg);
-               if(cache_mutatormsg)
-                       strunzone(cache_mutatormsg);
-               cache_lastmutatormsg = strzone(autocvar_g_mutatormsg);
-               cache_mutatormsg = strzone(cache_lastmutatormsg);
+               LOG_FATAL("TeamBalance_FindBestTeam: "
+                       "Team balance entity is not initialized.");
        }
-
-       if (cache_mutatormsg != "") {
-               s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
-       }
-
-       string mutator_msg = "";
-       MUTATOR_CALLHOOK(BuildGameplayTipsString, mutator_msg);
-       mutator_msg = M_ARGV(0, string);
-
-       s = strcat(s, mutator_msg); // trust that the mutator will do proper formatting
-
-       string motd = autocvar_sv_motd;
-       if (motd != "") {
-               s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
-       }
-       return s;
-}
-
-void setcolor(entity this, int clr)
-{
-#if 0
-       this.clientcolors = clr;
-       this.team = (clr & 15) + 1;
-#else
-       builtin_setcolor(this, clr);
-#endif
-}
-
-void SetPlayerColors(entity player, float _color)
-{
-       float pants = _color & 0x0F;
-       float shirt = _color & 0xF0;
-       if (teamplay)
+       // count how many players are in each team
+       if (ignore_player)
        {
-               setcolor(player, 16 * pants + pants);
+               TeamBalance_GetTeamCounts(balance, player);
        }
        else
        {
-               setcolor(player, shirt + pants);
+               TeamBalance_GetTeamCounts(balance, NULL);
        }
-}
-
-void KillPlayerForTeamChange(entity player)
-{
-       if (IS_DEAD(player))
+       int team_bits = TeamBalance_FindBestTeams(balance, player, true);
+       if (team_bits == 0)
        {
-               return;
+               LOG_FATALF("TeamBalance_FindBestTeam: No teams available for %s\n",
+                       MapInfo_Type_ToString(MapInfo_CurrentGametype()));
        }
-       if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
+       RandomSelection_Init();
+       for (int i = 1; i <= NUM_TEAMS; ++i)
        {
-               return;
+               if (team_bits & Team_IndexToBit(i))
+               {
+                       RandomSelection_AddFloat(i, 1, 1);
+               }
        }
-       Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
-               player.origin, '0 0 0');
+       return RandomSelection_chosen_float;
 }
 
-bool SetPlayerTeamSimple(entity player, int team_num)
+int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
 {
-       if (player.team == team_num)
+       if (balance == NULL)
        {
-               // This is important when players join the game and one of their color
-               // matches the team color while other doesn't. For example [BOT]Lion.
-               SetPlayerColors(player, team_num - 1);
-               return true;
+               LOG_FATAL("TeamBalance_FindBestTeams: Team balance entity is NULL.");
        }
-       if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, Team_TeamToNumber(
-               player.team), Team_TeamToNumber(team_num)) == true)
+       if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
        {
-               // Mutator has blocked team change.
-               return false;
+               LOG_FATAL("TeamBalance_FindBestTeams: "
+                       "TeamBalance_GetTeamCounts has not been called.");
        }
-       int old_team_num = player.team;
-       SetPlayerColors(player, team_num - 1);
-       MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_team_num, player.team);
-       return true;
-}
-
-bool SetPlayerTeam(entity player, int destination_team_index,
-       int source_team_index, bool no_print)
-{
-       int team_num = Team_NumberToTeam(destination_team_index);
-       if (!SetPlayerTeamSimple(player, team_num))
+       if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
        {
-               return false;
+               return M_ARGV(1, float);
        }
-       LogTeamchange(player.playerid, player.team, 3);  // log manual team join
-       if (no_print)
+       int team_bits = 0;
+       int previous_team = 0;
+       for (int i = 1; i <= NUM_TEAMS; ++i)
        {
-               return true;
+               if (!TeamBalance_IsTeamAllowedInternal(balance, i))
+               {
+                       continue;
+               }
+               if (previous_team == 0)
+               {
+                       team_bits = Team_IndexToBit(i);
+                       previous_team = i;
+                       continue;
+               }
+               int compare = TeamBalance_CompareTeams(balance, i, previous_team,
+                       player, use_score);
+               if (compare == TEAMS_COMPARE_LESS)
+               {
+                       team_bits = Team_IndexToBit(i);
+                       previous_team = i;
+                       continue;
+               }
+               if (compare == TEAMS_COMPARE_EQUAL)
+               {
+                       team_bits |= Team_IndexToBit(i);
+                       previous_team = i;
+               }
        }
-       bprint(playername(player, false), "^7 has changed from ",
-               Team_NumberToColoredFullName(source_team_index), "^7 to ",
-               Team_NumberToColoredFullName(destination_team_index), "\n");
-       return true;
+       return team_bits;
 }
 
-bool IsTeamSmallerThanTeam(int team_index_a, int team_index_b, entity player,
-       bool use_score)
+void TeamBalance_JoinBestTeam(entity this, bool force_best_team)
 {
-       if (!Team_IsValidIndex(team_index_a))
-       {
-               LOG_FATALF("IsTeamSmallerThanTeam: team_index_a is invalid: %f",
-                       team_index_a);
-       }
-       if (!Team_IsValidIndex(team_index_b))
+       //PrintToChatAll(sprintf("JoinBestTeam: %s, %f", this.netname, force_best_team));
+       // don't join a team if we're not playing a team game
+       if (!teamplay)
        {
-               LOG_FATALF("IsTeamSmallerThanTeam: team_index_b is invalid: %f",
-                       team_index_b);
+               return;
        }
-       if (team_index_a == team_index_b)
+
+       // find out what teams are available
+       entity balance = TeamBalance_CheckAllowedTeams(this);
+
+       // if we don't care what team they end up on, put them on whatever team they entered as.
+       // if they're not on a valid team, then let other code put them on the smallest team
+       if (!force_best_team)
        {
-               return false;
+               int selected_team_index = -1;
+               for (int i = 1; i <= NUM_TEAMS; ++i)
+               {
+                       if (TeamBalance_IsTeamAllowedInternal(balance, i) &&
+                               (Team_TeamToIndex(this.team) == i))
+                       {
+                               selected_team_index = i;
+                               break;
+                       }
+               }
+               
+               if (Team_IsValidIndex(selected_team_index))
+               {
+                       SetPlayerTeam(this, selected_team_index, TEAM_CHANGE_AUTO_RELAXED);
+                       TeamBalance_Destroy(balance);
+                       return;
+               }
        }
-       entity team_a = Team_GetTeamFromIndex(team_index_a);
-       entity team_b = Team_GetTeamFromIndex(team_index_b);
-       if (!Team_IsAllowed(team_a) || !Team_IsAllowed(team_b))
+       // otherwise end up on the smallest team (handled below)
+       if (this.bot_forced_team)
        {
-               return false;
+               TeamBalance_Destroy(balance);
+               return;
        }
-       int num_players_team_a = team_a.m_num_players;
-       int num_players_team_b = team_b.m_num_players;
-       if (IS_REAL_CLIENT(player) && bots_would_leave)
+       int best_team_index = TeamBalance_FindBestTeam(balance, this, true);
+       int old_team_index = Team_TeamToIndex(this.team);
+       TeamBalance_Destroy(balance);
+       PlayerScore_Clear(this);
+       if (!SetPlayerTeam(this, best_team_index, TEAM_CHANGE_AUTO))
        {
-               num_players_team_a -= team_a.m_num_bots;
-               num_players_team_b -= team_b.m_num_bots;
+               return;
        }
-       if (!use_score)
+       if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
        {
-               return num_players_team_a < num_players_team_b;
+               TeamBalance_AutoBalanceBots(best_team_index, old_team_index);
        }
-       if (num_players_team_a < num_players_team_b)
+}
+
+int TeamBalance_CompareTeams(entity balance, int team_index_a, int team_index_b,
+       entity player, bool use_score)
+{
+       if (balance == NULL)
        {
-               return true;
+               LOG_FATAL("TeamBalance_CompareTeams: Team balance entity is NULL.");
        }
-       if (num_players_team_a > num_players_team_b)
+       if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
        {
-               return false;
+               LOG_FATAL("TeamBalance_CompareTeams: "
+                       "TeamBalance_GetTeamCounts has not been called.");
        }
-       return team_a.m_team_score < team_b.m_team_score;
-}
-
-bool IsTeamEqualToTeam(int team_index_a, int team_index_b, entity player,
-       bool use_score)
-{
        if (!Team_IsValidIndex(team_index_a))
        {
-               LOG_FATALF("IsTeamEqualToTeam: team_index_a is invalid: %f",
+               LOG_FATALF("TeamBalance_CompareTeams: team_index_a is invalid: %f",
                        team_index_a);
        }
        if (!Team_IsValidIndex(team_index_b))
        {
-               LOG_FATALF("IsTeamEqualToTeam: team_index_b is invalid: %f",
+               LOG_FATALF("TeamBalance_CompareTeams: team_index_b is invalid: %f",
                        team_index_b);
        }
        if (team_index_a == team_index_b)
        {
-               return true;
+               return TEAMS_COMPARE_EQUAL;
        }
-       entity team_a = Team_GetTeamFromIndex(team_index_a);
-       entity team_b = Team_GetTeamFromIndex(team_index_b);
-       if (!Team_IsAllowed(team_a) || !Team_IsAllowed(team_b))
+       entity team_a = TeamBalance_GetTeamFromIndex(balance, team_index_a);
+       entity team_b = TeamBalance_GetTeamFromIndex(balance, team_index_b);
+       return TeamBalance_CompareTeamsInternal(team_a, team_b, player, use_score);
+}
+
+void TeamBalance_AutoBalanceBots(int source_team_index,
+       int destination_team_index)
+{
+       if (!Team_IsValidIndex(source_team_index))
        {
-               return false;
+               LOG_WARNF("TeamBalance_AutoBalanceBots: "
+                       "Source team index is invalid: %f", source_team_index);
+               return;
        }
-       int num_players_team_a = team_a.m_num_players;
-       int num_players_team_b = team_b.m_num_players;
-       if (IS_REAL_CLIENT(player) && bots_would_leave)
+       if (!Team_IsValidIndex(destination_team_index))
        {
-               num_players_team_a -= team_a.m_num_bots;
-               num_players_team_b -= team_b.m_num_bots;
+               LOG_WARNF("TeamBalance_AutoBalanceBots: "
+                       "Destination team index is invalid: %f", destination_team_index);
+               return;
        }
-       if (!use_score)
+       if (!autocvar_g_balance_teams ||
+               !autocvar_g_balance_teams_prevent_imbalance)
        {
-               return num_players_team_a == num_players_team_b;
+               return;
        }
-       if (num_players_team_a != num_players_team_b)
+       entity balance = TeamBalance_CheckAllowedTeams(NULL);
+       TeamBalance_GetTeamCounts(balance, NULL);
+       entity source_team = TeamBalance_GetTeamFromIndex(balance,
+               source_team_index);
+       entity destination_team = TeamBalance_GetTeamFromIndex(balance,
+               destination_team_index);
+       if ((source_team.m_num_bots == 0) || (source_team.m_num_players <=
+               destination_team.m_num_players))
        {
-               return false;
+               TeamBalance_Destroy(balance);
+               return;
        }
-       return team_a.m_team_score == team_b.m_team_score;
-}
-
-int FindBestTeams(entity player, bool use_score)
-{
-       if (MUTATOR_CALLHOOK(FindBestTeams, player) == true)
+       TeamBalance_Destroy(balance);
+       entity lowest_bot = NULL;
+       if (MUTATOR_CALLHOOK(TeamBalance_GetPlayerForTeamSwitch, source_team_index,
+               destination_team_index, true))
        {
-               return M_ARGV(1, float);
+               lowest_bot = M_ARGV(3, entity);
        }
-       int team_bits = 0;
-       int previous_team = 0;
-       if (Team_IsAllowed(g_team_entities[0]))
+       else
        {
-               team_bits = BIT(0);
-               previous_team = 1;
+               float lowest_score = FLOAT_MAX;
+               FOREACH_CLIENT(IS_BOT_CLIENT(it) && (Entity_GetTeamIndex(it) ==
+                       source_team_index),
+               {
+                       float temp_score = PlayerScore_Get(it, SP_SCORE);
+                       if (temp_score >= lowest_score)
+                       {
+                               continue;
+                       }
+                       balance = TeamBalance_CheckAllowedTeams(it);
+                       if (TeamBalance_IsTeamAllowed(balance, destination_team_index))
+                       {
+                               lowest_bot = it;
+                               lowest_score = temp_score;
+                       }
+                       TeamBalance_Destroy(balance);
+               });
        }
-       if (Team_IsAllowed(g_team_entities[1]))
+       if (lowest_bot == NULL)
        {
-               if (previous_team == 0)
-               {
-                       team_bits = BIT(1);
-                       previous_team = 2;
-               }
-               else if (IsTeamSmallerThanTeam(2, previous_team, player, use_score))
-               {
-                       team_bits = BIT(1);
-                       previous_team = 2;
-               }
-               else if (IsTeamEqualToTeam(2, previous_team, player, use_score))
-               {
-                       team_bits |= BIT(1);
-                       previous_team = 2;
-               }
+               return;
        }
-       if (Team_IsAllowed(g_team_entities[2]))
+       if (!Player_SetTeamIndex(lowest_bot, destination_team_index))
        {
-               if (previous_team == 0)
-               {
-                       team_bits = BIT(2);
-                       previous_team = 3;
-               }
-               else if (IsTeamSmallerThanTeam(3, previous_team, player, use_score))
-               {
-                       team_bits = BIT(2);
-                       previous_team = 3;
-               }
-               else if (IsTeamEqualToTeam(3, previous_team, player, use_score))
-               {
-                       team_bits |= BIT(2);
-                       previous_team = 3;
-               }
+               return;
        }
-       if (Team_IsAllowed(g_team_entities[3]))
+       KillPlayerForTeamChange(lowest_bot);
+}
+
+bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
+{
+       return balance.m_team_balance_team[index - 1].m_num_players !=
+               TEAM_NOT_ALLOWED;
+}
+
+void TeamBalance_BanTeamsExcept(entity balance, int index)
+{
+       for (int i = 1; i <= NUM_TEAMS; ++i)
        {
-               if (previous_team == 0)
-               {
-                       team_bits = BIT(3);
-               }
-               else if (IsTeamSmallerThanTeam(4, previous_team, player, use_score))
-               {
-                       team_bits = BIT(3);
-               }
-               else if (IsTeamEqualToTeam(4, previous_team, player, use_score))
+               if (i != index)
                {
-                       team_bits |= BIT(3);
+                       balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
                }
        }
-       return team_bits;
 }
 
-int FindBestTeam(entity player, float ignore_player)
+entity TeamBalance_GetTeamFromIndex(entity balance, int index)
 {
-       // count how many players are in each team
-       if (ignore_player)
-       {
-               GetTeamCounts(player);
-       }
-       else
-       {
-               GetTeamCounts(NULL);
-       }
-       int team_bits = FindBestTeams(player, true);
-       if (team_bits == 0)
+       if (!Team_IsValidIndex(index))
        {
-               LOG_FATALF("FindBestTeam: No teams available for %s\n",
-                       MapInfo_Type_ToString(MapInfo_CurrentGametype()));
+               LOG_FATALF("TeamBalance_GetTeamFromIndex: Index is invalid: %f", index);
        }
-       RandomSelection_Init();
-       if ((team_bits & BIT(0)) != 0)
+       return balance.m_team_balance_team[index - 1];
+}
+
+entity TeamBalance_GetTeam(entity balance, int team_num)
+{
+       return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
+}
+
+bool TeamBalanceTeam_IsAllowed(entity team_ent)
+{
+       return team_ent.m_num_players != TEAM_NOT_ALLOWED;
+}
+
+int TeamBalanceTeam_GetNumberOfPlayers(entity team_ent)
+{
+       return team_ent.m_num_players;
+}
+
+int TeamBalanceTeam_GetNumberOfBots(entity team_ent)
+{
+       return team_ent.m_num_bots;
+}
+
+int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b,
+       entity player, bool use_score)
+{
+       if (team_a == team_b)
        {
-               RandomSelection_AddFloat(1, 1, 1);
+               return TEAMS_COMPARE_EQUAL;
        }
-       if ((team_bits & BIT(1)) != 0)
+       if (!TeamBalanceTeam_IsAllowed(team_a) ||
+               !TeamBalanceTeam_IsAllowed(team_b))
        {
-               RandomSelection_AddFloat(2, 1, 1);
+               return TEAMS_COMPARE_INVALID;
        }
-       if ((team_bits & BIT(2)) != 0)
+       int num_players_team_a = team_a.m_num_players;
+       int num_players_team_b = team_b.m_num_players;
+       if (IS_REAL_CLIENT(player) && bots_would_leave)
        {
-               RandomSelection_AddFloat(3, 1, 1);
+               num_players_team_a -= team_a.m_num_bots;
+               num_players_team_b -= team_b.m_num_bots;
        }
-       if ((team_bits & BIT(3)) != 0)
+       if (num_players_team_a < num_players_team_b)
        {
-               RandomSelection_AddFloat(4, 1, 1);
+               return TEAMS_COMPARE_LESS;
        }
-       return RandomSelection_chosen_float;
-}
-
-void JoinBestTeam(entity this, bool force_best_team)
-{
-       // don't join a team if we're not playing a team game
-       if (!teamplay)
+       if (num_players_team_a > num_players_team_b)
        {
-               return;
+               return TEAMS_COMPARE_GREATER;
        }
-
-       // find out what teams are available
-       CheckAllowedTeams(this);
-
-       // if we don't care what team they end up on, put them on whatever team they entered as.
-       // if they're not on a valid team, then let other code put them on the smallest team
-       if (!force_best_team)
+       if (!use_score)
        {
-               int selected_team_num = -1;
-               for (int i = 0; i < 4; ++i)
-               {
-                       if (Team_IsAllowed(g_team_entities[i]) && (this.team ==
-                               Team_NumberToTeam(i)))
-                       {
-                               selected_team_num = this.team;
-                               break;
-                       }
-               }
-               
-               if (Team_IsValidTeam(selected_team_num))
-               {
-                       SetPlayerTeamSimple(this, selected_team_num);
-                       LogTeamchange(this.playerid, this.team, 99);
-                       return;
-               }
+               return TEAMS_COMPARE_EQUAL;
        }
-       // otherwise end up on the smallest team (handled below)
-       if (this.bot_forced_team)
+       if (team_a.m_team_score < team_b.m_team_score)
        {
-               return;
+               return TEAMS_COMPARE_LESS;
        }
-       int best_team_index = FindBestTeam(this, true);
-       int best_team_num = Team_NumberToTeam(best_team_index);
-       int old_team_index = Team_TeamToNumber(this.team);
-       TeamchangeFrags(this);
-       SetPlayerTeamSimple(this, best_team_num);
-       LogTeamchange(this.playerid, this.team, 2); // log auto join
-       if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
+       if (team_a.m_team_score > team_b.m_team_score)
        {
-               AutoBalanceBots(old_team_index, best_team_index);
+               return TEAMS_COMPARE_GREATER;
        }
-       KillPlayerForTeamChange(this);
+       return TEAMS_COMPARE_EQUAL;
 }
 
+// Called when the player connects or when they change their color with "color"
+// command.
 void SV_ChangeTeam(entity this, float _color)
 {
-       int source_color, destination_color;
-       int source_team_index, destination_team_index;
+       //PrintToChatAll(sprintf("SV_ChangeTeam: %s, %f", this.netname, _color));
 
        // in normal deathmatch we can just apply the color and we're done
        if(!teamplay)
@@ -855,28 +894,48 @@ void SV_ChangeTeam(entity this, float _color)
        if(!teamplay)
                return;
 
+       int source_color, destination_color;
+       int source_team_index, destination_team_index;
+
        source_color = this.clientcolors & 0x0F;
        destination_color = _color & 0x0F;
 
-       source_team_index = Team_TeamToNumber(source_color + 1);
-       destination_team_index = Team_TeamToNumber(destination_color + 1);
+       source_team_index = Team_TeamToIndex(source_color + 1);
+       destination_team_index = Team_TeamToIndex(destination_color + 1);
 
        if (destination_team_index == -1)
        {
                return;
        }
 
-       CheckAllowedTeams(this);
+       entity balance = TeamBalance_CheckAllowedTeams(this);
 
-       if (destination_team_index == 1 && !Team_IsAllowed(g_team_entities[0])) destination_team_index = 4;
-       if (destination_team_index == 4 && !Team_IsAllowed(g_team_entities[3])) destination_team_index = 3;
-       if (destination_team_index == 3 && !Team_IsAllowed(g_team_entities[2])) destination_team_index = 2;
-       if (destination_team_index == 2 && !Team_IsAllowed(g_team_entities[1])) destination_team_index = 1;
+       if (destination_team_index == 1 && !TeamBalance_IsTeamAllowedInternal(
+               balance, 1))
+       {
+               destination_team_index = 4;
+       }
+       if (destination_team_index == 4 && !TeamBalance_IsTeamAllowedInternal(
+               balance, 4))
+       {
+               destination_team_index = 3;
+       }
+       if (destination_team_index == 3 && !TeamBalance_IsTeamAllowedInternal(
+               balance, 3))
+       {
+               destination_team_index = 2;
+       }
+       if (destination_team_index == 2 && !TeamBalance_IsTeamAllowedInternal(
+               balance, 2))
+       {
+               destination_team_index = 1;
+       }
 
        // not changing teams
        if (source_color == destination_color)
        {
-               SetPlayerTeam(this, destination_team_index, source_team_index, true);
+               SetPlayerTeam(this, destination_team_index, TEAM_CHANGE_MANUAL);
+               TeamBalance_Destroy(balance);
                return;
        }
 
@@ -888,62 +947,24 @@ void SV_ChangeTeam(entity this, float _color)
        // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
        if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
        {
-               GetTeamCounts(this);
-               if ((BIT(destination_team_index - 1) & FindBestTeams(this, false)) == 0)
+               TeamBalance_GetTeamCounts(balance, this);
+               if ((Team_IndexToBit(destination_team_index) &
+                       TeamBalance_FindBestTeams(balance, this, false)) == 0)
                {
                        Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
+                       TeamBalance_Destroy(balance);
                        return;
                }
        }
+       TeamBalance_Destroy(balance);
        if (IS_PLAYER(this) && source_team_index != destination_team_index)
        {
                // reduce frags during a team change
-               TeamchangeFrags(this);
-       }
-       if (!SetPlayerTeam(this, destination_team_index, source_team_index,
-               !IS_CLIENT(this)))
-       {
-               return;
-       }
-       AutoBalanceBots(source_team_index, destination_team_index);
-       if (!IS_PLAYER(this) || (source_team_index == destination_team_index))
-       {
-               return;
-       }
-       KillPlayerForTeamChange(this);
-}
-
-void AutoBalanceBots(int source_team_index, int destination_team_index)
-{
-       if (!Team_IsValidIndex(source_team_index))
-       {
-               LOG_WARNF("AutoBalanceBots: Source team index is invalid: %f",
-                       source_team_index);
-               return;
-       }
-       if (!Team_IsValidIndex(destination_team_index))
-       {
-               LOG_WARNF("AutoBalanceBots: Destination team index is invalid: %f",
-                       destination_team_index);
-               return;
-       }
-       if (!autocvar_g_balance_teams ||
-               !autocvar_g_balance_teams_prevent_imbalance)
-       {
-               return;
-       }
-       entity source_team = Team_GetTeamFromIndex(source_team_index);
-       if (!Team_IsAllowed(source_team))
-       {
-               return;
+               PlayerScore_Clear(this);
        }
-       entity destination_team = Team_GetTeamFromIndex(destination_team_index);
-       if ((destination_team.m_num_players <= source_team.m_num_players) ||
-               (destination_team.m_lowest_bot == NULL))
+       if (!SetPlayerTeam(this, destination_team_index, TEAM_CHANGE_MANUAL))
        {
                return;
        }
-       SetPlayerTeamSimple(destination_team.m_lowest_bot,
-               Team_NumberToTeam(source_team_index));
-       KillPlayerForTeamChange(destination_team.m_lowest_bot);
+       TeamBalance_AutoBalanceBots(destination_team_index, source_team_index);
 }