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