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