5b9ab4db5faf240bcc887d156f083359521a19c1
[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 .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
40 entity g_team_entities[NUM_TEAMS]; ///< Holds global team entities.
41
42 STATIC_INIT(g_team_entities)
43 {
44         for (int i = 0; i < NUM_TEAMS; ++i)
45         {
46                 g_team_entities[i] = spawn();
47         }
48 }
49
50 entity Team_GetTeamFromIndex(int index)
51 {
52         if (!Team_IsValidIndex(index))
53         {
54                 LOG_FATALF("Team_GetTeamFromIndex: Index is invalid: %f", index);
55         }
56         return g_team_entities[index - 1];
57 }
58
59 entity Team_GetTeam(int team_num)
60 {
61         if (!Team_IsValidTeam(team_num))
62         {
63                 LOG_FATALF("Team_GetTeam: Value is invalid: %f", team_num);
64         }
65         return g_team_entities[Team_TeamToIndex(team_num) - 1];
66 }
67
68 float Team_GetTeamScore(entity team_ent)
69 {
70         return team_ent.m_team_score;
71 }
72
73 void Team_SetTeamScore(entity team_ent, float score)
74 {
75         team_ent.m_team_score = score;
76 }
77
78 int Team_GetNumberOfAlivePlayers(entity team_ent)
79 {
80         return team_ent.m_num_players_alive;
81 }
82
83 void Team_SetNumberOfAlivePlayers(entity team_ent, int number)
84 {
85         team_ent.m_num_players_alive = number;
86 }
87
88 int Team_GetNumberOfAliveTeams()
89 {
90         int result = 0;
91         for (int i = 0; i < NUM_TEAMS; ++i)
92         {
93                 if (g_team_entities[i].m_num_players_alive > 0)
94                 {
95                         ++result;
96                 }
97         }
98         return result;
99 }
100
101 int Team_GetNumberOfControlPoints(entity team_ent)
102 {
103         return team_ent.m_num_control_points;
104 }
105
106 void Team_SetNumberOfControlPoints(entity team_ent, int number)
107 {
108         team_ent.m_num_control_points = number;
109 }
110
111 int Team_GetNumberOfTeamsWithControlPoints()
112 {
113         int result = 0;
114         for (int i = 0; i < NUM_TEAMS; ++i)
115         {
116                 if (g_team_entities[i].m_num_control_points > 0)
117                 {
118                         ++result;
119                 }
120         }
121         return result;
122 }
123
124 void setcolor(entity this, int clr)
125 {
126 #if 0
127         this.clientcolors = clr;
128         this.team = (clr & 15) + 1;
129 #else
130         builtin_setcolor(this, clr);
131 #endif
132 }
133
134 bool Entity_HasValidTeam(entity this)
135 {
136         return Team_IsValidTeam(this.team);
137 }
138
139 int Entity_GetTeamIndex(entity this)
140 {
141         return Team_TeamToIndex(this.team);
142 }
143
144 entity Entity_GetTeam(entity this)
145 {
146         int index = Entity_GetTeamIndex(this);
147         if (!Team_IsValidIndex(index))
148         {
149                 return NULL;
150         }
151         return Team_GetTeamFromIndex(index);
152 }
153
154 void SetPlayerColors(entity player, float _color)
155 {
156         float pants = _color & 0x0F;
157         float shirt = _color & 0xF0;
158         if (teamplay)
159         {
160                 setcolor(player, 16 * pants + pants);
161         }
162         else
163         {
164                 setcolor(player, shirt + pants);
165         }
166 }
167
168 bool Player_SetTeamIndex(entity player, int index)
169 {
170         int new_team = Team_IndexToTeam(index);
171         if (player.team == new_team)
172         {
173                 if (new_team != -1)
174                 {
175                         // This is important when players join the game and one of their
176                         // color matches the team color while other doesn't. For example
177                         // [BOT]Lion.
178                         SetPlayerColors(player, new_team - 1);
179                 }
180                 return true;
181         }
182         int old_index = Team_TeamToIndex(player.team);
183         if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, old_index, index) == true)
184         {
185                 // Mutator has blocked team change.
186                 return false;
187         }
188         if (new_team == -1)
189         {
190                 player.team = -1;
191         }
192         else
193         {
194                 SetPlayerColors(player, new_team - 1);
195         }
196         MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_index, index);
197         return true;
198 }
199
200 bool SetPlayerTeam(entity player, int team_index, int type)
201 {
202         int old_team_index = Entity_GetTeamIndex(player);
203         if (!Player_SetTeamIndex(player, team_index))
204         {
205                 return false;
206         }
207         LogTeamchange(player.playerid, player.team, type);
208         if (team_index != old_team_index)
209         {
210                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(player.team,
211                         INFO_JOIN_PLAY_TEAM), player.netname);
212                 KillPlayerForTeamChange(player);
213         }
214         return true;
215 }
216
217 bool MoveToTeam(entity client, int team_index, int type)
218 {
219         //PrintToChatAll(sprintf("MoveToTeam: %s, %f", client.netname, team_index));
220         int lockteams_backup = lockteams;  // backup any team lock
221         lockteams = 0;  // disable locked teams
222         PlayerScore_Clear(client);
223         if (!SetPlayerTeam(client, team_index, type))
224         {
225                 lockteams = lockteams_backup;  // restore the team lock
226                 return false;
227         }
228         lockteams = lockteams_backup;  // restore the team lock
229         return true;
230 }
231
232 void KillPlayerForTeamChange(entity player)
233 {
234         if (IS_DEAD(player))
235         {
236                 return;
237         }
238         if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
239         {
240                 return;
241         }
242         Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
243                 player.origin, '0 0 0');
244 }
245
246 void LogTeamchange(float player_id, float team_number, int type)
247 {
248         if(!autocvar_sv_eventlog)
249                 return;
250
251         if(player_id < 1)
252                 return;
253
254         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
255 }
256
257 entity TeamBalance_CheckAllowedTeams(entity for_whom)
258 {
259         entity balance = spawn();
260         for (int i = 0; i < NUM_TEAMS; ++i)
261         {
262                 entity team_ent = balance.m_team_balance_team[i] = spawn();
263                 team_ent.m_team_score = g_team_entities[i].m_team_score;
264                 team_ent.m_num_players = TEAM_NOT_ALLOWED;
265                 team_ent.m_num_bots = 0;
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                 delete(balance.(m_team_balance_team[i]));
405         }
406         delete(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_ent = TeamBalance_GetTeamFromIndex(balance, i);
467                         if (TeamBalanceTeam_IsAllowed(team_ent))
468                         {
469                                 MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore);
470                                 team_ent.m_num_players = M_ARGV(2, float);
471                                 team_ent.m_num_bots = M_ARGV(3, float);
472                         }
473                 }
474         }
475         else
476         {
477                 // Manually count all players.
478                 FOREACH_CLIENT(true,
479                 {
480                         if (it == ignore)
481                         {
482                                 continue;
483                         }
484                         int team_num;
485                         if (IS_PLAYER(it) || it.caplayer)
486                         {
487                                 team_num = it.team;
488                         }
489                         else if (it.team_forced > 0)
490                         {
491                                 team_num = it.team_forced; // reserve the spot
492                         }
493                         else
494                         {
495                                 continue;
496                         }
497                         if (!Team_IsValidTeam(team_num))
498                         {
499                                 continue;
500                         }
501                         entity team_ent = TeamBalance_GetTeam(balance, team_num);
502                         if (!TeamBalanceTeam_IsAllowed(team_ent))
503                         {
504                                 continue;
505                         }
506                         ++team_ent.m_num_players;
507                         if (IS_BOT_CLIENT(it))
508                         {
509                                 ++team_ent.m_num_bots;
510                         }
511                 });
512         }
513
514         // if the player who has a forced team has not joined yet, reserve the spot
515         if (autocvar_g_campaign)
516         {
517                 if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
518                 {
519                         entity team_ent = TeamBalance_GetTeamFromIndex(balance,
520                                 autocvar_g_campaign_forceteam);
521                         if (team_ent.m_num_players == team_ent.m_num_bots)
522                         {
523                                 ++team_ent.m_num_players;
524                         }
525                 }
526         }
527         balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
528 }
529
530 int TeamBalance_GetNumberOfPlayers(entity balance, int index)
531 {
532         if (balance == NULL)
533         {
534                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
535                         "Team balance entity is NULL.");
536         }
537         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
538         {
539                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
540                         "TeamBalance_GetTeamCounts has not been called.");
541         }
542         if (!Team_IsValidIndex(index))
543         {
544                 LOG_FATALF("TeamBalance_GetNumberOfPlayers: Team index is invalid: %f",
545                         index);
546         }
547         return balance.m_team_balance_team[index - 1].m_num_players;
548 }
549
550 int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
551 {
552         if (balance == NULL)
553         {
554                 LOG_FATAL("TeamBalance_FindBestTeam: Team balance entity is NULL.");
555         }
556         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
557         {
558                 LOG_FATAL("TeamBalance_FindBestTeam: "
559                         "Team balance entity is not initialized.");
560         }
561         // count how many players are in each team
562         if (ignore_player)
563         {
564                 TeamBalance_GetTeamCounts(balance, player);
565         }
566         else
567         {
568                 TeamBalance_GetTeamCounts(balance, NULL);
569         }
570         int team_bits = TeamBalance_FindBestTeams(balance, player, true);
571         if (team_bits == 0)
572         {
573                 LOG_FATALF("TeamBalance_FindBestTeam: No teams available for %s\n",
574                         MapInfo_Type_ToString(MapInfo_CurrentGametype()));
575         }
576         RandomSelection_Init();
577         for (int i = 1; i <= NUM_TEAMS; ++i)
578         {
579                 if (team_bits & Team_IndexToBit(i))
580                 {
581                         RandomSelection_AddFloat(i, 1, 1);
582                 }
583         }
584         return RandomSelection_chosen_float;
585 }
586
587 int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
588 {
589         if (balance == NULL)
590         {
591                 LOG_FATAL("TeamBalance_FindBestTeams: Team balance entity is NULL.");
592         }
593         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
594         {
595                 LOG_FATAL("TeamBalance_FindBestTeams: "
596                         "TeamBalance_GetTeamCounts has not been called.");
597         }
598         if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
599         {
600                 return M_ARGV(1, float);
601         }
602         int team_bits = 0;
603         int previous_team = 0;
604         for (int i = 1; i <= NUM_TEAMS; ++i)
605         {
606                 if (!TeamBalance_IsTeamAllowedInternal(balance, i))
607                 {
608                         continue;
609                 }
610                 if (previous_team == 0)
611                 {
612                         team_bits = Team_IndexToBit(i);
613                         previous_team = i;
614                         continue;
615                 }
616                 int compare = TeamBalance_CompareTeams(balance, i, previous_team,
617                         player, use_score);
618                 if (compare == TEAMS_COMPARE_LESS)
619                 {
620                         team_bits = Team_IndexToBit(i);
621                         previous_team = i;
622                         continue;
623                 }
624                 if (compare == TEAMS_COMPARE_EQUAL)
625                 {
626                         team_bits |= Team_IndexToBit(i);
627                         previous_team = i;
628                 }
629         }
630         return team_bits;
631 }
632
633 void TeamBalance_JoinBestTeam(entity this, bool force_best_team)
634 {
635         //PrintToChatAll(sprintf("JoinBestTeam: %s, %f", this.netname, force_best_team));
636         // don't join a team if we're not playing a team game
637         if (!teamplay)
638         {
639                 return;
640         }
641
642         // find out what teams are available
643         entity balance = TeamBalance_CheckAllowedTeams(this);
644
645         // if we don't care what team they end up on, put them on whatever team they entered as.
646         // if they're not on a valid team, then let other code put them on the smallest team
647         if (!force_best_team)
648         {
649                 int selected_team_index = -1;
650                 for (int i = 1; i <= NUM_TEAMS; ++i)
651                 {
652                         if (TeamBalance_IsTeamAllowedInternal(balance, i) &&
653                                 (Team_TeamToIndex(this.team) == i))
654                         {
655                                 selected_team_index = i;
656                                 break;
657                         }
658                 }
659                 
660                 if (Team_IsValidIndex(selected_team_index))
661                 {
662                         SetPlayerTeam(this, selected_team_index, TEAM_CHANGE_AUTO_RELAXED);
663                         TeamBalance_Destroy(balance);
664                         return;
665                 }
666         }
667         // otherwise end up on the smallest team (handled below)
668         if (this.bot_forced_team)
669         {
670                 TeamBalance_Destroy(balance);
671                 return;
672         }
673         int best_team_index = TeamBalance_FindBestTeam(balance, this, true);
674         int old_team_index = Team_TeamToIndex(this.team);
675         TeamBalance_Destroy(balance);
676         PlayerScore_Clear(this);
677         if (!SetPlayerTeam(this, best_team_index, TEAM_CHANGE_AUTO))
678         {
679                 return;
680         }
681         if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
682         {
683                 TeamBalance_AutoBalanceBots(best_team_index, old_team_index);
684         }
685 }
686
687 int TeamBalance_CompareTeams(entity balance, int team_index_a, int team_index_b,
688         entity player, bool use_score)
689 {
690         if (balance == NULL)
691         {
692                 LOG_FATAL("TeamBalance_CompareTeams: Team balance entity is NULL.");
693         }
694         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
695         {
696                 LOG_FATAL("TeamBalance_CompareTeams: "
697                         "TeamBalance_GetTeamCounts has not been called.");
698         }
699         if (!Team_IsValidIndex(team_index_a))
700         {
701                 LOG_FATALF("TeamBalance_CompareTeams: team_index_a is invalid: %f",
702                         team_index_a);
703         }
704         if (!Team_IsValidIndex(team_index_b))
705         {
706                 LOG_FATALF("TeamBalance_CompareTeams: team_index_b is invalid: %f",
707                         team_index_b);
708         }
709         if (team_index_a == team_index_b)
710         {
711                 return TEAMS_COMPARE_EQUAL;
712         }
713         entity team_a = TeamBalance_GetTeamFromIndex(balance, team_index_a);
714         entity team_b = TeamBalance_GetTeamFromIndex(balance, team_index_b);
715         return TeamBalance_CompareTeamsInternal(team_a, team_b, player, use_score);
716 }
717
718 void TeamBalance_AutoBalanceBots(int source_team_index,
719         int destination_team_index)
720 {
721         if (!Team_IsValidIndex(source_team_index))
722         {
723                 LOG_WARNF("TeamBalance_AutoBalanceBots: "
724                         "Source team index is invalid: %f", source_team_index);
725                 return;
726         }
727         if (!Team_IsValidIndex(destination_team_index))
728         {
729                 LOG_WARNF("TeamBalance_AutoBalanceBots: "
730                         "Destination team index is invalid: %f", destination_team_index);
731                 return;
732         }
733         if (!autocvar_g_balance_teams ||
734                 !autocvar_g_balance_teams_prevent_imbalance)
735         {
736                 return;
737         }
738         entity balance = TeamBalance_CheckAllowedTeams(NULL);
739         TeamBalance_GetTeamCounts(balance, NULL);
740         entity source_team = TeamBalance_GetTeamFromIndex(balance,
741                 source_team_index);
742         entity destination_team = TeamBalance_GetTeamFromIndex(balance,
743                 destination_team_index);
744         if ((source_team.m_num_bots == 0) || (source_team.m_num_players <=
745                 destination_team.m_num_players))
746         {
747                 TeamBalance_Destroy(balance);
748                 return;
749         }
750         TeamBalance_Destroy(balance);
751         entity lowest_bot = NULL;
752         if (MUTATOR_CALLHOOK(TeamBalance_GetPlayerForTeamSwitch, source_team_index,
753                 destination_team_index, true))
754         {
755                 lowest_bot = M_ARGV(3, entity);
756         }
757         else
758         {
759                 float lowest_score = FLOAT_MAX;
760                 FOREACH_CLIENT(IS_BOT_CLIENT(it) && (Entity_GetTeamIndex(it) ==
761                         source_team_index),
762                 {
763                         float temp_score = PlayerScore_Get(it, SP_SCORE);
764                         if (temp_score >= lowest_score)
765                         {
766                                 continue;
767                         }
768                         balance = TeamBalance_CheckAllowedTeams(it);
769                         if (TeamBalance_IsTeamAllowed(balance, destination_team_index))
770                         {
771                                 lowest_bot = it;
772                                 lowest_score = temp_score;
773                         }
774                         TeamBalance_Destroy(balance);
775                 });
776         }
777         if (lowest_bot == NULL)
778         {
779                 return;
780         }
781         if (!Player_SetTeamIndex(lowest_bot, destination_team_index))
782         {
783                 return;
784         }
785         KillPlayerForTeamChange(lowest_bot);
786 }
787
788 bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
789 {
790         return balance.m_team_balance_team[index - 1].m_num_players !=
791                 TEAM_NOT_ALLOWED;
792 }
793
794 void TeamBalance_BanTeamsExcept(entity balance, int index)
795 {
796         for (int i = 1; i <= NUM_TEAMS; ++i)
797         {
798                 if (i != index)
799                 {
800                         balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
801                 }
802         }
803 }
804
805 entity TeamBalance_GetTeamFromIndex(entity balance, int index)
806 {
807         if (!Team_IsValidIndex(index))
808         {
809                 LOG_FATALF("TeamBalance_GetTeamFromIndex: Index is invalid: %f", index);
810         }
811         return balance.m_team_balance_team[index - 1];
812 }
813
814 entity TeamBalance_GetTeam(entity balance, int team_num)
815 {
816         return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
817 }
818
819 bool TeamBalanceTeam_IsAllowed(entity team_ent)
820 {
821         return team_ent.m_num_players != TEAM_NOT_ALLOWED;
822 }
823
824 int TeamBalanceTeam_GetNumberOfPlayers(entity team_ent)
825 {
826         return team_ent.m_num_players;
827 }
828
829 int TeamBalanceTeam_GetNumberOfBots(entity team_ent)
830 {
831         return team_ent.m_num_bots;
832 }
833
834 int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b,
835         entity player, bool use_score)
836 {
837         if (team_a == team_b)
838         {
839                 return TEAMS_COMPARE_EQUAL;
840         }
841         if (!TeamBalanceTeam_IsAllowed(team_a) ||
842                 !TeamBalanceTeam_IsAllowed(team_b))
843         {
844                 return TEAMS_COMPARE_INVALID;
845         }
846         int num_players_team_a = team_a.m_num_players;
847         int num_players_team_b = team_b.m_num_players;
848         if (IS_REAL_CLIENT(player) && bots_would_leave)
849         {
850                 num_players_team_a -= team_a.m_num_bots;
851                 num_players_team_b -= team_b.m_num_bots;
852         }
853         if (num_players_team_a < num_players_team_b)
854         {
855                 return TEAMS_COMPARE_LESS;
856         }
857         if (num_players_team_a > num_players_team_b)
858         {
859                 return TEAMS_COMPARE_GREATER;
860         }
861         if (!use_score)
862         {
863                 return TEAMS_COMPARE_EQUAL;
864         }
865         if (team_a.m_team_score < team_b.m_team_score)
866         {
867                 return TEAMS_COMPARE_LESS;
868         }
869         if (team_a.m_team_score > team_b.m_team_score)
870         {
871                 return TEAMS_COMPARE_GREATER;
872         }
873         return TEAMS_COMPARE_EQUAL;
874 }
875
876 // Called when the player connects or when they change their color with "color"
877 // command.
878 void SV_ChangeTeam(entity this, float _color)
879 {
880         //PrintToChatAll(sprintf("SV_ChangeTeam: %s, %f", this.netname, _color));
881
882         // in normal deathmatch we can just apply the color and we're done
883         if(!teamplay)
884                 SetPlayerColors(this, _color);
885
886         if(!IS_CLIENT(this))
887         {
888                 // since this is an engine function, and gamecode doesn't have any calls earlier than this, do the connecting message here
889                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CONNECTING, this.netname);
890                 return;
891         }
892
893         if(!teamplay)
894                 return;
895
896         int source_color, destination_color;
897         int source_team_index, destination_team_index;
898
899         source_color = this.clientcolors & 0x0F;
900         destination_color = _color & 0x0F;
901
902         source_team_index = Team_TeamToIndex(source_color + 1);
903         destination_team_index = Team_TeamToIndex(destination_color + 1);
904
905         if (destination_team_index == -1)
906         {
907                 return;
908         }
909
910         entity balance = TeamBalance_CheckAllowedTeams(this);
911
912         if (destination_team_index == 1 && !TeamBalance_IsTeamAllowedInternal(
913                 balance, 1))
914         {
915                 destination_team_index = 4;
916         }
917         if (destination_team_index == 4 && !TeamBalance_IsTeamAllowedInternal(
918                 balance, 4))
919         {
920                 destination_team_index = 3;
921         }
922         if (destination_team_index == 3 && !TeamBalance_IsTeamAllowedInternal(
923                 balance, 3))
924         {
925                 destination_team_index = 2;
926         }
927         if (destination_team_index == 2 && !TeamBalance_IsTeamAllowedInternal(
928                 balance, 2))
929         {
930                 destination_team_index = 1;
931         }
932
933         // not changing teams
934         if (source_color == destination_color)
935         {
936                 SetPlayerTeam(this, destination_team_index, TEAM_CHANGE_MANUAL);
937                 TeamBalance_Destroy(balance);
938                 return;
939         }
940
941         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && CS(this).wasplayer)) {
942                 Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
943                 return; // changing teams is not allowed
944         }
945
946         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
947         if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
948         {
949                 TeamBalance_GetTeamCounts(balance, this);
950                 if ((Team_IndexToBit(destination_team_index) &
951                         TeamBalance_FindBestTeams(balance, this, false)) == 0)
952                 {
953                         Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
954                         TeamBalance_Destroy(balance);
955                         return;
956                 }
957         }
958         TeamBalance_Destroy(balance);
959         if (IS_PLAYER(this) && source_team_index != destination_team_index)
960         {
961                 // reduce frags during a team change
962                 PlayerScore_Clear(this);
963         }
964         if (!SetPlayerTeam(this, destination_team_index, TEAM_CHANGE_MANUAL))
965         {
966                 return;
967         }
968         TeamBalance_AutoBalanceBots(destination_team_index, source_team_index);
969 }