]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/teamplay.qc
New design for bot autobalance.
[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 void TeamchangeFrags(entity e)
19 {
20         PlayerScore_Clear(e);
21 }
22
23 void LogTeamchange(float player_id, float team_number, float type)
24 {
25         if(!autocvar_sv_eventlog)
26                 return;
27
28         if(player_id < 1)
29                 return;
30
31         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
32 }
33
34 void default_delayedinit(entity this)
35 {
36         if(!scores_initialized)
37                 ScoreRules_generic();
38 }
39
40 void ActivateTeamplay()
41 {
42         serverflags |= SERVERFLAG_TEAMPLAY;
43         teamplay = 1;
44         cvar_set("teamplay", "2");  // DP needs this for sending proper getstatus replies.
45 }
46
47 void InitGameplayMode()
48 {
49         VoteReset();
50
51         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
52         get_mi_min_max(1);
53         world.mins = mi_min;
54         world.maxs = mi_max;
55         // currently, NetRadiant's limit is 131072 qu for each side
56         // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
57         // set the distance according to map size but don't go over the limit to avoid issues with float precision
58         // in case somebody makes extremely large maps
59         max_shot_distance = min(230000, vlen(world.maxs - world.mins));
60
61         MapInfo_LoadMapSettings(mapname);
62         serverflags &= ~SERVERFLAG_TEAMPLAY;
63         teamplay = 0;
64         cvar_set("teamplay", "0");  // DP needs this for sending proper getstatus replies.
65
66         if (!cvar_value_issafe(world.fog))
67         {
68                 LOG_INFO("The current map contains a potentially harmful fog setting, ignored\n");
69                 world.fog = string_null;
70         }
71         if(MapInfo_Map_fog != "")
72                 if(MapInfo_Map_fog == "none")
73                         world.fog = string_null;
74                 else
75                         world.fog = strzone(MapInfo_Map_fog);
76         clientstuff = strzone(MapInfo_Map_clientstuff);
77
78         MapInfo_ClearTemps();
79
80         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
81
82         cache_mutatormsg = strzone("");
83         cache_lastmutatormsg = strzone("");
84
85         InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
86 }
87
88 string GetClientVersionMessage(entity this)
89 {
90         if (this.version_mismatch) {
91                 if(this.version < autocvar_gameversion) {
92                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
93                                 "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8");
94                 } else {
95                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
96                                 "\n^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8");
97                 }
98         } else {
99                 return strcat("Welcome to Xonotic ", autocvar_g_xonoticversion);
100         }
101 }
102
103 string getwelcomemessage(entity this)
104 {
105         MUTATOR_CALLHOOK(BuildMutatorsPrettyString, "");
106         string modifications = M_ARGV(0, string);
107
108         if(g_weaponarena)
109         {
110                 if(g_weaponarena_random)
111                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
112                 else
113                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
114         }
115         else if(cvar("g_balance_blaster_weaponstartoverride") == 0)
116                 modifications = strcat(modifications, ", No start weapons");
117         if(cvar("sv_gravity") < stof(cvar_defstring("sv_gravity")))
118                 modifications = strcat(modifications, ", Low gravity");
119         if(g_weapon_stay && !g_cts)
120                 modifications = strcat(modifications, ", Weapons stay");
121         if(g_jetpack)
122                 modifications = strcat(modifications, ", Jet pack");
123         if(autocvar_g_powerups == 0)
124                 modifications = strcat(modifications, ", No powerups");
125         if(autocvar_g_powerups > 0)
126                 modifications = strcat(modifications, ", Powerups");
127         modifications = substring(modifications, 2, strlen(modifications) - 2);
128
129         string versionmessage = GetClientVersionMessage(this);
130         string s = strcat(versionmessage, "^8\n^8\nmatch type is ^1", gamemode_name, "^8\n");
131
132         if(modifications != "")
133                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
134
135         if(cache_lastmutatormsg != autocvar_g_mutatormsg)
136         {
137                 if(cache_lastmutatormsg)
138                         strunzone(cache_lastmutatormsg);
139                 if(cache_mutatormsg)
140                         strunzone(cache_mutatormsg);
141                 cache_lastmutatormsg = strzone(autocvar_g_mutatormsg);
142                 cache_mutatormsg = strzone(cache_lastmutatormsg);
143         }
144
145         if (cache_mutatormsg != "") {
146                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
147         }
148
149         string mutator_msg = "";
150         MUTATOR_CALLHOOK(BuildGameplayTipsString, mutator_msg);
151         mutator_msg = M_ARGV(0, string);
152
153         s = strcat(s, mutator_msg); // trust that the mutator will do proper formatting
154
155         string motd = autocvar_sv_motd;
156         if (motd != "") {
157                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
158         }
159         return s;
160 }
161
162 void setcolor(entity this, int clr)
163 {
164 #if 0
165         this.clientcolors = clr;
166         this.team = (clr & 15) + 1;
167 #else
168         builtin_setcolor(this, clr);
169 #endif
170 }
171
172 void SetPlayerColors(entity player, float _color)
173 {
174         float pants = _color & 0x0F;
175         float shirt = _color & 0xF0;
176         if (teamplay)
177         {
178                 setcolor(player, 16 * pants + pants);
179         }
180         else
181         {
182                 setcolor(player, shirt + pants);
183         }
184 }
185
186 bool SetPlayerTeamSimple(entity player, int teamnum)
187 {
188         if (player.team == teamnum)
189         {
190                 // This is important when players join the game and one of their color
191                 // matches the team color while other doesn't. For example [BOT]Lion.
192                 SetPlayerColors(player, teamnum - 1);
193                 return true;
194         }
195         if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, Team_TeamToNumber(
196                 player.team), Team_TeamToNumber(teamnum)) == true)
197         {
198                 // Mutator has blocked team change.
199                 return false;
200         }
201         int oldteam = player.team;
202         SetPlayerColors(player, teamnum - 1);
203         MUTATOR_CALLHOOK(Player_ChangedTeam, player, oldteam, player.team);
204         return true;
205 }
206
207 void SetPlayerTeam(entity player, int destinationteam, int sourceteam, bool noprint)
208 {
209         int teamnum = Team_NumberToTeam(destinationteam);
210         if (!SetPlayerTeamSimple(player, teamnum))
211         {
212                 return;
213         }
214         LogTeamchange(player.playerid, player.team, 3);  // log manual team join
215         if (noprint)
216         {
217                 return;
218         }
219         bprint(playername(player, false), "^7 has changed from ", Team_NumberToColoredFullName(sourceteam), "^7 to ", Team_NumberToColoredFullName(destinationteam), "\n");
220 }
221
222 // set c1...c4 to show what teams are allowed
223 void CheckAllowedTeams (entity for_whom)
224 {
225         int teams_mask = 0;
226
227         c1 = c2 = c3 = c4 = -1;
228         numbotsteam1 = numbotsteam2 = numbotsteam3 = numbotsteam4 = 0;
229
230         string teament_name = string_null;
231
232         bool mutator_returnvalue = MUTATOR_CALLHOOK(CheckAllowedTeams, teams_mask, teament_name, for_whom);
233         teams_mask = M_ARGV(0, float);
234         teament_name = M_ARGV(1, string);
235
236         if(!mutator_returnvalue)
237         {
238                 if(teams_mask & BIT(0)) c1 = 0;
239                 if(teams_mask & BIT(1)) c2 = 0;
240                 if(teams_mask & BIT(2)) c3 = 0;
241                 if(teams_mask & BIT(3)) c4 = 0;
242         }
243
244         // find out what teams are allowed if necessary
245         if(teament_name)
246         {
247                 entity head = find(NULL, classname, teament_name);
248                 while(head)
249                 {
250                         switch(head.team)
251                         {
252                                 case NUM_TEAM_1: c1 = 0; break;
253                                 case NUM_TEAM_2: c2 = 0; break;
254                                 case NUM_TEAM_3: c3 = 0; break;
255                                 case NUM_TEAM_4: c4 = 0; break;
256                         }
257
258                         head = find(head, classname, teament_name);
259                 }
260         }
261
262         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
263         if(AvailableTeams() == 2)
264         if(autocvar_bot_vs_human && for_whom)
265         {
266                 if(autocvar_bot_vs_human > 0)
267                 {
268                         // find last team available
269
270                         if(IS_BOT_CLIENT(for_whom))
271                         {
272                                 if(c4 >= 0) { c3 = c2 = c1 = -1; }
273                                 else if(c3 >= 0) { c4 = c2 = c1 = -1; }
274                                 else { c4 = c3 = c1 = -1; }
275                                 // no further cases, we know at least 2 teams exist
276                         }
277                         else
278                         {
279                                 if(c1 >= 0) { c2 = c3 = c4 = -1; }
280                                 else if(c2 >= 0) { c1 = c3 = c4 = -1; }
281                                 else { c1 = c2 = c4 = -1; }
282                                 // no further cases, bots have one of the teams
283                         }
284                 }
285                 else
286                 {
287                         // find first team available
288
289                         if(IS_BOT_CLIENT(for_whom))
290                         {
291                                 if(c1 >= 0) { c2 = c3 = c4 = -1; }
292                                 else if(c2 >= 0) { c1 = c3 = c4 = -1; }
293                                 else { c1 = c2 = c4 = -1; }
294                                 // no further cases, we know at least 2 teams exist
295                         }
296                         else
297                         {
298                                 if(c4 >= 0) { c3 = c2 = c1 = -1; }
299                                 else if(c3 >= 0) { c4 = c2 = c1 = -1; }
300                                 else { c4 = c3 = c1 = -1; }
301                                 // no further cases, bots have one of the teams
302                         }
303                 }
304         }
305
306         if(!for_whom)
307                 return;
308
309         // if player has a forced team, ONLY allow that one
310         if(for_whom.team_forced == NUM_TEAM_1 && c1 >= 0)
311                 c2 = c3 = c4 = -1;
312         else if(for_whom.team_forced == NUM_TEAM_2 && c2 >= 0)
313                 c1 = c3 = c4 = -1;
314         else if(for_whom.team_forced == NUM_TEAM_3 && c3 >= 0)
315                 c1 = c2 = c4 = -1;
316         else if(for_whom.team_forced == NUM_TEAM_4 && c4 >= 0)
317                 c1 = c2 = c3 = -1;
318 }
319
320 float PlayerValue(entity p)
321 {
322         return 1;
323         // FIXME: it always returns 1...
324 }
325
326 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
327 // teams that are allowed will now have their player counts stored in c1...c4
328 void GetTeamCounts(entity ignore)
329 {
330         if (MUTATOR_CALLHOOK(GetTeamCounts) == true)
331         {
332                 if (c1 >= 0)
333                 {
334                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_1, ignore, c1, numbotsteam1,
335                                 lowestplayerteam1, lowestbotteam1);
336                         c1 = M_ARGV(2, float);
337                         numbotsteam1 = M_ARGV(3, float);
338                         lowestplayerteam1 = M_ARGV(4, entity);
339                         lowestbotteam1 = M_ARGV(5, entity);
340                 }
341                 if (c2 >= 0)
342                 {
343                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_2, ignore, c2, numbotsteam2,
344                                 lowestplayerteam2, lowestbotteam2);
345                         c2 = M_ARGV(2, float);
346                         numbotsteam2 = M_ARGV(3, float);
347                         lowestplayerteam2 = M_ARGV(4, entity);
348                         lowestbotteam2 = M_ARGV(5, entity);
349                 }
350                 if (c3 >= 0)
351                 {
352                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_3, ignore, c3, numbotsteam3,
353                                 lowestplayerteam3, lowestbotteam3);
354                         c3 = M_ARGV(2, float);
355                         numbotsteam3 = M_ARGV(3, float);
356                         lowestplayerteam3 = M_ARGV(4, entity);
357                         lowestbotteam3 = M_ARGV(5, entity);
358                 }
359                 if (c4 >= 0)
360                 {
361                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_4, ignore, c4, numbotsteam4,
362                                 lowestplayerteam4, lowestbotteam4);
363                         c4 = M_ARGV(2, float);
364                         numbotsteam4 = M_ARGV(3, float);
365                         lowestplayerteam4 = M_ARGV(4, entity);
366                         lowestbotteam4 = M_ARGV(5, entity);
367                 }
368         }
369         else
370         {
371                 float value, bvalue;
372                 // now count how many players are on each team already
373                 float lowestplayerscore1 = FLOAT_MAX;
374                 float lowestbotscore1 = FLOAT_MAX;
375                 float lowestplayerscore2 = FLOAT_MAX;
376                 float lowestbotscore2 = FLOAT_MAX;
377                 float lowestplayerscore3 = FLOAT_MAX;
378                 float lowestbotscore3 = FLOAT_MAX;
379                 float lowestplayerscore4 = FLOAT_MAX;
380                 float lowestbotscore4 = FLOAT_MAX;
381                 FOREACH_CLIENT(true, LAMBDA(
382                         float t;
383                         if (IS_PLAYER(it) || it.caplayer)
384                         {
385                                 t = it.team;
386                         }
387                         else if (it.team_forced > 0)
388                         {
389                                 t = it.team_forced; // reserve the spot
390                         }
391                         else
392                         {
393                                 continue;
394                         }
395                         if (it == ignore)
396                         {
397                                 continue;
398                         }
399                         value = PlayerValue(it);
400                         if (IS_BOT_CLIENT(it))
401                         {
402                                 bvalue = value;
403                         }
404                         else
405                         {
406                                 bvalue = 0;
407                         }
408                         if (value == 0)
409                         {
410                                 continue;
411                         }
412                         switch (t)
413                         {
414                                 case NUM_TEAM_1:
415                                 {
416                                         if (c1 < 0)
417                                         {
418                                                 break;
419                                         }
420                                         c1 += value;
421                                         numbotsteam1 += bvalue;
422                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
423                                         if (!bvalue)
424                                         {
425                                                 if (tempscore < lowestplayerscore1)
426                                                 {
427                                                         lowestplayerteam1 = it;
428                                                         lowestplayerscore1 = tempscore;
429                                                 }
430                                                 break;
431                                         }
432                                         if (tempscore < lowestbotscore1)
433                                         {
434                                                 lowestbotteam1 = it;
435                                                 lowestbotscore1 = tempscore;
436                                         }
437                                         break;
438                                 }
439                                 case NUM_TEAM_2:
440                                 {
441                                         if (c2 < 0)
442                                         {
443                                                 break;
444                                         }
445                                         c2 += value;
446                                         numbotsteam2 += bvalue;
447                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
448                                         if (!bvalue)
449                                         {
450                                                 if (tempscore < lowestplayerscore2)
451                                                 {
452                                                         lowestplayerteam2 = it;
453                                                         lowestplayerscore2 = tempscore;
454                                                 }
455                                                 break;
456                                         }
457                                         if (tempscore < lowestbotscore2)
458                                         {
459                                                 lowestbotteam2 = it;
460                                                 lowestbotscore2 = tempscore;
461                                         }
462                                         break;
463                                 }
464                                 case NUM_TEAM_3:
465                                 {
466                                         if (c3 < 0)
467                                         {
468                                                 break;
469                                         }
470                                         c3 += value;
471                                         numbotsteam3 += bvalue;
472                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
473                                         if (!bvalue)
474                                         {
475                                                 if (tempscore < lowestplayerscore3)
476                                                 {
477                                                         lowestplayerteam3 = it;
478                                                         lowestplayerscore3 = tempscore;
479                                                 }
480                                                 break;
481                                         }
482                                         if (tempscore < lowestbotscore3)
483                                         {
484                                                 lowestbotteam3 = it;
485                                                 lowestbotscore3 = tempscore;
486                                         }
487                                         break;
488                                 }
489                                 case NUM_TEAM_4:
490                                 {
491                                         if (c4 < 0)
492                                         {
493                                                 break;
494                                         }
495                                         c4 += value;
496                                         numbotsteam4 += bvalue;
497                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
498                                         if (!bvalue)
499                                         {
500                                                 if (tempscore < lowestplayerscore4)
501                                                 {
502                                                         lowestplayerteam4 = it;
503                                                         lowestplayerscore4 = tempscore;
504                                                 }
505                                                 break;
506                                         }
507                                         if (tempscore < lowestbotscore4)
508                                         {
509                                                 lowestbotteam4 = it;
510                                                 lowestbotscore4 = tempscore;
511                                         }
512                                         break;
513                                 }
514                         }
515                 ));
516         }
517
518         // if the player who has a forced team has not joined yet, reserve the spot
519         if(autocvar_g_campaign)
520         {
521                 switch(autocvar_g_campaign_forceteam)
522                 {
523                         case 1: if(c1 == numbotsteam1) ++c1; break;
524                         case 2: if(c2 == numbotsteam2) ++c2; break;
525                         case 3: if(c3 == numbotsteam3) ++c3; break;
526                         case 4: if(c4 == numbotsteam4) ++c4; break;
527                 }
528         }
529 }
530
531 float TeamSmallerEqThanTeam(int teama, int teamb, entity e, bool usescore)
532 {
533         // equal
534         if (teama == teamb)
535         {
536                 return true;
537         }
538         // we assume that CheckAllowedTeams and GetTeamCounts have already been called
539         float numplayersteama = -1, numplayersteamb = -1;
540         float numbotsteama = 0, numbotsteamb = 0;
541         float scoreteama = 0, scoreteamb = 0;
542
543         switch (teama)
544         {
545                 case 1: numplayersteama = c1; numbotsteama = numbotsteam1; scoreteama = team1_score; break;
546                 case 2: numplayersteama = c2; numbotsteama = numbotsteam2; scoreteama = team2_score; break;
547                 case 3: numplayersteama = c3; numbotsteama = numbotsteam3; scoreteama = team3_score; break;
548                 case 4: numplayersteama = c4; numbotsteama = numbotsteam4; scoreteama = team4_score; break;
549         }
550         switch (teamb)
551         {
552                 case 1: numplayersteamb = c1; numbotsteamb = numbotsteam1; scoreteamb = team1_score; break;
553                 case 2: numplayersteamb = c2; numbotsteamb = numbotsteam2; scoreteamb = team2_score; break;
554                 case 3: numplayersteamb = c3; numbotsteamb = numbotsteam3; scoreteamb = team3_score; break;
555                 case 4: numplayersteamb = c4; numbotsteamb = numbotsteam4; scoreteamb = team4_score; break;
556         }
557
558         // invalid
559         if (numplayersteama < 0 || numplayersteamb < 0)
560                 return false;
561
562         if ((IS_REAL_CLIENT(e) && bots_would_leave))
563         {
564                 numplayersteama -= numbotsteama;
565                 numplayersteamb -= numbotsteamb;
566         }
567         if (!usescore)
568         {
569                 return numplayersteama <= numplayersteamb;
570         }
571         if (numplayersteama < numplayersteamb)
572         {
573                 return true;
574         }
575         if (numplayersteama > numplayersteamb)
576         {
577                 return false;
578         }
579         return scoreteama <= scoreteamb;
580
581         // first, normalize
582         //f = max(numplayersteama, numplayersteamb, 1);
583         //numplayersteama /= f;
584         //numplayersteamb /= f;
585
586         //float f = max(scoreteama, scoreteamb, 1);
587         //scoreteama /= f;
588         //scoreteamb /= f;
589
590         // the more we're at the end of the match, the more take scores into account
591         //f = bound(0, game_completion_ratio * autocvar_g_balance_teams_scorefactor, 1);
592         //numplayersteama += (scoreteama - numplayersteama) * f;
593         //numplayersteamb += (scoreteamb - numplayersteamb) * f;        
594 }
595
596 // returns # of smallest team (1, 2, 3, 4)
597 // NOTE: Assumes CheckAllowedTeams has already been called!
598 float FindSmallestTeam(entity pl, float ignore_pl)
599 {
600         int totalteams = 0;
601         int t = 1; // initialize with a random team?
602         if(c4 >= 0) t = 4;
603         if(c3 >= 0) t = 3;
604         if(c2 >= 0) t = 2;
605         if(c1 >= 0) t = 1;
606
607         // find out what teams are available
608         //CheckAllowedTeams();
609
610         // make sure there are at least 2 teams to join
611         if(c1 >= 0)
612                 totalteams = totalteams + 1;
613         if(c2 >= 0)
614                 totalteams = totalteams + 1;
615         if(c3 >= 0)
616                 totalteams = totalteams + 1;
617         if(c4 >= 0)
618                 totalteams = totalteams + 1;
619
620         if((autocvar_bot_vs_human || pl.team_forced > 0) && totalteams == 1)
621                 totalteams += 1;
622
623         if(totalteams <= 1)
624         {
625                 if(autocvar_g_campaign && pl && IS_REAL_CLIENT(pl))
626                         return 1; // special case for campaign and player joining
627                 else if(totalteams == 1) // single team
628                         LOG_TRACEF("Only 1 team available for %s, you may need to fix your map", MapInfo_Type_ToString(MapInfo_CurrentGametype()));
629                 else // no teams, major no no
630                         error(sprintf("No teams available for %s\n", MapInfo_Type_ToString(MapInfo_CurrentGametype())));
631         }
632
633         // count how many players are in each team
634         if(ignore_pl)
635                 GetTeamCounts(pl);
636         else
637                 GetTeamCounts(NULL);
638
639         RandomSelection_Init();
640
641         if(TeamSmallerEqThanTeam(1, t, pl, true))
642                 t = 1;
643         if(TeamSmallerEqThanTeam(2, t, pl, true))
644                 t = 2;
645         if(TeamSmallerEqThanTeam(3, t, pl, true))
646                 t = 3;
647         if(TeamSmallerEqThanTeam(4, t, pl, true))
648                 t = 4;
649
650         // now t is the minimum, or A minimum!
651         if(t == 1 || TeamSmallerEqThanTeam(1, t, pl, true))
652                 RandomSelection_AddFloat(1, 1, 1);
653         if(t == 2 || TeamSmallerEqThanTeam(2, t, pl, true))
654                 RandomSelection_AddFloat(2, 1, 1);
655         if(t == 3 || TeamSmallerEqThanTeam(3, t, pl, true))
656                 RandomSelection_AddFloat(3, 1, 1);
657         if(t == 4 || TeamSmallerEqThanTeam(4, t, pl, true))
658                 RandomSelection_AddFloat(4, 1, 1);
659
660         return RandomSelection_chosen_float;
661 }
662
663 int JoinBestTeam(entity this, bool only_return_best, bool forcebestteam)
664 {
665         // don't join a team if we're not playing a team game
666         if (!teamplay)
667         {
668                 return 0;
669         }
670
671         // find out what teams are available
672         CheckAllowedTeams(this);
673
674         float selectedteam;
675
676         // if we don't care what team he ends up on, put him on whatever team he entered as.
677         // if he's not on a valid team, then let other code put him on the smallest team
678         if (!forcebestteam)
679         {
680                 if(     c1 >= 0 && this.team == NUM_TEAM_1)
681                         selectedteam = this.team;
682                 else if(c2 >= 0 && this.team == NUM_TEAM_2)
683                         selectedteam = this.team;
684                 else if(c3 >= 0 && this.team == NUM_TEAM_3)
685                         selectedteam = this.team;
686                 else if(c4 >= 0 && this.team == NUM_TEAM_4)
687                         selectedteam = this.team;
688                 else
689                         selectedteam = -1;
690
691                 if (selectedteam > 0)
692                 {
693                         if (!only_return_best)
694                         {
695                                 SetPlayerTeamSimple(this, selectedteam);
696
697                                 // when JoinBestTeam is called by client.qc/ClientKill_Now_TeamChange the players team is -1 and thus skipped
698                                 // when JoinBestTeam is called by client.qc/ClientConnect the player_id is 0 the log attempt is rejected
699                                 LogTeamchange(this.playerid, this.team, 99);
700                         }
701                         return selectedteam;
702                 }
703                 // otherwise end up on the smallest team (handled below)
704         }
705
706         float bestteam = FindSmallestTeam(this, true);
707         MUTATOR_CALLHOOK(JoinBestTeam, this, bestteam);
708         bestteam = M_ARGV(1, float);
709
710         if (only_return_best || this.bot_forced_team)
711         {
712                 return bestteam;
713         }
714         bestteam = Team_NumberToTeam(bestteam);
715         if (bestteam == -1)
716         {
717                 error("JoinBestTeam: invalid team\n");
718         }
719         int oldteam = Team_TeamToNumber(this.team);
720         TeamchangeFrags(this);
721         SetPlayerTeamSimple(this, bestteam);
722         LogTeamchange(this.playerid, this.team, 2); // log auto join
723         if (!IS_BOT_CLIENT(this))
724         {
725                 AutoBalanceBots(oldteam, Team_TeamToNumber(bestteam));
726         }
727         if (!IS_DEAD(this) && (MUTATOR_CALLHOOK(Player_ChangeTeamKill, this) ==
728                 false))
729         {
730                 Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
731         }
732         return bestteam;
733 }
734
735 void SV_ChangeTeam(entity this, float _color)
736 {
737         float sourcecolor, destinationcolor, sourceteam, destinationteam;
738
739         // in normal deathmatch we can just apply the color and we're done
740         if(!teamplay)
741                 SetPlayerColors(this, _color);
742
743         if(!IS_CLIENT(this))
744         {
745                 // since this is an engine function, and gamecode doesn't have any calls earlier than this, do the connecting message here
746                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CONNECTING, this.netname);
747                 return;
748         }
749
750         if(!teamplay)
751                 return;
752
753         sourcecolor = this.clientcolors & 0x0F;
754         destinationcolor = _color & 0x0F;
755
756         sourceteam = Team_TeamToNumber(sourcecolor + 1);
757         destinationteam = Team_TeamToNumber(destinationcolor + 1);
758         
759         CheckAllowedTeams(this);
760
761         if (destinationteam == 1 && c1 < 0) destinationteam = 4;
762         if (destinationteam == 4 && c4 < 0) destinationteam = 3;
763         if (destinationteam == 3 && c3 < 0) destinationteam = 2;
764         if (destinationteam == 2 && c2 < 0) destinationteam = 1;
765
766         // not changing teams
767         if (sourcecolor == destinationcolor)
768         {
769                 SetPlayerTeam(this, destinationteam, sourceteam, true);
770                 return;
771         }
772
773         if (autocvar_g_campaign || (autocvar_g_changeteam_banned && this.wasplayer))
774         {
775                 Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
776                 return; // changing teams is not allowed
777         }
778
779         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
780         if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
781         {
782                 GetTeamCounts(this);
783                 if (!TeamSmallerEqThanTeam(destinationteam, sourceteam, this, false))
784                 {
785                         PrintToChatAll("TeamSmallerEqThanTeam prevented team switch.");
786                         Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
787                         return;
788                 }
789         }
790         if(IS_PLAYER(this) && sourceteam != destinationteam)
791         {
792                 // reduce frags during a team change
793                 TeamchangeFrags(this);
794         }
795         SetPlayerTeam(this, destinationteam, sourceteam, !IS_CLIENT(this));
796         AutoBalanceBots(sourceteam, destinationteam);
797         if (!IS_PLAYER(this) || (sourceteam == destinationteam))
798         {
799                 return;
800         }
801         // kill player when changing teams
802         if (IS_DEAD(this) || (MUTATOR_CALLHOOK(Player_ChangeTeamKill, this) == true))
803         {
804                 return;
805         }
806         Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
807 }
808
809 void AutoBalanceBots(int sourceteam, int destinationteam)
810 {
811         if ((sourceteam == -1) || (destinationteam == -1))
812         {
813                 return;
814         }
815         if (!autocvar_g_balance_teams ||
816                 !autocvar_g_balance_teams_prevent_imbalance)
817         {
818                 return;
819         }
820         int numplayerssourceteam = 0;
821         int numplayersdestinationteam = 0;
822         entity lowestbotdestinationteam = NULL;
823         switch (sourceteam)
824         {
825                 case 1:
826                 {
827                         numplayerssourceteam = c1;
828                         break;
829                 }
830                 case 2:
831                 {
832                         numplayerssourceteam = c2;
833                         break;
834                 }
835                 case 3:
836                 {
837                         numplayerssourceteam = c3;
838                         break;
839                 }
840                 case 4:
841                 {
842                         numplayerssourceteam = c4;
843                         break;
844                 }
845         }
846         switch (destinationteam)
847         {
848                 case 1:
849                 {
850                         numplayersdestinationteam = c1;
851                         lowestbotdestinationteam = lowestbotteam1;
852                         break;
853                 }
854                 case 2:
855                 {
856                         numplayersdestinationteam = c2;
857                         lowestbotdestinationteam = lowestbotteam2;
858                         break;
859                 }
860                 case 3:
861                 {
862                         numplayersdestinationteam = c3;
863                         lowestbotdestinationteam = lowestbotteam3;
864                         break;
865                 }
866                 case 4:
867                 {
868                         numplayersdestinationteam = c4;
869                         lowestbotdestinationteam = lowestbotteam4;
870                         break;
871                 }
872         }
873         if ((numplayersdestinationteam > numplayerssourceteam) && (lowestbotdestinationteam != NULL))
874         {
875                 SetPlayerTeamSimple(lowestbotdestinationteam, Team_NumberToTeam(sourceteam));
876         }
877 }
878
879 void ShufflePlayerOutOfTeam (float source_team)
880 {
881         float smallestteam, smallestteam_count, steam;
882         float lowest_bot_score, lowest_player_score;
883         entity lowest_bot, lowest_player, selected;
884
885         smallestteam = 0;
886         smallestteam_count = 999999999;
887
888         if(c1 >= 0 && c1 < smallestteam_count)
889         {
890                 smallestteam = 1;
891                 smallestteam_count = c1;
892         }
893         if(c2 >= 0 && c2 < smallestteam_count)
894         {
895                 smallestteam = 2;
896                 smallestteam_count = c2;
897         }
898         if(c3 >= 0 && c3 < smallestteam_count)
899         {
900                 smallestteam = 3;
901                 smallestteam_count = c3;
902         }
903         if(c4 >= 0 && c4 < smallestteam_count)
904         {
905                 smallestteam = 4;
906                 smallestteam_count = c4;
907         }
908
909         if(!smallestteam)
910         {
911                 bprint("warning: no smallest team\n");
912                 return;
913         }
914
915         if(source_team == 1)
916                 steam = NUM_TEAM_1;
917         else if(source_team == 2)
918                 steam = NUM_TEAM_2;
919         else if(source_team == 3)
920                 steam = NUM_TEAM_3;
921         else // if(source_team == 4)
922                 steam = NUM_TEAM_4;
923
924         lowest_bot = NULL;
925         lowest_bot_score = 999999999;
926         lowest_player = NULL;
927         lowest_player_score = 999999999;
928
929         // find the lowest-scoring player & bot of that team
930         FOREACH_CLIENT(IS_PLAYER(it) && it.team == steam, LAMBDA(
931                 if(it.isbot)
932                 {
933                         if(it.totalfrags < lowest_bot_score)
934                         {
935                                 lowest_bot = it;
936                                 lowest_bot_score = it.totalfrags;
937                         }
938                 }
939                 else
940                 {
941                         if(it.totalfrags < lowest_player_score)
942                         {
943                                 lowest_player = it;
944                                 lowest_player_score = it.totalfrags;
945                         }
946                 }
947         ));
948
949         // prefers to move a bot...
950         if(lowest_bot != NULL)
951                 selected = lowest_bot;
952         // but it will move a player if it has to
953         else
954                 selected = lowest_player;
955         // don't do anything if it couldn't find anyone
956         if(!selected)
957         {
958                 bprint("warning: couldn't find a player to move from team\n");
959                 return;
960         }
961
962         // smallest team gains a member
963         if(smallestteam == 1)
964         {
965                 c1 = c1 + 1;
966         }
967         else if(smallestteam == 2)
968         {
969                 c2 = c2 + 1;
970         }
971         else if(smallestteam == 3)
972         {
973                 c3 = c3 + 1;
974         }
975         else if(smallestteam == 4)
976         {
977                 c4 = c4 + 1;
978         }
979         else
980         {
981                 bprint("warning: destination team invalid\n");
982                 return;
983         }
984         // source team loses a member
985         if(source_team == 1)
986         {
987                 c1 = c1 + 1;
988         }
989         else if(source_team == 2)
990         {
991                 c2 = c2 + 2;
992         }
993         else if(source_team == 3)
994         {
995                 c3 = c3 + 3;
996         }
997         else if(source_team == 4)
998         {
999                 c4 = c4 + 4;
1000         }
1001         else
1002         {
1003                 bprint("warning: source team invalid\n");
1004                 return;
1005         }
1006
1007         // move the player to the new team
1008         TeamchangeFrags(selected);
1009         SetPlayerTeam(selected, smallestteam, source_team, false);
1010
1011         if (IS_DEAD(selected) || MUTATOR_CALLHOOK(Player_ChangeTeamKill, selected) == true)
1012         {
1013                 return;
1014         }
1015         Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE.m_id, selected.origin, '0 0 0');
1016         Send_Notification(NOTIF_ONE, selected, MSG_CENTER, CENTER_DEATH_SELF_AUTOTEAMCHANGE, selected.team);
1017 }