]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/teamplay.qc
e2b16cab9a2babf7aa10e8bdece8cf4a3b93a002
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / teamplay.qc
1 #include "teamplay.qh"
2
3 #include "client.qh"
4 #include "race.qh"
5 #include "scores.qh"
6 #include "scores_rules.qh"
7
8 #include "bot/api.qh"
9
10 #include "command/vote.qh"
11
12 #include "mutators/_mod.qh"
13
14 #include "../common/deathtypes/all.qh"
15 #include "../common/gamemodes/_mod.qh"
16 #include "../common/teams.qh"
17
18 /// \brief Describes a state of team balance entity.
19 enum
20 {
21         TEAM_BALANCE_UNINITIALIZED, ///< The team balance has not been initialized.
22         /// \brief TeamBalance_CheckAllowedTeams has been called.
23         TEAM_BALANCE_TEAMS_CHECKED,
24         /// \brief TeamBalance_GetTeamCounts has been called.
25         TEAM_BALANCE_TEAM_COUNTS_FILLED
26 };
27
28 /// \brief Indicates that the player is not allowed to join a team.
29 const int TEAM_NOT_ALLOWED = -1;
30
31 .int m_team_balance_state; ///< Holds the state of the team balance entity.
32 .entity m_team_balance_team[NUM_TEAMS]; ///< ???
33
34 .float m_team_score; ///< The score of the team.
35 .int m_num_players; ///< Number of players (both humans and bots) in a team.
36 .int m_num_bots; ///< Number of bots in a team.
37 .entity m_lowest_human; ///< Human with the lowest score in a team.
38 .entity m_lowest_bot; ///< Bot with the lowest score in 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_)
69 {
70         return team_.m_team_score;
71 }
72
73 void Team_SetTeamScore(entity team_, float score)
74 {
75         team_.m_team_score = score;
76 }
77
78 void TeamchangeFrags(entity e)
79 {
80         PlayerScore_Clear(e);
81 }
82
83 void LogTeamchange(float player_id, float team_number, float type)
84 {
85         if(!autocvar_sv_eventlog)
86                 return;
87
88         if(player_id < 1)
89                 return;
90
91         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
92 }
93
94 void default_delayedinit(entity this)
95 {
96         if(!scores_initialized)
97                 ScoreRules_generic();
98 }
99
100 void InitGameplayMode()
101 {
102         VoteReset();
103
104         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
105         get_mi_min_max(1);
106         // assign reflectively to avoid "assignment to world" warning
107         int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
108             string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
109             if (v) {
110             putentityfieldstring(i, world, sprintf("%v", v));
111             if (++done == 2) break;
112         }
113         }
114         // currently, NetRadiant's limit is 131072 qu for each side
115         // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
116         // set the distance according to map size but don't go over the limit to avoid issues with float precision
117         // in case somebody makes extremely large maps
118         max_shot_distance = min(230000, vlen(world.maxs - world.mins));
119
120         MapInfo_LoadMapSettings(mapname);
121         GameRules_teams(false);
122
123         if (!cvar_value_issafe(world.fog))
124         {
125                 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
126                 world.fog = string_null;
127         }
128         if(MapInfo_Map_fog != "")
129                 if(MapInfo_Map_fog == "none")
130                         world.fog = string_null;
131                 else
132                         world.fog = strzone(MapInfo_Map_fog);
133         clientstuff = strzone(MapInfo_Map_clientstuff);
134
135         MapInfo_ClearTemps();
136
137         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
138
139         cache_mutatormsg = strzone("");
140         cache_lastmutatormsg = strzone("");
141
142         InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
143 }
144
145 string GetClientVersionMessage(entity this)
146 {
147         if (CS(this).version_mismatch) {
148                 if(CS(this).version < autocvar_gameversion) {
149                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
150                                 "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8");
151                 } else {
152                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
153                                 "\n^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8");
154                 }
155         } else {
156                 return strcat("Welcome to Xonotic ", autocvar_g_xonoticversion);
157         }
158 }
159
160 string getwelcomemessage(entity this)
161 {
162         MUTATOR_CALLHOOK(BuildMutatorsPrettyString, "");
163         string modifications = M_ARGV(0, string);
164
165         if(g_weaponarena)
166         {
167                 if(g_weaponarena_random)
168                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
169                 else
170                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
171         }
172         else if(cvar("g_balance_blaster_weaponstartoverride") == 0)
173                 modifications = strcat(modifications, ", No start weapons");
174         if(cvar("sv_gravity") < stof(cvar_defstring("sv_gravity")))
175                 modifications = strcat(modifications, ", Low gravity");
176         if(g_weapon_stay && !g_cts)
177                 modifications = strcat(modifications, ", Weapons stay");
178         if(g_jetpack)
179                 modifications = strcat(modifications, ", Jet pack");
180         if(autocvar_g_powerups == 0)
181                 modifications = strcat(modifications, ", No powerups");
182         if(autocvar_g_powerups > 0)
183                 modifications = strcat(modifications, ", Powerups");
184         modifications = substring(modifications, 2, strlen(modifications) - 2);
185
186         string versionmessage = GetClientVersionMessage(this);
187         string s = strcat(versionmessage, "^8\n^8\nmatch type is ^1", gamemode_name, "^8\n");
188
189         if(modifications != "")
190                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
191
192         if(cache_lastmutatormsg != autocvar_g_mutatormsg)
193         {
194                 if(cache_lastmutatormsg)
195                         strunzone(cache_lastmutatormsg);
196                 if(cache_mutatormsg)
197                         strunzone(cache_mutatormsg);
198                 cache_lastmutatormsg = strzone(autocvar_g_mutatormsg);
199                 cache_mutatormsg = strzone(cache_lastmutatormsg);
200         }
201
202         if (cache_mutatormsg != "") {
203                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
204         }
205
206         string mutator_msg = "";
207         MUTATOR_CALLHOOK(BuildGameplayTipsString, mutator_msg);
208         mutator_msg = M_ARGV(0, string);
209
210         s = strcat(s, mutator_msg); // trust that the mutator will do proper formatting
211
212         string motd = autocvar_sv_motd;
213         if (motd != "") {
214                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
215         }
216         return s;
217 }
218
219 void setcolor(entity this, int clr)
220 {
221 #if 0
222         this.clientcolors = clr;
223         this.team = (clr & 15) + 1;
224 #else
225         builtin_setcolor(this, clr);
226 #endif
227 }
228
229 int Entity_GetTeamIndex(entity this)
230 {
231         return Team_TeamToIndex(this.team);
232 }
233
234 void SetPlayerColors(entity player, float _color)
235 {
236         float pants = _color & 0x0F;
237         float shirt = _color & 0xF0;
238         if (teamplay)
239         {
240                 setcolor(player, 16 * pants + pants);
241         }
242         else
243         {
244                 setcolor(player, shirt + pants);
245         }
246 }
247
248 bool Player_SetTeamIndex(entity player, int index)
249 {
250         int new_team = Team_IndexToTeam(index);
251         if (player.team == new_team)
252         {
253                 // This is important when players join the game and one of their color
254                 // matches the team color while other doesn't. For example [BOT]Lion.
255                 SetPlayerColors(player, new_team - 1);
256                 return true;
257         }
258         int old_index = Team_TeamToIndex(player.team);
259         if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, old_index, index) == true)
260         {
261                 // Mutator has blocked team change.
262                 return false;
263         }
264         SetPlayerColors(player, new_team - 1);
265         MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_index, index);
266         return true;
267 }
268
269 bool SetPlayerTeam(entity player, int destination_team_index,
270         int source_team_index, bool no_print)
271 {
272         if (!Player_SetTeamIndex(player, destination_team_index))
273         {
274                 return false;
275         }
276         LogTeamchange(player.playerid, player.team, 3);  // log manual team join
277         if (no_print)
278         {
279                 return true;
280         }
281         bprint(playername(player, false), "^7 has changed from ",
282                 Team_IndexToColoredFullName(source_team_index), "^7 to ",
283                 Team_IndexToColoredFullName(destination_team_index), "\n");
284         return true;
285 }
286
287 void KillPlayerForTeamChange(entity player)
288 {
289         if (IS_DEAD(player))
290         {
291                 return;
292         }
293         if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
294         {
295                 return;
296         }
297         Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
298                 player.origin, '0 0 0');
299 }
300
301 entity TeamBalance_CheckAllowedTeams(entity for_whom)
302 {
303         entity balance = spawn();
304         for (int i = 0; i < NUM_TEAMS; ++i)
305         {
306                 entity team_ = balance.m_team_balance_team[i] = spawn();
307                 team_.m_team_score = g_team_entities[i].m_team_score;
308                 team_.m_num_players = TEAM_NOT_ALLOWED;
309                 team_.m_num_bots = 0;
310                 team_.m_lowest_human = NULL;
311                 team_.m_lowest_bot = NULL;
312         }
313         
314         int teams_mask = 0;     
315         string teament_name = string_null;
316         bool mutator_returnvalue = MUTATOR_CALLHOOK(TeamBalance_CheckAllowedTeams,
317                 teams_mask, teament_name, for_whom);
318         teams_mask = M_ARGV(0, float);
319         teament_name = M_ARGV(1, string);
320         if (mutator_returnvalue)
321         {
322                 for (int i = 0; i < NUM_TEAMS; ++i)
323                 {
324                         if (teams_mask & BIT(i))
325                         {
326                                 balance.m_team_balance_team[i].m_num_players = 0;
327                         }
328                 }
329         }
330
331         if (teament_name)
332         {
333                 entity head = find(NULL, classname, teament_name);
334                 while (head)
335                 {
336                         if (Team_IsValidTeam(head.team))
337                         {
338                                 TeamBalance_GetTeam(balance, head.team).m_num_players = 0;
339                         }
340                         head = find(head, classname, teament_name);
341                 }
342         }
343
344         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
345         if (AvailableTeams() == 2)
346         if (autocvar_bot_vs_human && for_whom)
347         {
348                 if (autocvar_bot_vs_human > 0)
349                 {
350                         // find last team available
351                         if (IS_BOT_CLIENT(for_whom))
352                         {
353                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
354                                 {
355                                         TeamBalance_BanTeamsExcept(balance, 4);
356                                 }
357                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
358                                 {
359                                         TeamBalance_BanTeamsExcept(balance, 3);
360                                 }
361                                 else
362                                 {
363                                         TeamBalance_BanTeamsExcept(balance, 2);
364                                 }
365                                 // no further cases, we know at least 2 teams exist
366                         }
367                         else
368                         {
369                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
370                                 {
371                                         TeamBalance_BanTeamsExcept(balance, 1);
372                                 }
373                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
374                                 {
375                                         TeamBalance_BanTeamsExcept(balance, 2);
376                                 }
377                                 else
378                                 {
379                                         TeamBalance_BanTeamsExcept(balance, 3);
380                                 }
381                                 // no further cases, bots have one of the teams
382                         }
383                 }
384                 else
385                 {
386                         // find first team available
387                         if (IS_BOT_CLIENT(for_whom))
388                         {
389                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
390                                 {
391                                         TeamBalance_BanTeamsExcept(balance, 1);
392                                 }
393                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
394                                 {
395                                         TeamBalance_BanTeamsExcept(balance, 2);
396                                 }
397                                 else
398                                 {
399                                         TeamBalance_BanTeamsExcept(balance, 3);
400                                 }
401                                 // no further cases, we know at least 2 teams exist
402                         }
403                         else
404                         {
405                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
406                                 {
407                                         TeamBalance_BanTeamsExcept(balance, 4);
408                                 }
409                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
410                                 {
411                                         TeamBalance_BanTeamsExcept(balance, 3);
412                                 }
413                                 else
414                                 {
415                                         TeamBalance_BanTeamsExcept(balance, 2);
416                                 }
417                                 // no further cases, bots have one of the teams
418                         }
419                 }
420         }
421
422         if (!for_whom)
423         {
424                 balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
425                 return balance;
426         }
427
428         // if player has a forced team, ONLY allow that one
429         for (int i = 1; i <= NUM_TEAMS; ++i)
430         {
431                 if (for_whom.team_forced == Team_IndexToTeam(i) &&
432                         TeamBalance_IsTeamAllowedInternal(balance, i))
433                 {
434                         TeamBalance_BanTeamsExcept(balance, i);
435                 }
436                 break;
437         }
438         balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
439         return balance;
440 }
441
442 void TeamBalance_Destroy(entity balance)
443 {
444         if (balance == NULL)
445         {
446                 return;
447         }
448         for (int i = 0; i < NUM_TEAMS; ++i)
449         {
450                 remove(balance.(m_team_balance_team[i]));
451         }
452         remove(balance);
453 }
454
455 int TeamBalance_GetAllowedTeams(entity balance)
456 {
457         if (balance == NULL)
458         {
459                 LOG_FATAL("TeamBalance_GetAllowedTeams: Team balance entity is NULL.");
460         }
461         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
462         {
463                 LOG_FATAL("TeamBalance_GetAllowedTeams: "
464                         "Team balance entity is not initialized.");
465         }
466         int result = 0;
467         for (int i = 1; i <= NUM_TEAMS; ++i)
468         {
469                 if (TeamBalance_IsTeamAllowedInternal(balance, i))
470                 {
471                         result |= Team_IndexToBit(i);
472                 }
473         }
474         return result;
475 }
476
477 bool TeamBalance_IsTeamAllowed(entity balance, int index)
478 {
479         if (balance == NULL)
480         {
481                 LOG_FATAL("TeamBalance_IsTeamAllowed: Team balance entity is NULL.");
482         }
483         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
484         {
485                 LOG_FATAL("TeamBalance_IsTeamAllowed: "
486                         "Team balance entity is not initialized.");
487         }
488         if (!Team_IsValidIndex(index))
489         {
490                 LOG_FATALF("TeamBalance_IsTeamAllowed: Team index is invalid: %f",
491                         index);
492         }
493         return TeamBalance_IsTeamAllowedInternal(balance, index);
494 }
495
496 void TeamBalance_GetTeamCounts(entity balance, entity ignore)
497 {
498         if (balance == NULL)
499         {
500                 LOG_FATAL("TeamBalance_GetTeamCounts: Team balance entity is NULL.");
501         }
502         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
503         {
504                 LOG_FATAL("TeamBalance_GetTeamCounts: "
505                         "Team balance entity is not initialized.");
506         }
507         if (MUTATOR_CALLHOOK(TeamBalance_GetTeamCounts) == true)
508         {
509                 // Mutator has overriden the configuration.
510                 for (int i = 1; i <= NUM_TEAMS; ++i)
511                 {
512                         entity team_ = TeamBalance_GetTeamFromIndex(balance, i);
513                         if (TeamBalanceTeam_IsAllowed(team_))
514                         {
515                                 MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore,
516                                         team_.m_num_players, team_.m_num_bots, team_.m_lowest_human,
517                                         team_.m_lowest_bot);
518                                 team_.m_num_players = M_ARGV(2, float);
519                                 team_.m_num_bots = M_ARGV(3, float);
520                                 team_.m_lowest_human = M_ARGV(4, entity);
521                                 team_.m_lowest_bot = M_ARGV(5, entity);
522                         }
523                 }
524         }
525         else
526         {
527                 // Manually count all players.
528                 FOREACH_CLIENT(true,
529                 {
530                         if (it == ignore)
531                         {
532                                 continue;
533                         }
534                         int team_num;
535                         if (IS_PLAYER(it) || it.caplayer)
536                         {
537                                 team_num = it.team;
538                         }
539                         else if (it.team_forced > 0)
540                         {
541                                 team_num = it.team_forced; // reserve the spot
542                         }
543                         else
544                         {
545                                 continue;
546                         }
547                         if (!Team_IsValidTeam(team_num))
548                         {
549                                 continue;
550                         }
551                         entity team_ = TeamBalance_GetTeam(balance, team_num);
552                         if (!TeamBalanceTeam_IsAllowed(team_))
553                         {
554                                 continue;
555                         }
556                         ++team_.m_num_players;
557                         if (IS_BOT_CLIENT(it))
558                         {
559                                 ++team_.m_num_bots;
560                         }
561                         float temp_score = PlayerScore_Get(it, SP_SCORE);
562                         if (!IS_BOT_CLIENT(it))
563                         {
564                                 if (team_.m_lowest_human == NULL)
565                                 {
566                                         team_.m_lowest_human = it;
567                                         continue;
568                                 }
569                                 if (temp_score < PlayerScore_Get(team_.m_lowest_human,
570                                         SP_SCORE))
571                                 {
572                                         team_.m_lowest_human = it;
573                                 }
574                                 continue;
575                         }
576                         if (team_.m_lowest_bot == NULL)
577                         {
578                                 team_.m_lowest_bot = it;
579                                 continue;
580                         }
581                         if (temp_score < PlayerScore_Get(team_.m_lowest_bot, SP_SCORE))
582                         {
583                                 team_.m_lowest_bot = it;
584                         }
585                 });
586         }
587
588         // if the player who has a forced team has not joined yet, reserve the spot
589         if (autocvar_g_campaign)
590         {
591                 if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
592                 {
593                         entity team_ = TeamBalance_GetTeamFromIndex(balance,
594                                 autocvar_g_campaign_forceteam);
595                         if (team_.m_num_players == team_.m_num_bots)
596                         {
597                                 ++team_.m_num_players;
598                         }
599                 }
600         }
601         balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
602 }
603
604 int TeamBalance_GetNumberOfPlayers(entity balance, int index)
605 {
606         if (balance == NULL)
607         {
608                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
609                         "Team balance entity is NULL.");
610         }
611         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
612         {
613                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
614                         "TeamBalance_GetTeamCounts has not been called.");
615         }
616         if (!Team_IsValidIndex(index))
617         {
618                 LOG_FATALF("TeamBalance_GetNumberOfPlayers: Team index is invalid: %f",
619                         index);
620         }
621         return balance.m_team_balance_team[index - 1].m_num_players;
622 }
623
624 int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
625 {
626         if (balance == NULL)
627         {
628                 LOG_FATAL("TeamBalance_FindBestTeam: Team balance entity is NULL.");
629         }
630         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
631         {
632                 LOG_FATAL("TeamBalance_FindBestTeam: "
633                         "Team balance entity is not initialized.");
634         }
635         // count how many players are in each team
636         if (ignore_player)
637         {
638                 TeamBalance_GetTeamCounts(balance, player);
639         }
640         else
641         {
642                 TeamBalance_GetTeamCounts(balance, NULL);
643         }
644         int team_bits = TeamBalance_FindBestTeams(balance, player, true);
645         if (team_bits == 0)
646         {
647                 LOG_FATALF("TeamBalance_FindBestTeam: No teams available for %s\n",
648                         MapInfo_Type_ToString(MapInfo_CurrentGametype()));
649         }
650         RandomSelection_Init();
651         for (int i = 1; i <= NUM_TEAMS; ++i)
652         {
653                 if (team_bits & Team_IndexToBit(i))
654                 {
655                         RandomSelection_AddFloat(i, 1, 1);
656                 }
657         }
658         return RandomSelection_chosen_float;
659 }
660
661 int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
662 {
663         if (balance == NULL)
664         {
665                 LOG_FATAL("TeamBalance_FindBestTeams: Team balance entity is NULL.");
666         }
667         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
668         {
669                 LOG_FATAL("TeamBalance_FindBestTeams: "
670                         "TeamBalance_GetTeamCounts has not been called.");
671         }
672         if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
673         {
674                 return M_ARGV(1, float);
675         }
676         int team_bits = 0;
677         int previous_team = 0;
678         for (int i = 1; i <= NUM_TEAMS; ++i)
679         {
680                 if (!TeamBalance_IsTeamAllowedInternal(balance, i))
681                 {
682                         continue;
683                 }
684                 if (previous_team == 0)
685                 {
686                         team_bits = Team_IndexToBit(i);
687                         previous_team = i;
688                         continue;
689                 }
690                 int compare = TeamBalance_CompareTeams(balance, i, previous_team,
691                         player, use_score);
692                 if (compare == TEAMS_COMPARE_LESS)
693                 {
694                         team_bits = Team_IndexToBit(i);
695                         previous_team = i;
696                         continue;
697                 }
698                 if (compare == TEAMS_COMPARE_EQUAL)
699                 {
700                         team_bits |= Team_IndexToBit(i);
701                         previous_team = i;
702                 }
703         }
704         return team_bits;
705 }
706
707 void TeamBalance_JoinBestTeam(entity this, bool force_best_team)
708 {
709         // don't join a team if we're not playing a team game
710         if (!teamplay)
711         {
712                 return;
713         }
714
715         // find out what teams are available
716         entity balance = TeamBalance_CheckAllowedTeams(this);
717
718         // if we don't care what team they end up on, put them on whatever team they entered as.
719         // if they're not on a valid team, then let other code put them on the smallest team
720         if (!force_best_team)
721         {
722                 int selected_team_index = -1;
723                 for (int i = 1; i <= NUM_TEAMS; ++i)
724                 {
725                         if (TeamBalance_IsTeamAllowedInternal(balance, i) &&
726                                 (Team_TeamToIndex(this.team) == i))
727                         {
728                                 selected_team_index = i;
729                                 break;
730                         }
731                 }
732                 
733                 if (Team_IsValidIndex(selected_team_index))
734                 {
735                         Player_SetTeamIndex(this, selected_team_index);
736                         LogTeamchange(this.playerid, this.team, 99);
737                         TeamBalance_Destroy(balance);
738                         return;
739                 }
740         }
741         // otherwise end up on the smallest team (handled below)
742         if (this.bot_forced_team)
743         {
744                 TeamBalance_Destroy(balance);
745                 return;
746         }
747         int best_team_index = TeamBalance_FindBestTeam(balance, this, true);
748         int old_team_index = Team_TeamToIndex(this.team);
749         TeamchangeFrags(this);
750         Player_SetTeamIndex(this, best_team_index);
751         LogTeamchange(this.playerid, this.team, 2); // log auto join
752         if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
753         {
754                 TeamBalance_AutoBalanceBots(balance, old_team_index, best_team_index);
755         }
756         KillPlayerForTeamChange(this);
757         TeamBalance_Destroy(balance);
758 }
759
760 int TeamBalance_CompareTeams(entity balance, int team_index_a, int team_index_b,
761         entity player, bool use_score)
762 {
763         if (balance == NULL)
764         {
765                 LOG_FATAL("TeamBalance_CompareTeams: Team balance entity is NULL.");
766         }
767         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
768         {
769                 LOG_FATAL("TeamBalance_CompareTeams: "
770                         "TeamBalance_GetTeamCounts has not been called.");
771         }
772         if (!Team_IsValidIndex(team_index_a))
773         {
774                 LOG_FATALF("TeamBalance_CompareTeams: team_index_a is invalid: %f",
775                         team_index_a);
776         }
777         if (!Team_IsValidIndex(team_index_b))
778         {
779                 LOG_FATALF("TeamBalance_CompareTeams: team_index_b is invalid: %f",
780                         team_index_b);
781         }
782         if (team_index_a == team_index_b)
783         {
784                 return TEAMS_COMPARE_EQUAL;
785         }
786         entity team_a = TeamBalance_GetTeamFromIndex(balance, team_index_a);
787         entity team_b = TeamBalance_GetTeamFromIndex(balance, team_index_b);
788         return TeamBalance_CompareTeamsInternal(team_a, team_b, player, use_score);
789 }
790
791 void TeamBalance_AutoBalanceBots(entity balance, int source_team_index,
792         int destination_team_index)
793 {
794         if (balance == NULL)
795         {
796                 LOG_FATAL("TeamBalance_AutoBalanceBots: Team balance entity is NULL.");
797         }
798         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
799         {
800                 LOG_FATAL("TeamBalance_AutoBalanceBots: "
801                         "TeamBalance_GetTeamCounts has not been called.");
802         }
803         if (!Team_IsValidIndex(source_team_index))
804         {
805                 LOG_WARNF("AutoBalanceBots: Source team index is invalid: %f",
806                         source_team_index);
807                 return;
808         }
809         if (!Team_IsValidIndex(destination_team_index))
810         {
811                 LOG_WARNF("AutoBalanceBots: Destination team index is invalid: %f",
812                         destination_team_index);
813                 return;
814         }
815         if (!autocvar_g_balance_teams ||
816                 !autocvar_g_balance_teams_prevent_imbalance)
817         {
818                 return;
819         }
820         entity source_team = TeamBalance_GetTeamFromIndex(balance,
821                 source_team_index);
822         if (!TeamBalanceTeam_IsAllowed(source_team))
823         {
824                 return;
825         }
826         entity destination_team = TeamBalance_GetTeamFromIndex(balance,
827                 destination_team_index);
828         if ((destination_team.m_num_players <= source_team.m_num_players) ||
829                 (destination_team.m_lowest_bot == NULL))
830         {
831                 return;
832         }
833         Player_SetTeamIndex(destination_team.m_lowest_bot, source_team_index);
834         KillPlayerForTeamChange(destination_team.m_lowest_bot);
835 }
836
837 bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
838 {
839         return balance.m_team_balance_team[index - 1].m_num_players !=
840                 TEAM_NOT_ALLOWED;
841 }
842
843 void TeamBalance_BanTeamsExcept(entity balance, int index)
844 {
845         for (int i = 1; i <= NUM_TEAMS; ++i)
846         {
847                 if (i != index)
848                 {
849                         balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
850                 }
851         }
852 }
853
854 entity TeamBalance_GetTeamFromIndex(entity balance, int index)
855 {
856         if (!Team_IsValidIndex(index))
857         {
858                 LOG_FATALF("TeamBalance_GetTeamFromIndex: Index is invalid: %f", index);
859         }
860         return balance.m_team_balance_team[index - 1];
861 }
862
863 entity TeamBalance_GetTeam(entity balance, int team_num)
864 {
865         return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
866 }
867
868 bool TeamBalanceTeam_IsAllowed(entity team_)
869 {
870         return team_.m_num_players != TEAM_NOT_ALLOWED;
871 }
872
873 int TeamBalanceTeam_GetNumberOfPlayers(entity team_)
874 {
875         return team_.m_num_players;
876 }
877
878 int TeamBalanceTeam_GetNumberOfBots(entity team_)
879 {
880         return team_.m_num_bots;
881 }
882
883 entity TeamBalanceTeam_GetLowestHuman(entity team_)
884 {
885         return team_.m_lowest_human;
886 }
887
888 entity TeamBalanceTeam_GetLowestBot(entity team_)
889 {
890         return team_.m_lowest_bot;
891 }
892
893 int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b,
894         entity player, bool use_score)
895 {
896         if (team_a == team_b)
897         {
898                 return TEAMS_COMPARE_EQUAL;
899         }
900         if (!TeamBalanceTeam_IsAllowed(team_a) ||
901                 !TeamBalanceTeam_IsAllowed(team_b))
902         {
903                 return TEAMS_COMPARE_INVALID;
904         }
905         int num_players_team_a = team_a.m_num_players;
906         int num_players_team_b = team_b.m_num_players;
907         if (IS_REAL_CLIENT(player) && bots_would_leave)
908         {
909                 num_players_team_a -= team_a.m_num_bots;
910                 num_players_team_b -= team_b.m_num_bots;
911         }
912         if (num_players_team_a < num_players_team_b)
913         {
914                 return TEAMS_COMPARE_LESS;
915         }
916         if (num_players_team_a > num_players_team_b)
917         {
918                 return TEAMS_COMPARE_GREATER;
919         }
920         if (!use_score)
921         {
922                 return TEAMS_COMPARE_EQUAL;
923         }
924         if (team_a.m_team_score < team_b.m_team_score)
925         {
926                 return TEAMS_COMPARE_LESS;
927         }
928         if (team_a.m_team_score > team_b.m_team_score)
929         {
930                 return TEAMS_COMPARE_GREATER;
931         }
932         return TEAMS_COMPARE_EQUAL;
933 }
934
935 void SV_ChangeTeam(entity this, float _color)
936 {
937         int source_color, destination_color;
938         int source_team_index, destination_team_index;
939
940         // in normal deathmatch we can just apply the color and we're done
941         if(!teamplay)
942                 SetPlayerColors(this, _color);
943
944         if(!IS_CLIENT(this))
945         {
946                 // since this is an engine function, and gamecode doesn't have any calls earlier than this, do the connecting message here
947                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CONNECTING, this.netname);
948                 return;
949         }
950
951         if(!teamplay)
952                 return;
953
954         source_color = this.clientcolors & 0x0F;
955         destination_color = _color & 0x0F;
956
957         source_team_index = Team_TeamToIndex(source_color + 1);
958         destination_team_index = Team_TeamToIndex(destination_color + 1);
959
960         if (destination_team_index == -1)
961         {
962                 return;
963         }
964
965         entity balance = TeamBalance_CheckAllowedTeams(this);
966
967         if (destination_team_index == 1 && !TeamBalance_IsTeamAllowedInternal(
968                 balance, 1))
969         {
970                 destination_team_index = 4;
971         }
972         if (destination_team_index == 4 && !TeamBalance_IsTeamAllowedInternal(
973                 balance, 4))
974         {
975                 destination_team_index = 3;
976         }
977         if (destination_team_index == 3 && !TeamBalance_IsTeamAllowedInternal(
978                 balance, 3))
979         {
980                 destination_team_index = 2;
981         }
982         if (destination_team_index == 2 && !TeamBalance_IsTeamAllowedInternal(
983                 balance, 2))
984         {
985                 destination_team_index = 1;
986         }
987
988         // not changing teams
989         if (source_color == destination_color)
990         {
991                 SetPlayerTeam(this, destination_team_index, source_team_index, true);
992                 TeamBalance_Destroy(balance);
993                 return;
994         }
995
996         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && CS(this).wasplayer)) {
997                 Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
998                 return; // changing teams is not allowed
999         }
1000
1001         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
1002         if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
1003         {
1004                 TeamBalance_GetTeamCounts(balance, this);
1005                 if ((Team_IndexToBit(destination_team_index) &
1006                         TeamBalance_FindBestTeams(balance, this, false)) == 0)
1007                 {
1008                         Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
1009                         TeamBalance_Destroy(balance);
1010                         return;
1011                 }
1012         }
1013         if (IS_PLAYER(this) && source_team_index != destination_team_index)
1014         {
1015                 // reduce frags during a team change
1016                 TeamchangeFrags(this);
1017         }
1018         if (!SetPlayerTeam(this, destination_team_index, source_team_index,
1019                 !IS_CLIENT(this)))
1020         {
1021                 TeamBalance_Destroy(balance);
1022                 return;
1023         }
1024         TeamBalance_AutoBalanceBots(balance, source_team_index,
1025                 destination_team_index);
1026         if (!IS_PLAYER(this) || (source_team_index == destination_team_index))
1027         {
1028                 TeamBalance_Destroy(balance);
1029                 return;
1030         }
1031         KillPlayerForTeamChange(this);
1032         TeamBalance_Destroy(balance);
1033 }