]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/teamplay.qc
Improved MoveToTeam.
[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 bool MoveToTeam(entity client, int team_index, int type)
226 {
227         int lockteams_backup = lockteams;  // backup any team lock
228         lockteams = 0;  // disable locked teams
229         TeamchangeFrags(client);  // move the players frags
230         if (!Player_SetTeamIndex(client, team_index))
231         {
232                 lockteams = lockteams_backup;  // restore the team lock
233                 return false;
234         }
235         KillPlayerForTeamChange(client);
236         lockteams = lockteams_backup;  // restore the team lock
237         LogTeamchange(client.playerid, client.team, type);
238         return true;
239 }
240
241 void KillPlayerForTeamChange(entity player)
242 {
243         if (IS_DEAD(player))
244         {
245                 return;
246         }
247         if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
248         {
249                 return;
250         }
251         Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
252                 player.origin, '0 0 0');
253 }
254
255 entity TeamBalance_CheckAllowedTeams(entity for_whom)
256 {
257         entity balance = spawn();
258         for (int i = 0; i < NUM_TEAMS; ++i)
259         {
260                 entity team_ = balance.m_team_balance_team[i] = spawn();
261                 team_.m_team_score = g_team_entities[i].m_team_score;
262                 team_.m_num_players = TEAM_NOT_ALLOWED;
263                 team_.m_num_bots = 0;
264                 team_.m_lowest_human = NULL;
265                 team_.m_lowest_bot = NULL;
266         }
267         
268         int teams_mask = 0;     
269         string teament_name = string_null;
270         bool mutator_returnvalue = MUTATOR_CALLHOOK(TeamBalance_CheckAllowedTeams,
271                 teams_mask, teament_name, for_whom);
272         teams_mask = M_ARGV(0, float);
273         teament_name = M_ARGV(1, string);
274         if (mutator_returnvalue)
275         {
276                 for (int i = 0; i < NUM_TEAMS; ++i)
277                 {
278                         if (teams_mask & BIT(i))
279                         {
280                                 balance.m_team_balance_team[i].m_num_players = 0;
281                         }
282                 }
283         }
284
285         if (teament_name)
286         {
287                 entity head = find(NULL, classname, teament_name);
288                 while (head)
289                 {
290                         if (Team_IsValidTeam(head.team))
291                         {
292                                 TeamBalance_GetTeam(balance, head.team).m_num_players = 0;
293                         }
294                         head = find(head, classname, teament_name);
295                 }
296         }
297
298         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
299         if (AvailableTeams() == 2)
300         if (autocvar_bot_vs_human && for_whom)
301         {
302                 if (autocvar_bot_vs_human > 0)
303                 {
304                         // find last team available
305                         if (IS_BOT_CLIENT(for_whom))
306                         {
307                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
308                                 {
309                                         TeamBalance_BanTeamsExcept(balance, 4);
310                                 }
311                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
312                                 {
313                                         TeamBalance_BanTeamsExcept(balance, 3);
314                                 }
315                                 else
316                                 {
317                                         TeamBalance_BanTeamsExcept(balance, 2);
318                                 }
319                                 // no further cases, we know at least 2 teams exist
320                         }
321                         else
322                         {
323                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
324                                 {
325                                         TeamBalance_BanTeamsExcept(balance, 1);
326                                 }
327                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
328                                 {
329                                         TeamBalance_BanTeamsExcept(balance, 2);
330                                 }
331                                 else
332                                 {
333                                         TeamBalance_BanTeamsExcept(balance, 3);
334                                 }
335                                 // no further cases, bots have one of the teams
336                         }
337                 }
338                 else
339                 {
340                         // find first team available
341                         if (IS_BOT_CLIENT(for_whom))
342                         {
343                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
344                                 {
345                                         TeamBalance_BanTeamsExcept(balance, 1);
346                                 }
347                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
348                                 {
349                                         TeamBalance_BanTeamsExcept(balance, 2);
350                                 }
351                                 else
352                                 {
353                                         TeamBalance_BanTeamsExcept(balance, 3);
354                                 }
355                                 // no further cases, we know at least 2 teams exist
356                         }
357                         else
358                         {
359                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
360                                 {
361                                         TeamBalance_BanTeamsExcept(balance, 4);
362                                 }
363                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
364                                 {
365                                         TeamBalance_BanTeamsExcept(balance, 3);
366                                 }
367                                 else
368                                 {
369                                         TeamBalance_BanTeamsExcept(balance, 2);
370                                 }
371                                 // no further cases, bots have one of the teams
372                         }
373                 }
374         }
375
376         if (!for_whom)
377         {
378                 balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
379                 return balance;
380         }
381
382         // if player has a forced team, ONLY allow that one
383         for (int i = 1; i <= NUM_TEAMS; ++i)
384         {
385                 if (for_whom.team_forced == Team_IndexToTeam(i) &&
386                         TeamBalance_IsTeamAllowedInternal(balance, i))
387                 {
388                         TeamBalance_BanTeamsExcept(balance, i);
389                 }
390                 break;
391         }
392         balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
393         return balance;
394 }
395
396 void TeamBalance_Destroy(entity balance)
397 {
398         if (balance == NULL)
399         {
400                 return;
401         }
402         for (int i = 0; i < NUM_TEAMS; ++i)
403         {
404                 remove(balance.(m_team_balance_team[i]));
405         }
406         remove(balance);
407 }
408
409 int TeamBalance_GetAllowedTeams(entity balance)
410 {
411         if (balance == NULL)
412         {
413                 LOG_FATAL("TeamBalance_GetAllowedTeams: Team balance entity is NULL.");
414         }
415         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
416         {
417                 LOG_FATAL("TeamBalance_GetAllowedTeams: "
418                         "Team balance entity is not initialized.");
419         }
420         int result = 0;
421         for (int i = 1; i <= NUM_TEAMS; ++i)
422         {
423                 if (TeamBalance_IsTeamAllowedInternal(balance, i))
424                 {
425                         result |= Team_IndexToBit(i);
426                 }
427         }
428         return result;
429 }
430
431 bool TeamBalance_IsTeamAllowed(entity balance, int index)
432 {
433         if (balance == NULL)
434         {
435                 LOG_FATAL("TeamBalance_IsTeamAllowed: Team balance entity is NULL.");
436         }
437         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
438         {
439                 LOG_FATAL("TeamBalance_IsTeamAllowed: "
440                         "Team balance entity is not initialized.");
441         }
442         if (!Team_IsValidIndex(index))
443         {
444                 LOG_FATALF("TeamBalance_IsTeamAllowed: Team index is invalid: %f",
445                         index);
446         }
447         return TeamBalance_IsTeamAllowedInternal(balance, index);
448 }
449
450 void TeamBalance_GetTeamCounts(entity balance, entity ignore)
451 {
452         if (balance == NULL)
453         {
454                 LOG_FATAL("TeamBalance_GetTeamCounts: Team balance entity is NULL.");
455         }
456         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
457         {
458                 LOG_FATAL("TeamBalance_GetTeamCounts: "
459                         "Team balance entity is not initialized.");
460         }
461         if (MUTATOR_CALLHOOK(TeamBalance_GetTeamCounts) == true)
462         {
463                 // Mutator has overriden the configuration.
464                 for (int i = 1; i <= NUM_TEAMS; ++i)
465                 {
466                         entity team_ = TeamBalance_GetTeamFromIndex(balance, i);
467                         if (TeamBalanceTeam_IsAllowed(team_))
468                         {
469                                 MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore,
470                                         team_.m_num_players, team_.m_num_bots, team_.m_lowest_human,
471                                         team_.m_lowest_bot);
472                                 team_.m_num_players = M_ARGV(2, float);
473                                 team_.m_num_bots = M_ARGV(3, float);
474                                 team_.m_lowest_human = M_ARGV(4, entity);
475                                 team_.m_lowest_bot = M_ARGV(5, entity);
476                         }
477                 }
478         }
479         else
480         {
481                 // Manually count all players.
482                 FOREACH_CLIENT(true,
483                 {
484                         if (it == ignore)
485                         {
486                                 continue;
487                         }
488                         int team_num;
489                         if (IS_PLAYER(it) || it.caplayer)
490                         {
491                                 team_num = it.team;
492                         }
493                         else if (it.team_forced > 0)
494                         {
495                                 team_num = it.team_forced; // reserve the spot
496                         }
497                         else
498                         {
499                                 continue;
500                         }
501                         if (!Team_IsValidTeam(team_num))
502                         {
503                                 continue;
504                         }
505                         entity team_ = TeamBalance_GetTeam(balance, team_num);
506                         if (!TeamBalanceTeam_IsAllowed(team_))
507                         {
508                                 continue;
509                         }
510                         ++team_.m_num_players;
511                         if (IS_BOT_CLIENT(it))
512                         {
513                                 ++team_.m_num_bots;
514                         }
515                         float temp_score = PlayerScore_Get(it, SP_SCORE);
516                         if (!IS_BOT_CLIENT(it))
517                         {
518                                 if (team_.m_lowest_human == NULL)
519                                 {
520                                         team_.m_lowest_human = it;
521                                         continue;
522                                 }
523                                 if (temp_score < PlayerScore_Get(team_.m_lowest_human,
524                                         SP_SCORE))
525                                 {
526                                         team_.m_lowest_human = it;
527                                 }
528                                 continue;
529                         }
530                         if (team_.m_lowest_bot == NULL)
531                         {
532                                 team_.m_lowest_bot = it;
533                                 continue;
534                         }
535                         if (temp_score < PlayerScore_Get(team_.m_lowest_bot, SP_SCORE))
536                         {
537                                 team_.m_lowest_bot = it;
538                         }
539                 });
540         }
541
542         // if the player who has a forced team has not joined yet, reserve the spot
543         if (autocvar_g_campaign)
544         {
545                 if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
546                 {
547                         entity team_ = TeamBalance_GetTeamFromIndex(balance,
548                                 autocvar_g_campaign_forceteam);
549                         if (team_.m_num_players == team_.m_num_bots)
550                         {
551                                 ++team_.m_num_players;
552                         }
553                 }
554         }
555         balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
556 }
557
558 int TeamBalance_GetNumberOfPlayers(entity balance, int index)
559 {
560         if (balance == NULL)
561         {
562                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
563                         "Team balance entity is NULL.");
564         }
565         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
566         {
567                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
568                         "TeamBalance_GetTeamCounts has not been called.");
569         }
570         if (!Team_IsValidIndex(index))
571         {
572                 LOG_FATALF("TeamBalance_GetNumberOfPlayers: Team index is invalid: %f",
573                         index);
574         }
575         return balance.m_team_balance_team[index - 1].m_num_players;
576 }
577
578 int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
579 {
580         if (balance == NULL)
581         {
582                 LOG_FATAL("TeamBalance_FindBestTeam: Team balance entity is NULL.");
583         }
584         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
585         {
586                 LOG_FATAL("TeamBalance_FindBestTeam: "
587                         "Team balance entity is not initialized.");
588         }
589         // count how many players are in each team
590         if (ignore_player)
591         {
592                 TeamBalance_GetTeamCounts(balance, player);
593         }
594         else
595         {
596                 TeamBalance_GetTeamCounts(balance, NULL);
597         }
598         int team_bits = TeamBalance_FindBestTeams(balance, player, true);
599         if (team_bits == 0)
600         {
601                 LOG_FATALF("TeamBalance_FindBestTeam: No teams available for %s\n",
602                         MapInfo_Type_ToString(MapInfo_CurrentGametype()));
603         }
604         RandomSelection_Init();
605         for (int i = 1; i <= NUM_TEAMS; ++i)
606         {
607                 if (team_bits & Team_IndexToBit(i))
608                 {
609                         RandomSelection_AddFloat(i, 1, 1);
610                 }
611         }
612         return RandomSelection_chosen_float;
613 }
614
615 int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
616 {
617         if (balance == NULL)
618         {
619                 LOG_FATAL("TeamBalance_FindBestTeams: Team balance entity is NULL.");
620         }
621         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
622         {
623                 LOG_FATAL("TeamBalance_FindBestTeams: "
624                         "TeamBalance_GetTeamCounts has not been called.");
625         }
626         if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
627         {
628                 return M_ARGV(1, float);
629         }
630         int team_bits = 0;
631         int previous_team = 0;
632         for (int i = 1; i <= NUM_TEAMS; ++i)
633         {
634                 if (!TeamBalance_IsTeamAllowedInternal(balance, i))
635                 {
636                         continue;
637                 }
638                 if (previous_team == 0)
639                 {
640                         team_bits = Team_IndexToBit(i);
641                         previous_team = i;
642                         continue;
643                 }
644                 int compare = TeamBalance_CompareTeams(balance, i, previous_team,
645                         player, use_score);
646                 if (compare == TEAMS_COMPARE_LESS)
647                 {
648                         team_bits = Team_IndexToBit(i);
649                         previous_team = i;
650                         continue;
651                 }
652                 if (compare == TEAMS_COMPARE_EQUAL)
653                 {
654                         team_bits |= Team_IndexToBit(i);
655                         previous_team = i;
656                 }
657         }
658         return team_bits;
659 }
660
661 void TeamBalance_JoinBestTeam(entity this, bool force_best_team)
662 {
663         // don't join a team if we're not playing a team game
664         if (!teamplay)
665         {
666                 return;
667         }
668
669         // find out what teams are available
670         entity balance = TeamBalance_CheckAllowedTeams(this);
671
672         // if we don't care what team they end up on, put them on whatever team they entered as.
673         // if they're not on a valid team, then let other code put them on the smallest team
674         if (!force_best_team)
675         {
676                 int selected_team_index = -1;
677                 for (int i = 1; i <= NUM_TEAMS; ++i)
678                 {
679                         if (TeamBalance_IsTeamAllowedInternal(balance, i) &&
680                                 (Team_TeamToIndex(this.team) == i))
681                         {
682                                 selected_team_index = i;
683                                 break;
684                         }
685                 }
686                 
687                 if (Team_IsValidIndex(selected_team_index))
688                 {
689                         Player_SetTeamIndex(this, selected_team_index);
690                         LogTeamchange(this.playerid, this.team, 99);
691                         TeamBalance_Destroy(balance);
692                         return;
693                 }
694         }
695         // otherwise end up on the smallest team (handled below)
696         if (this.bot_forced_team)
697         {
698                 TeamBalance_Destroy(balance);
699                 return;
700         }
701         int best_team_index = TeamBalance_FindBestTeam(balance, this, true);
702         int old_team_index = Team_TeamToIndex(this.team);
703         TeamchangeFrags(this);
704         Player_SetTeamIndex(this, best_team_index);
705         LogTeamchange(this.playerid, this.team, 2); // log auto join
706         if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
707         {
708                 TeamBalance_AutoBalanceBots(balance, old_team_index, best_team_index);
709         }
710         KillPlayerForTeamChange(this);
711         TeamBalance_Destroy(balance);
712 }
713
714 int TeamBalance_CompareTeams(entity balance, int team_index_a, int team_index_b,
715         entity player, bool use_score)
716 {
717         if (balance == NULL)
718         {
719                 LOG_FATAL("TeamBalance_CompareTeams: Team balance entity is NULL.");
720         }
721         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
722         {
723                 LOG_FATAL("TeamBalance_CompareTeams: "
724                         "TeamBalance_GetTeamCounts has not been called.");
725         }
726         if (!Team_IsValidIndex(team_index_a))
727         {
728                 LOG_FATALF("TeamBalance_CompareTeams: team_index_a is invalid: %f",
729                         team_index_a);
730         }
731         if (!Team_IsValidIndex(team_index_b))
732         {
733                 LOG_FATALF("TeamBalance_CompareTeams: team_index_b is invalid: %f",
734                         team_index_b);
735         }
736         if (team_index_a == team_index_b)
737         {
738                 return TEAMS_COMPARE_EQUAL;
739         }
740         entity team_a = TeamBalance_GetTeamFromIndex(balance, team_index_a);
741         entity team_b = TeamBalance_GetTeamFromIndex(balance, team_index_b);
742         return TeamBalance_CompareTeamsInternal(team_a, team_b, player, use_score);
743 }
744
745 void TeamBalance_AutoBalanceBots(entity balance, int source_team_index,
746         int destination_team_index)
747 {
748         if (balance == NULL)
749         {
750                 LOG_FATAL("TeamBalance_AutoBalanceBots: Team balance entity is NULL.");
751         }
752         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
753         {
754                 LOG_FATAL("TeamBalance_AutoBalanceBots: "
755                         "TeamBalance_GetTeamCounts has not been called.");
756         }
757         if (!Team_IsValidIndex(source_team_index))
758         {
759                 LOG_WARNF("AutoBalanceBots: Source team index is invalid: %f",
760                         source_team_index);
761                 return;
762         }
763         if (!Team_IsValidIndex(destination_team_index))
764         {
765                 LOG_WARNF("AutoBalanceBots: Destination team index is invalid: %f",
766                         destination_team_index);
767                 return;
768         }
769         if (!autocvar_g_balance_teams ||
770                 !autocvar_g_balance_teams_prevent_imbalance)
771         {
772                 return;
773         }
774         entity source_team = TeamBalance_GetTeamFromIndex(balance,
775                 source_team_index);
776         if (!TeamBalanceTeam_IsAllowed(source_team))
777         {
778                 return;
779         }
780         entity destination_team = TeamBalance_GetTeamFromIndex(balance,
781                 destination_team_index);
782         if ((destination_team.m_num_players <= source_team.m_num_players) ||
783                 (destination_team.m_lowest_bot == NULL))
784         {
785                 return;
786         }
787         Player_SetTeamIndex(destination_team.m_lowest_bot, source_team_index);
788         KillPlayerForTeamChange(destination_team.m_lowest_bot);
789 }
790
791 bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
792 {
793         return balance.m_team_balance_team[index - 1].m_num_players !=
794                 TEAM_NOT_ALLOWED;
795 }
796
797 void TeamBalance_BanTeamsExcept(entity balance, int index)
798 {
799         for (int i = 1; i <= NUM_TEAMS; ++i)
800         {
801                 if (i != index)
802                 {
803                         balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
804                 }
805         }
806 }
807
808 entity TeamBalance_GetTeamFromIndex(entity balance, int index)
809 {
810         if (!Team_IsValidIndex(index))
811         {
812                 LOG_FATALF("TeamBalance_GetTeamFromIndex: Index is invalid: %f", index);
813         }
814         return balance.m_team_balance_team[index - 1];
815 }
816
817 entity TeamBalance_GetTeam(entity balance, int team_num)
818 {
819         return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
820 }
821
822 bool TeamBalanceTeam_IsAllowed(entity team_)
823 {
824         return team_.m_num_players != TEAM_NOT_ALLOWED;
825 }
826
827 int TeamBalanceTeam_GetNumberOfPlayers(entity team_)
828 {
829         return team_.m_num_players;
830 }
831
832 int TeamBalanceTeam_GetNumberOfBots(entity team_)
833 {
834         return team_.m_num_bots;
835 }
836
837 entity TeamBalanceTeam_GetLowestHuman(entity team_)
838 {
839         return team_.m_lowest_human;
840 }
841
842 entity TeamBalanceTeam_GetLowestBot(entity team_)
843 {
844         return team_.m_lowest_bot;
845 }
846
847 int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b,
848         entity player, bool use_score)
849 {
850         if (team_a == team_b)
851         {
852                 return TEAMS_COMPARE_EQUAL;
853         }
854         if (!TeamBalanceTeam_IsAllowed(team_a) ||
855                 !TeamBalanceTeam_IsAllowed(team_b))
856         {
857                 return TEAMS_COMPARE_INVALID;
858         }
859         int num_players_team_a = team_a.m_num_players;
860         int num_players_team_b = team_b.m_num_players;
861         if (IS_REAL_CLIENT(player) && bots_would_leave)
862         {
863                 num_players_team_a -= team_a.m_num_bots;
864                 num_players_team_b -= team_b.m_num_bots;
865         }
866         if (num_players_team_a < num_players_team_b)
867         {
868                 return TEAMS_COMPARE_LESS;
869         }
870         if (num_players_team_a > num_players_team_b)
871         {
872                 return TEAMS_COMPARE_GREATER;
873         }
874         if (!use_score)
875         {
876                 return TEAMS_COMPARE_EQUAL;
877         }
878         if (team_a.m_team_score < team_b.m_team_score)
879         {
880                 return TEAMS_COMPARE_LESS;
881         }
882         if (team_a.m_team_score > team_b.m_team_score)
883         {
884                 return TEAMS_COMPARE_GREATER;
885         }
886         return TEAMS_COMPARE_EQUAL;
887 }
888
889 void SV_ChangeTeam(entity this, float _color)
890 {
891         int source_color, destination_color;
892         int source_team_index, destination_team_index;
893
894         // in normal deathmatch we can just apply the color and we're done
895         if(!teamplay)
896                 SetPlayerColors(this, _color);
897
898         if(!IS_CLIENT(this))
899         {
900                 // since this is an engine function, and gamecode doesn't have any calls earlier than this, do the connecting message here
901                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CONNECTING, this.netname);
902                 return;
903         }
904
905         if(!teamplay)
906                 return;
907
908         source_color = this.clientcolors & 0x0F;
909         destination_color = _color & 0x0F;
910
911         source_team_index = Team_TeamToIndex(source_color + 1);
912         destination_team_index = Team_TeamToIndex(destination_color + 1);
913
914         if (destination_team_index == -1)
915         {
916                 return;
917         }
918
919         entity balance = TeamBalance_CheckAllowedTeams(this);
920
921         if (destination_team_index == 1 && !TeamBalance_IsTeamAllowedInternal(
922                 balance, 1))
923         {
924                 destination_team_index = 4;
925         }
926         if (destination_team_index == 4 && !TeamBalance_IsTeamAllowedInternal(
927                 balance, 4))
928         {
929                 destination_team_index = 3;
930         }
931         if (destination_team_index == 3 && !TeamBalance_IsTeamAllowedInternal(
932                 balance, 3))
933         {
934                 destination_team_index = 2;
935         }
936         if (destination_team_index == 2 && !TeamBalance_IsTeamAllowedInternal(
937                 balance, 2))
938         {
939                 destination_team_index = 1;
940         }
941
942         // not changing teams
943         if (source_color == destination_color)
944         {
945                 SetPlayerTeam(this, destination_team_index, source_team_index, true);
946                 TeamBalance_Destroy(balance);
947                 return;
948         }
949
950         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && CS(this).wasplayer)) {
951                 Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
952                 return; // changing teams is not allowed
953         }
954
955         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
956         if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
957         {
958                 TeamBalance_GetTeamCounts(balance, this);
959                 if ((Team_IndexToBit(destination_team_index) &
960                         TeamBalance_FindBestTeams(balance, this, false)) == 0)
961                 {
962                         Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
963                         TeamBalance_Destroy(balance);
964                         return;
965                 }
966         }
967         if (IS_PLAYER(this) && source_team_index != destination_team_index)
968         {
969                 // reduce frags during a team change
970                 TeamchangeFrags(this);
971         }
972         if (!SetPlayerTeam(this, destination_team_index, source_team_index,
973                 !IS_CLIENT(this)))
974         {
975                 TeamBalance_Destroy(balance);
976                 return;
977         }
978         TeamBalance_AutoBalanceBots(balance, source_team_index,
979                 destination_team_index);
980         if (!IS_PLAYER(this) || (source_team_index == destination_team_index))
981         {
982                 TeamBalance_Destroy(balance);
983                 return;
984         }
985         KillPlayerForTeamChange(this);
986         TeamBalance_Destroy(balance);
987 }