]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/teamplay.qc
Teamplay: Abstracted forced teams.
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / teamplay.qc
1 #include "teamplay.qh"
2
3 #include "client.qh"
4 #include "race.qh"
5 #include "scores.qh"
6 #include "scores_rules.qh"
7
8 #include "bot/api.qh"
9
10 #include "command/vote.qh"
11
12 #include <server/mutators/_mod.qh>
13
14 #include "../common/deathtypes/all.qh"
15 #include <common/gamemodes/_mod.qh>
16 #include "../common/teams.qh"
17
18 /// \brief Describes a state of team balance entity.
19 enum
20 {
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
26 };
27
28 /// \brief Indicates that the player is not allowed to join a team.
29 const int TEAM_NOT_ALLOWED = -1;
30
31 .float team_forced; // can be a team number to force a team, or 0 for default action, or -1 for forced spectator
32
33 .int m_team_balance_state; ///< Holds the state of the team balance entity.
34 .entity m_team_balance_team[NUM_TEAMS]; ///< ???
35
36 .float m_team_score; ///< The score of the team.
37 .int m_num_players; ///< Number of players (both humans and bots) in a team.
38 .int m_num_bots; ///< Number of bots in a team.
39 .int m_num_players_alive; ///< Number of alive players in a team.
40 .int m_num_control_points; ///< Number of control points owned by a team.
41
42 string autocvar_g_forced_team_red;
43 string autocvar_g_forced_team_blue;
44 string autocvar_g_forced_team_yellow;
45 string autocvar_g_forced_team_pink;
46
47 entity g_team_entities[NUM_TEAMS]; ///< Holds global team entities.
48
49 STATIC_INIT(g_team_entities)
50 {
51         for (int i = 0; i < NUM_TEAMS; ++i)
52         {
53                 g_team_entities[i] = spawn();
54         }
55 }
56
57 entity Team_GetTeamFromIndex(int index)
58 {
59         if (!Team_IsValidIndex(index))
60         {
61                 LOG_FATALF("Team_GetTeamFromIndex: Index is invalid: %f", index);
62         }
63         return g_team_entities[index - 1];
64 }
65
66 entity Team_GetTeam(int team_num)
67 {
68         if (!Team_IsValidTeam(team_num))
69         {
70                 LOG_FATALF("Team_GetTeam: Value is invalid: %f", team_num);
71         }
72         return g_team_entities[Team_TeamToIndex(team_num) - 1];
73 }
74
75 float Team_GetTeamScore(entity team_ent)
76 {
77         return team_ent.m_team_score;
78 }
79
80 void Team_SetTeamScore(entity team_ent, float score)
81 {
82         team_ent.m_team_score = score;
83 }
84
85 int Team_GetNumberOfAlivePlayers(entity team_ent)
86 {
87         return team_ent.m_num_players_alive;
88 }
89
90 void Team_SetNumberOfAlivePlayers(entity team_ent, int number)
91 {
92         team_ent.m_num_players_alive = number;
93 }
94
95 int Team_GetNumberOfAliveTeams()
96 {
97         int result = 0;
98         for (int i = 0; i < NUM_TEAMS; ++i)
99         {
100                 if (g_team_entities[i].m_num_players_alive > 0)
101                 {
102                         ++result;
103                 }
104         }
105         return result;
106 }
107
108 int Team_GetNumberOfControlPoints(entity team_ent)
109 {
110         return team_ent.m_num_control_points;
111 }
112
113 void Team_SetNumberOfControlPoints(entity team_ent, int number)
114 {
115         team_ent.m_num_control_points = number;
116 }
117
118 int Team_GetNumberOfTeamsWithControlPoints()
119 {
120         int result = 0;
121         for (int i = 0; i < NUM_TEAMS; ++i)
122         {
123                 if (g_team_entities[i].m_num_control_points > 0)
124                 {
125                         ++result;
126                 }
127         }
128         return result;
129 }
130
131 void setcolor(entity this, int clr)
132 {
133 #if 0
134         this.clientcolors = clr;
135         this.team = (clr & 15) + 1;
136 #else
137         builtin_setcolor(this, clr);
138 #endif
139 }
140
141 bool Entity_HasValidTeam(entity this)
142 {
143         return Team_IsValidTeam(this.team);
144 }
145
146 int Entity_GetTeamIndex(entity this)
147 {
148         return Team_TeamToIndex(this.team);
149 }
150
151 entity Entity_GetTeam(entity this)
152 {
153         int index = Entity_GetTeamIndex(this);
154         if (!Team_IsValidIndex(index))
155         {
156                 return NULL;
157         }
158         return Team_GetTeamFromIndex(index);
159 }
160
161 void SetPlayerColors(entity player, float _color)
162 {
163         float pants = _color & 0x0F;
164         float shirt = _color & 0xF0;
165         if (teamplay)
166         {
167                 setcolor(player, 16 * pants + pants);
168         }
169         else
170         {
171                 setcolor(player, shirt + pants);
172         }
173 }
174
175 bool Player_SetTeamIndex(entity player, int index)
176 {
177         int new_team = Team_IndexToTeam(index);
178         if (player.team == new_team)
179         {
180                 if (new_team != -1)
181                 {
182                         // This is important when players join the game and one of their
183                         // color matches the team color while other doesn't. For example
184                         // [BOT]Lion.
185                         SetPlayerColors(player, new_team - 1);
186                 }
187                 return true;
188         }
189         int old_index = Team_TeamToIndex(player.team);
190         if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, old_index, index) == true)
191         {
192                 // Mutator has blocked team change.
193                 return false;
194         }
195         if (new_team == -1)
196         {
197                 player.team = -1;
198         }
199         else
200         {
201                 SetPlayerColors(player, new_team - 1);
202         }
203         MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_index, index);
204         return true;
205 }
206
207 bool SetPlayerTeam(entity player, int team_index, int type)
208 {
209         int old_team_index = Entity_GetTeamIndex(player);
210         if (!Player_SetTeamIndex(player, team_index))
211         {
212                 return false;
213         }
214         LogTeamchange(player.playerid, player.team, type);
215         if (team_index != old_team_index)
216         {
217                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(player.team,
218                         INFO_JOIN_PLAY_TEAM), player.netname);
219                 KillPlayerForTeamChange(player);
220         }
221         return true;
222 }
223
224 bool MoveToTeam(entity client, int team_index, int type)
225 {
226         //PrintToChatAll(sprintf("MoveToTeam: %s, %f", client.netname, team_index));
227         int lockteams_backup = lockteams;  // backup any team lock
228         lockteams = 0;  // disable locked teams
229         PlayerScore_Clear(client);
230         if (!SetPlayerTeam(client, team_index, type))
231         {
232                 lockteams = lockteams_backup;  // restore the team lock
233                 return false;
234         }
235         lockteams = lockteams_backup;  // restore the team lock
236         return true;
237 }
238
239 void KillPlayerForTeamChange(entity player)
240 {
241         if (IS_DEAD(player))
242         {
243                 return;
244         }
245         if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
246         {
247                 return;
248         }
249         Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
250                 player.origin, '0 0 0');
251 }
252
253 void LogTeamchange(float player_id, float team_number, int type)
254 {
255         if(!autocvar_sv_eventlog)
256                 return;
257
258         if(player_id < 1)
259                 return;
260
261         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
262 }
263
264 bool Player_HasRealForcedTeam(entity player)
265 {
266         return player.team_forced > TEAM_FORCE_DEFAULT;
267 }
268
269 int Player_GetForcedTeamIndex(entity player)
270 {
271         return player.team_forced;
272 }
273
274 void Player_SetForcedTeamIndex(entity player, int team_index)
275 {
276         player.team_forced = team_index;
277 }
278
279 void Player_DetermineForcedTeam(entity player)
280 {
281         if (autocvar_g_campaign)
282         {
283                 if (IS_REAL_CLIENT(player)) // only players, not bots
284                 {
285                         if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
286                         {
287                                 player.team_forced = autocvar_g_campaign_forceteam;
288                         }
289                         else
290                         {
291                                 player.team_forced = TEAM_FORCE_DEFAULT;
292                         }
293                 }
294         }
295         else if (PlayerInList(player, autocvar_g_forced_team_red))
296         {
297                 player.team_forced = 1;
298         }
299         else if (PlayerInList(player, autocvar_g_forced_team_blue))
300         {
301                 player.team_forced = 2;
302         }
303         else if (PlayerInList(player, autocvar_g_forced_team_yellow))
304         {
305                 player.team_forced = 3;
306         }
307         else if (PlayerInList(player, autocvar_g_forced_team_pink))
308         {
309                 player.team_forced = 4;
310         }
311         else
312         {
313                 switch (autocvar_g_forced_team_otherwise)
314                 {
315                         case "red":
316                         {
317                                 player.team_forced = 1;
318                                 break;
319                         }
320                         case "blue":
321                         {
322                                 player.team_forced = 2;
323                                 break;
324                         }
325                         case "yellow":
326                         {
327                                 player.team_forced = 3;
328                                 break;
329                         }
330                         case "pink":
331                         {
332                                 player.team_forced = 4;
333                                 break;
334                         }
335                         case "spectate":
336                         case "spectator":
337                         {
338                                 player.team_forced = TEAM_FORCE_SPECTATOR;
339                                 break;
340                         }
341                         default:
342                         {
343                                 player.team_forced = TEAM_FORCE_DEFAULT;
344                                 break;
345                         }
346                 }
347         }
348         if (!teamplay && Player_HasRealForcedTeam(player))
349         {
350                 player.team_forced = TEAM_FORCE_DEFAULT;
351         }
352 }
353
354 entity TeamBalance_CheckAllowedTeams(entity for_whom)
355 {
356         entity balance = spawn();
357         for (int i = 0; i < NUM_TEAMS; ++i)
358         {
359                 entity team_ent = balance.m_team_balance_team[i] = spawn();
360                 team_ent.m_team_score = g_team_entities[i].m_team_score;
361                 team_ent.m_num_players = TEAM_NOT_ALLOWED;
362                 team_ent.m_num_bots = 0;
363         }
364         setthink(balance, TeamBalance_Destroy);
365         
366         int teams_mask = 0;     
367         string teament_name = string_null;
368         bool mutator_returnvalue = MUTATOR_CALLHOOK(TeamBalance_CheckAllowedTeams,
369                 teams_mask, teament_name, for_whom);
370         teams_mask = M_ARGV(0, float);
371         teament_name = M_ARGV(1, string);
372         if (mutator_returnvalue)
373         {
374                 for (int i = 0; i < NUM_TEAMS; ++i)
375                 {
376                         if (teams_mask & BIT(i))
377                         {
378                                 balance.m_team_balance_team[i].m_num_players = 0;
379                         }
380                 }
381         }
382
383         if (teament_name)
384         {
385                 entity head = find(NULL, classname, teament_name);
386                 while (head)
387                 {
388                         if (Team_IsValidTeam(head.team))
389                         {
390                                 TeamBalance_GetTeam(balance, head.team).m_num_players = 0;
391                         }
392                         head = find(head, classname, teament_name);
393                 }
394         }
395
396         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
397         if (AvailableTeams() == 2)
398         if (autocvar_bot_vs_human && for_whom)
399         {
400                 if (autocvar_bot_vs_human > 0)
401                 {
402                         // find last team available
403                         if (IS_BOT_CLIENT(for_whom))
404                         {
405                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
406                                 {
407                                         TeamBalance_BanTeamsExcept(balance, 4);
408                                 }
409                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
410                                 {
411                                         TeamBalance_BanTeamsExcept(balance, 3);
412                                 }
413                                 else
414                                 {
415                                         TeamBalance_BanTeamsExcept(balance, 2);
416                                 }
417                                 // no further cases, we know at least 2 teams exist
418                         }
419                         else
420                         {
421                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
422                                 {
423                                         TeamBalance_BanTeamsExcept(balance, 1);
424                                 }
425                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
426                                 {
427                                         TeamBalance_BanTeamsExcept(balance, 2);
428                                 }
429                                 else
430                                 {
431                                         TeamBalance_BanTeamsExcept(balance, 3);
432                                 }
433                                 // no further cases, bots have one of the teams
434                         }
435                 }
436                 else
437                 {
438                         // find first team available
439                         if (IS_BOT_CLIENT(for_whom))
440                         {
441                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
442                                 {
443                                         TeamBalance_BanTeamsExcept(balance, 1);
444                                 }
445                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
446                                 {
447                                         TeamBalance_BanTeamsExcept(balance, 2);
448                                 }
449                                 else
450                                 {
451                                         TeamBalance_BanTeamsExcept(balance, 3);
452                                 }
453                                 // no further cases, we know at least 2 teams exist
454                         }
455                         else
456                         {
457                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
458                                 {
459                                         TeamBalance_BanTeamsExcept(balance, 4);
460                                 }
461                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
462                                 {
463                                         TeamBalance_BanTeamsExcept(balance, 3);
464                                 }
465                                 else
466                                 {
467                                         TeamBalance_BanTeamsExcept(balance, 2);
468                                 }
469                                 // no further cases, bots have one of the teams
470                         }
471                 }
472         }
473
474         if (!for_whom)
475         {
476                 balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
477                 return balance;
478         }
479
480         // if player has a forced team, ONLY allow that one
481         for (int i = 1; i <= NUM_TEAMS; ++i)
482         {
483                 if (for_whom.team_forced == i &&
484                         TeamBalance_IsTeamAllowedInternal(balance, i))
485                 {
486                         TeamBalance_BanTeamsExcept(balance, i);
487                 }
488                 break;
489         }
490         balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
491         return balance;
492 }
493
494 void TeamBalance_Destroy(entity balance)
495 {
496         if (balance == NULL)
497         {
498                 return;
499         }
500         for (int i = 0; i < NUM_TEAMS; ++i)
501         {
502                 delete(balance.(m_team_balance_team[i]));
503         }
504         delete(balance);
505 }
506
507 int TeamBalance_GetAllowedTeams(entity balance)
508 {
509         if (balance == NULL)
510         {
511                 LOG_FATAL("TeamBalance_GetAllowedTeams: Team balance entity is NULL.");
512         }
513         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
514         {
515                 LOG_FATAL("TeamBalance_GetAllowedTeams: "
516                         "Team balance entity is not initialized.");
517         }
518         int result = 0;
519         for (int i = 1; i <= NUM_TEAMS; ++i)
520         {
521                 if (TeamBalance_IsTeamAllowedInternal(balance, i))
522                 {
523                         result |= Team_IndexToBit(i);
524                 }
525         }
526         return result;
527 }
528
529 bool TeamBalance_IsTeamAllowed(entity balance, int index)
530 {
531         if (balance == NULL)
532         {
533                 LOG_FATAL("TeamBalance_IsTeamAllowed: Team balance entity is NULL.");
534         }
535         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
536         {
537                 LOG_FATAL("TeamBalance_IsTeamAllowed: "
538                         "Team balance entity is not initialized.");
539         }
540         if (!Team_IsValidIndex(index))
541         {
542                 LOG_FATALF("TeamBalance_IsTeamAllowed: Team index is invalid: %f",
543                         index);
544         }
545         return TeamBalance_IsTeamAllowedInternal(balance, index);
546 }
547
548 void TeamBalance_GetTeamCounts(entity balance, entity ignore)
549 {
550         if (balance == NULL)
551         {
552                 LOG_FATAL("TeamBalance_GetTeamCounts: Team balance entity is NULL.");
553         }
554         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
555         {
556                 LOG_FATAL("TeamBalance_GetTeamCounts: "
557                         "Team balance entity is not initialized.");
558         }
559         if (MUTATOR_CALLHOOK(TeamBalance_GetTeamCounts) == true)
560         {
561                 // Mutator has overriden the configuration.
562                 for (int i = 1; i <= NUM_TEAMS; ++i)
563                 {
564                         entity team_ent = TeamBalance_GetTeamFromIndex(balance, i);
565                         if (TeamBalanceTeam_IsAllowed(team_ent))
566                         {
567                                 MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore);
568                                 team_ent.m_num_players = M_ARGV(2, float);
569                                 team_ent.m_num_bots = M_ARGV(3, float);
570                         }
571                 }
572         }
573         else
574         {
575                 // Manually count all players.
576                 FOREACH_CLIENT(true,
577                 {
578                         if (it == ignore)
579                         {
580                                 continue;
581                         }
582                         int team_num;
583                         if (IS_PLAYER(it) || it.caplayer)
584                         {
585                                 team_num = it.team;
586                         }
587                         else if (Player_HasRealForcedTeam(it))
588                         {
589                                 team_num = Team_IndexToTeam(it.team_forced); // reserve the spot
590                         }
591                         else
592                         {
593                                 continue;
594                         }
595                         if (!Team_IsValidTeam(team_num))
596                         {
597                                 continue;
598                         }
599                         entity team_ent = TeamBalance_GetTeam(balance, team_num);
600                         if (!TeamBalanceTeam_IsAllowed(team_ent))
601                         {
602                                 continue;
603                         }
604                         ++team_ent.m_num_players;
605                         if (IS_BOT_CLIENT(it))
606                         {
607                                 ++team_ent.m_num_bots;
608                         }
609                 });
610         }
611
612         // if the player who has a forced team has not joined yet, reserve the spot
613         if (autocvar_g_campaign)
614         {
615                 if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
616                 {
617                         entity team_ent = TeamBalance_GetTeamFromIndex(balance,
618                                 autocvar_g_campaign_forceteam);
619                         if (team_ent.m_num_players == team_ent.m_num_bots)
620                         {
621                                 ++team_ent.m_num_players;
622                         }
623                 }
624         }
625         balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
626 }
627
628 int TeamBalance_GetNumberOfPlayers(entity balance, int index)
629 {
630         if (balance == NULL)
631         {
632                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
633                         "Team balance entity is NULL.");
634         }
635         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
636         {
637                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
638                         "TeamBalance_GetTeamCounts has not been called.");
639         }
640         if (!Team_IsValidIndex(index))
641         {
642                 LOG_FATALF("TeamBalance_GetNumberOfPlayers: Team index is invalid: %f",
643                         index);
644         }
645         return balance.m_team_balance_team[index - 1].m_num_players;
646 }
647
648 int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
649 {
650         if (balance == NULL)
651         {
652                 LOG_FATAL("TeamBalance_FindBestTeam: Team balance entity is NULL.");
653         }
654         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
655         {
656                 LOG_FATAL("TeamBalance_FindBestTeam: "
657                         "Team balance entity is not initialized.");
658         }
659         // count how many players are in each team
660         if (ignore_player)
661         {
662                 TeamBalance_GetTeamCounts(balance, player);
663         }
664         else
665         {
666                 TeamBalance_GetTeamCounts(balance, NULL);
667         }
668         int team_bits = TeamBalance_FindBestTeams(balance, player, true);
669         if (team_bits == 0)
670         {
671                 LOG_FATALF("TeamBalance_FindBestTeam: No teams available for %s\n",
672                         MapInfo_Type_ToString(MapInfo_CurrentGametype()));
673         }
674         RandomSelection_Init();
675         for (int i = 1; i <= NUM_TEAMS; ++i)
676         {
677                 if (team_bits & Team_IndexToBit(i))
678                 {
679                         RandomSelection_AddFloat(i, 1, 1);
680                 }
681         }
682         return RandomSelection_chosen_float;
683 }
684
685 int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
686 {
687         if (balance == NULL)
688         {
689                 LOG_FATAL("TeamBalance_FindBestTeams: Team balance entity is NULL.");
690         }
691         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
692         {
693                 LOG_FATAL("TeamBalance_FindBestTeams: "
694                         "TeamBalance_GetTeamCounts has not been called.");
695         }
696         if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
697         {
698                 return M_ARGV(1, float);
699         }
700         int team_bits = 0;
701         int previous_team = 0;
702         for (int i = 1; i <= NUM_TEAMS; ++i)
703         {
704                 if (!TeamBalance_IsTeamAllowedInternal(balance, i))
705                 {
706                         continue;
707                 }
708                 if (previous_team == 0)
709                 {
710                         team_bits = Team_IndexToBit(i);
711                         previous_team = i;
712                         continue;
713                 }
714                 int compare = TeamBalance_CompareTeams(balance, i, previous_team,
715                         player, use_score);
716                 if (compare == TEAMS_COMPARE_LESS)
717                 {
718                         team_bits = Team_IndexToBit(i);
719                         previous_team = i;
720                         continue;
721                 }
722                 if (compare == TEAMS_COMPARE_EQUAL)
723                 {
724                         team_bits |= Team_IndexToBit(i);
725                         previous_team = i;
726                 }
727         }
728         return team_bits;
729 }
730
731 void TeamBalance_JoinBestTeam(entity this)
732 {
733         //PrintToChatAll(sprintf("JoinBestTeam: %s", this.netname));
734         // don't join a team if we're not playing a team game
735         if (!teamplay)
736         {
737                 return;
738         }
739
740         // find out what teams are available
741         entity balance = TeamBalance_CheckAllowedTeams(this);
742
743         if (this.bot_forced_team)
744         {
745                 TeamBalance_Destroy(balance);
746                 return;
747         }
748         int best_team_index = TeamBalance_FindBestTeam(balance, this, true);
749         int old_team_index = Team_TeamToIndex(this.team);
750         TeamBalance_Destroy(balance);
751         PlayerScore_Clear(this);
752         if (!SetPlayerTeam(this, best_team_index, TEAM_CHANGE_AUTO))
753         {
754                 return;
755         }
756         if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
757         {
758                 TeamBalance_AutoBalanceBots(best_team_index, old_team_index);
759         }
760 }
761
762 int TeamBalance_CompareTeams(entity balance, int team_index_a, int team_index_b,
763         entity player, bool use_score)
764 {
765         if (balance == NULL)
766         {
767                 LOG_FATAL("TeamBalance_CompareTeams: Team balance entity is NULL.");
768         }
769         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
770         {
771                 LOG_FATAL("TeamBalance_CompareTeams: "
772                         "TeamBalance_GetTeamCounts has not been called.");
773         }
774         if (!Team_IsValidIndex(team_index_a))
775         {
776                 LOG_FATALF("TeamBalance_CompareTeams: team_index_a is invalid: %f",
777                         team_index_a);
778         }
779         if (!Team_IsValidIndex(team_index_b))
780         {
781                 LOG_FATALF("TeamBalance_CompareTeams: team_index_b is invalid: %f",
782                         team_index_b);
783         }
784         if (team_index_a == team_index_b)
785         {
786                 return TEAMS_COMPARE_EQUAL;
787         }
788         entity team_a = TeamBalance_GetTeamFromIndex(balance, team_index_a);
789         entity team_b = TeamBalance_GetTeamFromIndex(balance, team_index_b);
790         return TeamBalance_CompareTeamsInternal(team_a, team_b, player, use_score);
791 }
792
793 void TeamBalance_AutoBalanceBots(int source_team_index,
794         int destination_team_index)
795 {
796         if (!Team_IsValidIndex(source_team_index))
797         {
798                 LOG_WARNF("TeamBalance_AutoBalanceBots: "
799                         "Source team index is invalid: %f", source_team_index);
800                 return;
801         }
802         if (!Team_IsValidIndex(destination_team_index))
803         {
804                 LOG_WARNF("TeamBalance_AutoBalanceBots: "
805                         "Destination team index is invalid: %f", destination_team_index);
806                 return;
807         }
808         if (!autocvar_g_balance_teams ||
809                 !autocvar_g_balance_teams_prevent_imbalance)
810         {
811                 return;
812         }
813         entity balance = TeamBalance_CheckAllowedTeams(NULL);
814         TeamBalance_GetTeamCounts(balance, NULL);
815         entity source_team = TeamBalance_GetTeamFromIndex(balance,
816                 source_team_index);
817         entity destination_team = TeamBalance_GetTeamFromIndex(balance,
818                 destination_team_index);
819         if ((source_team.m_num_bots == 0) || (source_team.m_num_players <=
820                 destination_team.m_num_players))
821         {
822                 TeamBalance_Destroy(balance);
823                 return;
824         }
825         TeamBalance_Destroy(balance);
826         entity lowest_bot = NULL;
827         if (MUTATOR_CALLHOOK(TeamBalance_GetPlayerForTeamSwitch, source_team_index,
828                 destination_team_index, true))
829         {
830                 lowest_bot = M_ARGV(3, entity);
831         }
832         else
833         {
834                 float lowest_score = FLOAT_MAX;
835                 FOREACH_CLIENT(IS_BOT_CLIENT(it) && (Entity_GetTeamIndex(it) ==
836                         source_team_index),
837                 {
838                         float temp_score = PlayerScore_Get(it, SP_SCORE);
839                         if (temp_score >= lowest_score)
840                         {
841                                 continue;
842                         }
843                         balance = TeamBalance_CheckAllowedTeams(it);
844                         if (TeamBalance_IsTeamAllowed(balance, destination_team_index))
845                         {
846                                 lowest_bot = it;
847                                 lowest_score = temp_score;
848                         }
849                         TeamBalance_Destroy(balance);
850                 });
851         }
852         if (lowest_bot == NULL)
853         {
854                 return;
855         }
856         if (!Player_SetTeamIndex(lowest_bot, destination_team_index))
857         {
858                 return;
859         }
860         KillPlayerForTeamChange(lowest_bot);
861 }
862
863 bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
864 {
865         return balance.m_team_balance_team[index - 1].m_num_players !=
866                 TEAM_NOT_ALLOWED;
867 }
868
869 void TeamBalance_BanTeamsExcept(entity balance, int index)
870 {
871         for (int i = 1; i <= NUM_TEAMS; ++i)
872         {
873                 if (i != index)
874                 {
875                         balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
876                 }
877         }
878 }
879
880 entity TeamBalance_GetTeamFromIndex(entity balance, int index)
881 {
882         if (!Team_IsValidIndex(index))
883         {
884                 LOG_FATALF("TeamBalance_GetTeamFromIndex: Index is invalid: %f", index);
885         }
886         return balance.m_team_balance_team[index - 1];
887 }
888
889 entity TeamBalance_GetTeam(entity balance, int team_num)
890 {
891         return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
892 }
893
894 bool TeamBalanceTeam_IsAllowed(entity team_ent)
895 {
896         return team_ent.m_num_players != TEAM_NOT_ALLOWED;
897 }
898
899 int TeamBalanceTeam_GetNumberOfPlayers(entity team_ent)
900 {
901         return team_ent.m_num_players;
902 }
903
904 int TeamBalanceTeam_GetNumberOfBots(entity team_ent)
905 {
906         return team_ent.m_num_bots;
907 }
908
909 int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b,
910         entity player, bool use_score)
911 {
912         if (team_a == team_b)
913         {
914                 return TEAMS_COMPARE_EQUAL;
915         }
916         if (!TeamBalanceTeam_IsAllowed(team_a) ||
917                 !TeamBalanceTeam_IsAllowed(team_b))
918         {
919                 return TEAMS_COMPARE_INVALID;
920         }
921         int num_players_team_a = team_a.m_num_players;
922         int num_players_team_b = team_b.m_num_players;
923         if (IS_REAL_CLIENT(player) && bots_would_leave)
924         {
925                 num_players_team_a -= team_a.m_num_bots;
926                 num_players_team_b -= team_b.m_num_bots;
927         }
928         if (num_players_team_a < num_players_team_b)
929         {
930                 return TEAMS_COMPARE_LESS;
931         }
932         if (num_players_team_a > num_players_team_b)
933         {
934                 return TEAMS_COMPARE_GREATER;
935         }
936         if (!use_score)
937         {
938                 return TEAMS_COMPARE_EQUAL;
939         }
940         if (team_a.m_team_score < team_b.m_team_score)
941         {
942                 return TEAMS_COMPARE_LESS;
943         }
944         if (team_a.m_team_score > team_b.m_team_score)
945         {
946                 return TEAMS_COMPARE_GREATER;
947         }
948         return TEAMS_COMPARE_EQUAL;
949 }
950
951 // Called when the player connects or when they change their color with "color"
952 // command.
953 void SV_ChangeTeam(entity this, float _color)
954 {
955         //PrintToChatAll(sprintf("SV_ChangeTeam: %s, %f", this.netname, _color));
956
957         // in normal deathmatch we can just apply the color and we're done
958         if(!teamplay)
959                 SetPlayerColors(this, _color);
960
961         if(!IS_CLIENT(this))
962         {
963                 // since this is an engine function, and gamecode doesn't have any calls earlier than this, do the connecting message here
964                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CONNECTING, this.netname);
965                 return;
966         }
967
968         if(!teamplay)
969                 return;
970
971         int source_color, destination_color;
972         int source_team_index, destination_team_index;
973
974         source_color = this.clientcolors & 0x0F;
975         destination_color = _color & 0x0F;
976
977         source_team_index = Team_TeamToIndex(source_color + 1);
978         destination_team_index = Team_TeamToIndex(destination_color + 1);
979
980         if (destination_team_index == -1)
981         {
982                 return;
983         }
984
985         entity balance = TeamBalance_CheckAllowedTeams(this);
986
987         if (destination_team_index == 1 && !TeamBalance_IsTeamAllowedInternal(
988                 balance, 1))
989         {
990                 destination_team_index = 4;
991         }
992         if (destination_team_index == 4 && !TeamBalance_IsTeamAllowedInternal(
993                 balance, 4))
994         {
995                 destination_team_index = 3;
996         }
997         if (destination_team_index == 3 && !TeamBalance_IsTeamAllowedInternal(
998                 balance, 3))
999         {
1000                 destination_team_index = 2;
1001         }
1002         if (destination_team_index == 2 && !TeamBalance_IsTeamAllowedInternal(
1003                 balance, 2))
1004         {
1005                 destination_team_index = 1;
1006         }
1007
1008         // not changing teams
1009         if (source_color == destination_color)
1010         {
1011                 SetPlayerTeam(this, destination_team_index, TEAM_CHANGE_MANUAL);
1012                 TeamBalance_Destroy(balance);
1013                 return;
1014         }
1015
1016         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && CS(this).wasplayer)) {
1017                 Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
1018                 return; // changing teams is not allowed
1019         }
1020
1021         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
1022         if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
1023         {
1024                 TeamBalance_GetTeamCounts(balance, this);
1025                 if ((Team_IndexToBit(destination_team_index) &
1026                         TeamBalance_FindBestTeams(balance, this, false)) == 0)
1027                 {
1028                         Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
1029                         TeamBalance_Destroy(balance);
1030                         return;
1031                 }
1032         }
1033         TeamBalance_Destroy(balance);
1034         if (IS_PLAYER(this) && source_team_index != destination_team_index)
1035         {
1036                 // reduce frags during a team change
1037                 PlayerScore_Clear(this);
1038         }
1039         if (!SetPlayerTeam(this, destination_team_index, TEAM_CHANGE_MANUAL))
1040         {
1041                 return;
1042         }
1043         TeamBalance_AutoBalanceBots(destination_team_index, source_team_index);
1044 }