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