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