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