]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/teamplay.qc
Remove runematch gamemode
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / teamplay.qc
1 string cache_mutatormsg;
2 string cache_lastmutatormsg;
3
4 // client counts for each team
5 float c1, c2, c3, c4;
6 // # of bots on those teams
7 float cb1, cb2, cb3, cb4;
8
9 //float audit_teams_time;
10
11 void TeamchangeFrags(entity e)
12 {
13         PlayerScore_Clear(e);
14 }
15
16 vector TeamColor(float teem)
17 {
18         switch(teem)
19         {
20                 case COLOR_TEAM1:
21                         return '1 0.0625 0.0625';
22                 case COLOR_TEAM2:
23                         return '0.0625 0.0625 1';
24                 case COLOR_TEAM3:
25                         return '1 1 0.0625';
26                 case COLOR_TEAM4:
27                         return '1 0.0625 1';
28                 default:
29                         return '1 1 1';
30         }
31 }
32
33 string TeamName(float t)
34 {
35         return strcat(Team_ColorName(t), " Team");
36 }
37 string ColoredTeamName(float t)
38 {
39         return strcat(Team_ColorCode(t), Team_ColorName(t), " Team^7");
40 }
41 string TeamNoName(float t)
42 {
43         // fixme: Search for team entities and get their .netname's!
44         if(t == 1)
45                 return "Red Team";
46         if(t == 2)
47                 return "Blue Team";
48         if(t == 3)
49                 return "Yellow Team";
50         if(t == 4)
51                 return "Pink Team";
52         return "Neutral Team";
53 }
54
55 void tdm_init();
56 void entcs_init();
57
58 void LogTeamchange(float player_id, float team_number, float type)
59 {
60         if(!autocvar_sv_eventlog)
61                 return;
62
63         if(player_id < 1)
64                 return;
65
66         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
67 }
68
69 void default_delayedinit()
70 {
71         if(!scores_initialized)
72                 ScoreRules_generic();
73 }
74
75 void ActivateTeamplay()
76 {
77         serverflags |= SERVERFLAG_TEAMPLAY;
78         teamplay = 1;
79 }
80
81 void InitGameplayMode()
82 {
83         float fraglimit_override, timelimit_override, leadlimit_override, qualifying_override;
84
85         qualifying_override = -1;
86
87         VoteReset();
88
89         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
90         get_mi_min_max(1);
91         world.mins = mi_min;
92         world.maxs = mi_max;
93
94         MapInfo_LoadMapSettings(mapname);
95         teamplay = 0;
96         serverflags &~= SERVERFLAG_TEAMPLAY;
97
98         if not(cvar_value_issafe(world.fog))
99         {
100                 print("The current map contains a potentially harmful fog setting, ignored\n");
101                 world.fog = string_null;
102         }
103         if(MapInfo_Map_fog != "")
104                 if(MapInfo_Map_fog == "none")
105                         world.fog = string_null;
106                 else
107                         world.fog = strzone(MapInfo_Map_fog);
108         clientstuff = strzone(MapInfo_Map_clientstuff);
109
110         MapInfo_ClearTemps();
111
112         // set both here, gamemode can override it later
113         timelimit_override = autocvar_timelimit_override;
114         fraglimit_override = autocvar_fraglimit_override;
115         leadlimit_override = autocvar_leadlimit_override;
116         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
117
118         if(g_dm)
119         {
120         }
121
122         if(g_tdm)
123         {
124                 ActivateTeamplay();
125                 tdm_init();
126                 if(autocvar_g_tdm_team_spawns)
127                         have_team_spawns = -1; // request team spawns
128         }
129
130         if(g_domination)
131         {
132                 ActivateTeamplay();
133                 fraglimit_override = autocvar_g_domination_point_limit;
134                 leadlimit_override = autocvar_g_domination_point_leadlimit;
135                 MUTATOR_ADD(gamemode_domination);
136                 have_team_spawns = -1; // request team spawns
137         }
138
139         if(g_ctf)
140         {
141                 ActivateTeamplay();
142                 fraglimit_override = autocvar_capturelimit_override;
143                 leadlimit_override = autocvar_captureleadlimit_override;
144                 MUTATOR_ADD(gamemode_ctf);
145                 have_team_spawns = -1; // request team spawns
146         }
147
148         if(g_lms)
149         {
150                 fraglimit_override = autocvar_g_lms_lives_override;
151                 leadlimit_override = 0; // not supported by LMS
152                 if(fraglimit_override == 0)
153                         fraglimit_override = -1;
154                 lms_lowest_lives = 9999;
155                 lms_next_place = 0;
156                 ScoreRules_lms();
157         }
158
159         if(g_arena)
160         {
161                 fraglimit_override = autocvar_g_arena_point_limit;
162                 leadlimit_override = autocvar_g_arena_point_leadlimit;
163                 maxspawned = autocvar_g_arena_maxspawned;
164                 if(maxspawned < 2)
165                         maxspawned = 2;
166                 arena_roundbased = autocvar_g_arena_roundbased;
167         }
168
169         if(g_ca)
170         {
171                 ActivateTeamplay();
172                 fraglimit_override = autocvar_g_ca_point_limit;
173                 leadlimit_override = autocvar_g_ca_point_leadlimit;
174                 precache_sound("ctf/red_capture.wav");
175                 precache_sound("ctf/blue_capture.wav");
176         }
177         if(g_keyhunt)
178         {
179                 ActivateTeamplay();
180                 fraglimit_override = autocvar_g_keyhunt_point_limit;
181                 leadlimit_override = autocvar_g_keyhunt_point_leadlimit;
182                 MUTATOR_ADD(gamemode_keyhunt);
183         }
184
185         if(g_freezetag)
186         {
187                 ActivateTeamplay();
188                 fraglimit_override = autocvar_g_freezetag_point_limit;
189                 leadlimit_override = autocvar_g_freezetag_point_leadlimit;
190                 MUTATOR_ADD(gamemode_freezetag);
191         }
192
193         if(g_assault)
194         {
195                 ActivateTeamplay();
196                 ScoreRules_assault();
197                 have_team_spawns = -1; // request team spawns
198         }
199
200         if(g_onslaught)
201         {
202                 ActivateTeamplay();
203                 have_team_spawns = -1; // request team spawns
204                 MUTATOR_ADD(gamemode_onslaught);
205         }
206
207         if(g_race)
208         {
209
210                 if(autocvar_g_race_teams)
211                 {
212                         ActivateTeamplay();
213                         race_teams = bound(2, autocvar_g_race_teams, 4);
214                         have_team_spawns = -1; // request team spawns
215                 }
216                 else
217                         race_teams = 0;
218
219                 qualifying_override = autocvar_g_race_qualifying_timelimit_override;
220                 fraglimit_override = autocvar_g_race_laps_limit;
221                 leadlimit_override = 0; // currently not supported by race
222         }
223
224         if(g_cts)
225         {
226                 g_race_qualifying = 1;
227                 fraglimit_override = 0;
228                 leadlimit_override = 0;
229         }
230
231         if(g_nexball)
232         {
233         fraglimit_override = autocvar_g_nexball_goallimit;
234         leadlimit_override = autocvar_g_nexball_goalleadlimit;
235         ActivateTeamplay();
236         have_team_spawns = -1; // request team spawns
237             MUTATOR_ADD(gamemode_nexball);
238         }
239         
240         if(g_keepaway)
241         {
242                 MUTATOR_ADD(gamemode_keepaway);
243         }
244
245         if(teamplay)
246                 entcs_init();
247
248         cache_mutatormsg = strzone("");
249         cache_lastmutatormsg = strzone("");
250
251         // enforce the server's universal frag/time limits
252         if(!autocvar_g_campaign)
253         {
254                 if(fraglimit_override >= 0)
255                         cvar_set("fraglimit", ftos(fraglimit_override));
256                 if(timelimit_override >= 0)
257                         cvar_set("timelimit", ftos(timelimit_override));
258                 if(leadlimit_override >= 0)
259                         cvar_set("leadlimit", ftos(leadlimit_override));
260                 if(qualifying_override >= 0)
261                         cvar_set("g_race_qualifying_timelimit", ftos(qualifying_override));
262         }
263
264         if(g_race)
265         {
266                 // we need to find out the correct value for g_race_qualifying
267                 if(autocvar_g_campaign)
268                 {
269                         g_race_qualifying = 1;
270                 }
271                 else if(!autocvar_g_campaign && autocvar_g_race_qualifying_timelimit > 0)
272                 {
273                         g_race_qualifying = 2;
274                         race_fraglimit = autocvar_fraglimit;
275                         race_leadlimit = autocvar_leadlimit;
276                         race_timelimit = autocvar_timelimit;
277                         cvar_set("fraglimit", "0");
278                         cvar_set("leadlimit", "0");
279                         cvar_set("timelimit", ftos(autocvar_g_race_qualifying_timelimit));
280                 }
281                 else
282                         g_race_qualifying = 0;
283         }
284
285         if(g_race || g_cts)
286         {
287                 if(g_race_qualifying)
288                         independent_players = 1;
289
290                 ScoreRules_race();
291         }
292
293         InitializeEntity(world, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
294 }
295
296 string GetClientVersionMessage() {
297         string versionmsg;
298         if (self.version_mismatch) {
299                 if(self.version < autocvar_gameversion) {
300                         versionmsg = "^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8";
301                 } else {
302                         versionmsg = "^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8";
303                 }
304         } else {
305                 versionmsg = "^2client version and server version are compatible.^8";
306         }
307         return versionmsg;
308 }
309
310 string getwelcomemessage(void)
311 {
312         string s, modifications, motd;
313
314         ret_string = "";
315         MUTATOR_CALLHOOK(BuildMutatorsPrettyString);
316         modifications = ret_string;
317         
318         if(g_minstagib)
319                 modifications = strcat(modifications, ", MinstaGib");
320         if(g_weaponarena)
321         {
322                 if(g_weaponarena_random)
323                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
324                 else
325                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
326         }
327         if(autocvar_g_start_weapon_laser == 0)
328                 modifications = strcat(modifications, ", No start weapons");
329         if(autocvar_sv_gravity < 800)
330                 modifications = strcat(modifications, ", Low gravity");
331         if(g_cloaked && !g_cts)
332                 modifications = strcat(modifications, ", Cloaked");
333         if(g_grappling_hook)
334                 modifications = strcat(modifications, ", Hook");
335         if(g_midair)
336                 modifications = strcat(modifications, ", Midair");
337         if(g_pinata)
338                 modifications = strcat(modifications, ", Piñata");
339         if(g_weapon_stay && !g_cts)
340                 modifications = strcat(modifications, ", Weapons stay");
341         if(g_bloodloss > 0)
342                 modifications = strcat(modifications, ", Blood loss");
343         if(g_jetpack)
344                 modifications = strcat(modifications, ", Jet pack");
345         if(autocvar_g_powerups == 0)
346                 modifications = strcat(modifications, ", No powerups");
347         if(autocvar_g_powerups > 0)
348                 modifications = strcat(modifications, ", Powerups");
349         modifications = substring(modifications, 2, strlen(modifications) - 2);
350
351         string versionmessage;
352         versionmessage = GetClientVersionMessage();
353
354         s = strcat("This is Xonotic ", autocvar_g_xonoticversion, "\n", versionmessage);
355         s = strcat(s, "^8\n\nmatch type is ^1", gamemode_name, "^8\n");
356
357         if(modifications != "")
358                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
359
360         if (g_grappling_hook)
361                 s = strcat(s, "\n\n^3grappling hook^8 is enabled, press 'e' to use it\n");
362
363         if(cache_lastmutatormsg != autocvar_g_mutatormsg)
364         {
365                 if(cache_lastmutatormsg)
366                         strunzone(cache_lastmutatormsg);
367                 if(cache_mutatormsg)
368                         strunzone(cache_mutatormsg);
369                 cache_lastmutatormsg = strzone(autocvar_g_mutatormsg);
370                 cache_mutatormsg = strzone(cache_lastmutatormsg);
371         }
372
373         if (cache_mutatormsg != "") {
374                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
375         }
376
377         motd = autocvar_sv_motd;
378         if (motd != "") {
379                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
380         }
381         return s;
382 }
383
384 void SetPlayerColors(entity pl, float _color)
385 {
386         /*string s;
387         s = ftos(cl);
388         stuffcmd(pl, strcat("color ", s, " ", s, "\n")  );
389         pl.team = cl + 1;
390         //pl.clientcolors = pl.clientcolors - (pl.clientcolors & 15) + cl;
391         pl.clientcolors = 16*cl + cl;*/
392
393         float pants, shirt;
394         pants = _color & 0x0F;
395         shirt = _color & 0xF0;
396
397
398         if(teamplay) {
399                 setcolor(pl, 16*pants + pants);
400         } else {
401                 setcolor(pl, shirt + pants);
402         }
403 }
404
405 void SetPlayerTeam(entity pl, float t, float s, float noprint)
406 {
407         float _color;
408
409         if(t == 4)
410                 _color = COLOR_TEAM4 - 1;
411         else if(t == 3)
412                 _color = COLOR_TEAM3 - 1;
413         else if(t == 2)
414                 _color = COLOR_TEAM2 - 1;
415         else
416                 _color = COLOR_TEAM1 - 1;
417
418         SetPlayerColors(pl,_color);
419
420         if(t != s) {
421                 LogTeamchange(pl.playerid, pl.team, 3);  // log manual team join
422
423                 if(!noprint)
424                 bprint(pl.netname, "^7 has changed from ", TeamNoName(s), " to ", TeamNoName(t), "\n");
425         }
426
427 }
428
429 // set c1...c4 to show what teams are allowed
430 void CheckAllowedTeams (entity for_whom)
431 {
432         float dm;
433         entity head;
434         string teament_name;
435
436         c1 = c2 = c3 = c4 = -1;
437         cb1 = cb2 = cb3 = cb4 = 0;
438
439         teament_name = string_null;
440         if(g_onslaught)
441         {
442                 // onslaught is special
443                 head = findchain(classname, "onslaught_generator");
444                 while (head)
445                 {
446                         if (head.team == COLOR_TEAM1) c1 = 0;
447                         if (head.team == COLOR_TEAM2) c2 = 0;
448                         if (head.team == COLOR_TEAM3) c3 = 0;
449                         if (head.team == COLOR_TEAM4) c4 = 0;
450                         head = head.chain;
451                 }
452         }
453         else if(g_domination)
454                 teament_name = "dom_team";
455         else if(g_ctf)
456                 teament_name = "ctf_team";
457         else if(g_tdm)
458                 teament_name = "tdm_team";
459         else if(g_nexball)
460                 teament_name = "nexball_team";
461         else if(g_assault)
462                 c1 = c2 = 0; // Assault always has 2 teams
463         else
464         {
465                 // cover anything else by treating it like tdm with no teams spawned
466                 if(g_race)
467                         dm = race_teams;
468                 else
469                         dm = 2;
470
471                 ret_float = dm;
472                 MUTATOR_CALLHOOK(GetTeamCount);
473                 dm = ret_float;
474
475                 if(dm >= 4)
476                         c1 = c2 = c3 = c4 = 0;
477                 else if(dm >= 3)
478                         c1 = c2 = c3 = 0;
479                 else
480                         c1 = c2 = 0;
481         }
482
483         // find out what teams are allowed if necessary
484         if(teament_name)
485         {
486                 head = find(world, classname, teament_name);
487                 while(head)
488                 {
489                         if(!(g_domination && head.netname == ""))
490                         {
491                                 if(head.team == COLOR_TEAM1)
492                                         c1 = 0;
493                                 else if(head.team == COLOR_TEAM2)
494                                         c2 = 0;
495                                 else if(head.team == COLOR_TEAM3)
496                                         c3 = 0;
497                                 else if(head.team == COLOR_TEAM4)
498                                         c4 = 0;
499                         }
500                         head = find(head, classname, teament_name);
501                 }
502         }
503
504         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
505         if(c3==-1 && c4==-1)
506         if(autocvar_bot_vs_human && for_whom)
507         {
508                 if(autocvar_bot_vs_human > 0)
509                 {
510                         // bots are all blue
511                         if(clienttype(for_whom) == CLIENTTYPE_BOT)
512                                 c1 = c3 = c4 = -1;
513                         else
514                                 c2 = -1;
515                 }
516                 else
517                 {
518                         // bots are all red
519                         if(clienttype(for_whom) == CLIENTTYPE_BOT)
520                                 c2 = c3 = c4 = -1;
521                         else
522                                 c1 = -1;
523                 }
524         }
525
526         // if player has a forced team, ONLY allow that one
527         if(self.team_forced == COLOR_TEAM1 && c1 >= 0)
528                 c2 = c3 = c4 = -1;
529         else if(self.team_forced == COLOR_TEAM2 && c2 >= 0)
530                 c1 = c3 = c4 = -1;
531         else if(self.team_forced == COLOR_TEAM3 && c3 >= 0)
532                 c1 = c2 = c4 = -1;
533         else if(self.team_forced == COLOR_TEAM4 && c4 >= 0)
534                 c1 = c2 = c3 = -1;
535 }
536
537 float PlayerValue(entity p)
538 {
539         return 1;
540         // FIXME: it always returns 1...
541 }
542
543 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
544 // teams that are allowed will now have their player counts stored in c1...c4
545 void GetTeamCounts(entity ignore)
546 {
547         entity head;
548         float value, bvalue;
549         // now count how many players are on each team already
550
551         // FIXME: also find and memorize the lowest-scoring bot on each team (in case players must be shuffled around)
552         // also remember the lowest-scoring player
553
554         FOR_EACH_CLIENT(head)
555         {
556                 float t;
557                 if(head.classname == "player")
558                         t = head.team;
559                 else if(head.team_forced > 0)
560                         t = head.team_forced; // reserve the spot
561                 else
562                         continue;
563                 if(head != ignore)// && head.netname != "")
564                 {
565                         value = PlayerValue(head);
566                         if(clienttype(head) == CLIENTTYPE_BOT)
567                                 bvalue = value;
568                         else
569                                 bvalue = 0;
570                         if(t == COLOR_TEAM1)
571                         {
572                                 if(c1 >= 0)
573                                 {
574                                         c1 = c1 + value;
575                                         cb1 = cb1 + bvalue;
576                                 }
577                         }
578                         if(t == COLOR_TEAM2)
579                         {
580                                 if(c2 >= 0)
581                                 {
582                                         c2 = c2 + value;
583                                         cb2 = cb2 + bvalue;
584                                 }
585                         }
586                         if(t == COLOR_TEAM3)
587                         {
588                                 if(c3 >= 0)
589                                 {
590                                         c3 = c3 + value;
591                                         cb3 = cb3 + bvalue;
592                                 }
593                         }
594                         if(t == COLOR_TEAM4)
595                         {
596                                 if(c4 >= 0)
597                                 {
598                                         c4 = c4 + value;
599                                         cb4 = cb4 + bvalue;
600                                 }
601                         }
602                 }
603         }
604
605         // if the player who has a forced team has not joined yet, reserve the spot
606         if(autocvar_g_campaign)
607         {
608                 switch(autocvar_g_campaign_forceteam)
609                 {
610                         case 1: if(c1 == cb1) ++c1; break;
611                         case 2: if(c2 == cb2) ++c2; break;
612                         case 3: if(c3 == cb3) ++c3; break;
613                         case 4: if(c4 == cb4) ++c4; break;
614                 }
615         }
616 }
617
618 float TeamSmallerEqThanTeam(float ta, float tb, entity e)
619 {
620         // we assume that CheckAllowedTeams and GetTeamCounts have already been called
621         float f;
622         float ca = -1, cb = -1, cba = 0, cbb = 0, sa = 0, sb = 0;
623
624         switch(ta)
625         {
626                 case 1: ca = c1; cba = cb1; sa = team1_score; break;
627                 case 2: ca = c2; cba = cb2; sa = team2_score; break;
628                 case 3: ca = c3; cba = cb3; sa = team3_score; break;
629                 case 4: ca = c4; cba = cb4; sa = team4_score; break;
630         }
631         switch(tb)
632         {
633                 case 1: cb = c1; cbb = cb1; sb = team1_score; break;
634                 case 2: cb = c2; cbb = cb2; sb = team2_score; break;
635                 case 3: cb = c3; cbb = cb3; sb = team3_score; break;
636                 case 4: cb = c4; cbb = cb4; sb = team4_score; break;
637         }
638
639         // invalid
640         if(ca < 0 || cb < 0)
641                 return FALSE;
642
643         // equal
644         if(ta == tb)
645                 return TRUE;
646
647         if(clienttype(e) == CLIENTTYPE_REAL)
648         {
649                 if(bots_would_leave)
650                 {
651                         ca -= cba * 0.999;
652                         cb -= cbb * 0.999;
653                 }
654         }
655         
656         // keep teams alive (teams of size 0 always count as smaller, ignoring score)
657         if(ca < 1)
658                 if(cb >= 1)
659                         return TRUE;
660         if(ca >= 1)
661                 if(cb < 1)
662                         return FALSE;
663
664         // first, normalize
665         f = max(ca, cb, 1);
666         ca /= f;
667         cb /= f;
668         f = max(sa, sb, 1);
669         sa /= f;
670         sb /= f;
671
672         // the more we're at the end of the match, the more take scores into account
673         f = bound(0, game_completion_ratio * autocvar_g_balance_teams_scorefactor, 1);
674         ca += (sa - ca) * f;
675         cb += (sb - cb) * f;
676
677         return ca <= cb;
678 }
679
680 // returns # of smallest team (1, 2, 3, 4)
681 // NOTE: Assumes CheckAllowedTeams has already been called!
682 float FindSmallestTeam(entity pl, float ignore_pl)
683 {
684         float totalteams, t;
685         totalteams = 0;
686
687         // find out what teams are available
688         //CheckAllowedTeams();
689
690         // make sure there are at least 2 teams to join
691         if(c1 >= 0)
692                 totalteams = totalteams + 1;
693         if(c2 >= 0)
694                 totalteams = totalteams + 1;
695         if(c3 >= 0)
696                 totalteams = totalteams + 1;
697         if(c4 >= 0)
698                 totalteams = totalteams + 1;
699
700         if((autocvar_bot_vs_human || pl.team_forced > 0) && totalteams == 1)
701                 totalteams += 1;
702
703         if(totalteams <= 1)
704         {
705                 if(autocvar_g_campaign && pl && clienttype(pl) == CLIENTTYPE_REAL)
706                         return 1; // special case for campaign and player joining
707                 else if(g_domination)
708                         error("Too few teams available for domination\n");
709                 else if(g_ctf)
710                         error("Too few teams available for ctf\n");
711                 else if(g_keyhunt)
712                         error("Too few teams available for key hunt\n");
713                 else if(g_freezetag)
714                         error("Too few teams available for freeze tag\n");
715                 else
716                         error("Too few teams available for team deathmatch\n");
717         }
718
719         // count how many players are in each team
720         if(ignore_pl)
721                 GetTeamCounts(pl);
722         else
723                 GetTeamCounts(world);
724
725         RandomSelection_Init();
726         
727         t = 1;
728         if(TeamSmallerEqThanTeam(2, t, pl))
729                 t = 2;
730         if(TeamSmallerEqThanTeam(3, t, pl))
731                 t = 3;
732         if(TeamSmallerEqThanTeam(4, t, pl))
733                 t = 4;
734
735         // now t is the minimum, or A minimum!
736         if(t == 1 || TeamSmallerEqThanTeam(1, t, pl))
737                 RandomSelection_Add(world, 1, string_null, 1, 1);
738         if(t == 2 || TeamSmallerEqThanTeam(2, t, pl))
739                 RandomSelection_Add(world, 2, string_null, 1, 1);
740         if(t == 3 || TeamSmallerEqThanTeam(3, t, pl))
741                 RandomSelection_Add(world, 3, string_null, 1, 1);
742         if(t == 4 || TeamSmallerEqThanTeam(4, t, pl))
743                 RandomSelection_Add(world, 4, string_null, 1, 1);
744
745         return RandomSelection_chosen_float;
746 }
747
748 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam)
749 {
750         float smallest, selectedteam;
751
752         // don't join a team if we're not playing a team game
753         if(!teamplay)
754                 return 0;
755
756         // find out what teams are available
757         CheckAllowedTeams(pl);
758
759         // if we don't care what team he ends up on, put him on whatever team he entered as.
760         // if he's not on a valid team, then let other code put him on the smallest team
761         if(!forcebestteam)
762         {
763                 if(     c1 >= 0 && pl.team == COLOR_TEAM1)
764                         selectedteam = pl.team;
765                 else if(c2 >= 0 && pl.team == COLOR_TEAM2)
766                         selectedteam = pl.team;
767                 else if(c3 >= 0 && pl.team == COLOR_TEAM3)
768                         selectedteam = pl.team;
769                 else if(c4 >= 0 && pl.team == COLOR_TEAM4)
770                         selectedteam = pl.team;
771                 else
772                         selectedteam = -1;
773
774                 if(selectedteam > 0)
775                 {
776                         if(!only_return_best)
777                         {
778                                 SetPlayerColors(pl, selectedteam - 1);
779
780                                 // when JoinBestTeam is called by client.qc/ClientKill_Now_TeamChange the players team is -1 and thus skipped
781                                 // when JoinBestTeam is called by cl_client.qc/ClientConnect the player_id is 0 the log attempt is rejected
782                                 LogTeamchange(pl.playerid, pl.team, 99);
783                         }
784                         return selectedteam;
785                 }
786                 // otherwise end up on the smallest team (handled below)
787         }
788
789         smallest = FindSmallestTeam(pl, TRUE);
790
791         if(!only_return_best && !pl.bot_forced_team)
792         {
793                 TeamchangeFrags(self);
794                 if(smallest == 1)
795                 {
796                         SetPlayerColors(pl, COLOR_TEAM1 - 1);
797                 }
798                 else if(smallest == 2)
799                 {
800                         SetPlayerColors(pl, COLOR_TEAM2 - 1);
801                 }
802                 else if(smallest == 3)
803                 {
804                         SetPlayerColors(pl, COLOR_TEAM3 - 1);
805                 }
806                 else if(smallest == 4)
807                 {
808                         SetPlayerColors(pl, COLOR_TEAM4 - 1);
809                 }
810                 else
811                 {
812                         error("smallest team: invalid team\n");
813                 }
814
815                 LogTeamchange(pl.playerid, pl.team, 2); // log auto join
816
817                 if(pl.deadflag == DEAD_NO)
818                         Damage(pl, pl, pl, 100000, DEATH_TEAMCHANGE, pl.origin, '0 0 0');
819         }
820
821         return smallest;
822 }
823
824 //void() ctf_playerchanged;
825 void SV_ChangeTeam(float _color)
826 {
827         float scolor, dcolor, steam, dteam; //, dbotcount, scount, dcount;
828
829         // in normal deathmatch we can just apply the color and we're done
830         if(!teamplay) {
831                 SetPlayerColors(self, _color);
832                 return;
833         }
834
835         scolor = self.clientcolors & 0x0F;
836         dcolor = _color & 0x0F;
837
838         if(scolor == COLOR_TEAM1 - 1)
839                 steam = 1;
840         else if(scolor == COLOR_TEAM2 - 1)
841                 steam = 2;
842         else if(scolor == COLOR_TEAM3 - 1)
843                 steam = 3;
844         else // if(scolor == COLOR_TEAM4 - 1)
845                 steam = 4;
846         if(dcolor == COLOR_TEAM1 - 1)
847                 dteam = 1;
848         else if(dcolor == COLOR_TEAM2 - 1)
849                 dteam = 2;
850         else if(dcolor == COLOR_TEAM3 - 1)
851                 dteam = 3;
852         else // if(dcolor == COLOR_TEAM4 - 1)
853                 dteam = 4;
854
855         CheckAllowedTeams(self);
856
857         if(dteam == 1 && c1 < 0) dteam = 4;
858         if(dteam == 4 && c4 < 0) dteam = 3;
859         if(dteam == 3 && c3 < 0) dteam = 2;
860         if(dteam == 2 && c2 < 0) dteam = 1;
861
862         // not changing teams
863         if(scolor == dcolor)
864         {
865                 //bprint("same team change\n");
866                 SetPlayerTeam(self, dteam, steam, TRUE);
867                 return;
868         }
869
870         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && self.wasplayer)) {
871                 sprint(self, "Team changes not allowed\n");
872                 return; // changing teams is not allowed
873         }
874
875         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
876         if(autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
877         {
878                 GetTeamCounts(self);
879                 if(!TeamSmallerEqThanTeam(dteam, steam, self))
880                 {
881                         sprint(self, "Cannot change to a larger/better/shinier team\n");
882                         return;
883                 }
884         }
885
886 //      bprint("allow change teams from ", ftos(steam), " to ", ftos(dteam), "\n");
887
888         if(self.classname == "player" && steam != dteam)
889         {
890                 // reduce frags during a team change
891                 TeamchangeFrags(self);
892         }
893
894         SetPlayerTeam(self, dteam, steam, FALSE);
895
896         if(self.classname == "player" && steam != dteam)
897         {
898                 // kill player when changing teams
899                 if(self.deadflag == DEAD_NO)
900                         Damage(self, self, self, 100000, DEATH_TEAMCHANGE, self.origin, '0 0 0');
901         }
902 }
903
904 void ShufflePlayerOutOfTeam (float source_team)
905 {
906         float smallestteam, smallestteam_count, steam;
907         float lowest_bot_score, lowest_player_score;
908         entity head, lowest_bot, lowest_player, selected;
909
910         smallestteam = 0;
911         smallestteam_count = 999999999;
912
913         if(c1 >= 0 && c1 < smallestteam_count)
914         {
915                 smallestteam = 1;
916                 smallestteam_count = c1;
917         }
918         if(c2 >= 0 && c2 < smallestteam_count)
919         {
920                 smallestteam = 2;
921                 smallestteam_count = c2;
922         }
923         if(c3 >= 0 && c3 < smallestteam_count)
924         {
925                 smallestteam = 3;
926                 smallestteam_count = c3;
927         }
928         if(c4 >= 0 && c4 < smallestteam_count)
929         {
930                 smallestteam = 4;
931                 smallestteam_count = c4;
932         }
933
934         if(!smallestteam)
935         {
936                 bprint("warning: no smallest team\n");
937                 return;
938         }
939
940         if(source_team == 1)
941                 steam = COLOR_TEAM1;
942         else if(source_team == 2)
943                 steam = COLOR_TEAM2;
944         else if(source_team == 3)
945                 steam = COLOR_TEAM3;
946         else // if(source_team == 4)
947                 steam = COLOR_TEAM4;
948
949         lowest_bot = world;
950         lowest_bot_score = 999999999;
951         lowest_player = world;
952         lowest_player_score = 999999999;
953
954         // find the lowest-scoring player & bot of that team
955         FOR_EACH_PLAYER(head)
956         {
957                 if(head.team == steam)
958                 {
959                         if(head.isbot)
960                         {
961                                 if(head.totalfrags < lowest_bot_score)
962                                 {
963                                         lowest_bot = head;
964                                         lowest_bot_score = head.totalfrags;
965                                 }
966                         }
967                         else
968                         {
969                                 if(head.totalfrags < lowest_player_score)
970                                 {
971                                         lowest_player = head;
972                                         lowest_player_score = head.totalfrags;
973                                 }
974                         }
975                 }
976         }
977
978         // prefers to move a bot...
979         if(lowest_bot != world)
980                 selected = lowest_bot;
981         // but it will move a player if it has to
982         else
983                 selected = lowest_player;
984         // don't do anything if it couldn't find anyone
985         if(!selected)
986         {
987                 bprint("warning: couldn't find a player to move from team\n");
988                 return;
989         }
990
991         // smallest team gains a member
992         if(smallestteam == 1)
993         {
994                 c1 = c1 + 1;
995         }
996         else if(smallestteam == 2)
997         {
998                 c2 = c2 + 1;
999         }
1000         else if(smallestteam == 3)
1001         {
1002                 c3 = c3 + 1;
1003         }
1004         else if(smallestteam == 4)
1005         {
1006                 c4 = c4 + 1;
1007         }
1008         else
1009         {
1010                 bprint("warning: destination team invalid\n");
1011                 return;
1012         }
1013         // source team loses a member
1014         if(source_team == 1)
1015         {
1016                 c1 = c1 + 1;
1017         }
1018         else if(source_team == 2)
1019         {
1020                 c2 = c2 + 2;
1021         }
1022         else if(source_team == 3)
1023         {
1024                 c3 = c3 + 3;
1025         }
1026         else if(source_team == 4)
1027         {
1028                 c4 = c4 + 4;
1029         }
1030         else
1031         {
1032                 bprint("warning: source team invalid\n");
1033                 return;
1034         }
1035
1036         // move the player to the new team
1037         TeamchangeFrags(selected);
1038         SetPlayerTeam(selected, smallestteam, source_team, FALSE);
1039
1040         if(selected.deadflag == DEAD_NO)
1041                 Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE, selected.origin, '0 0 0');
1042         centerprint(selected, strcat("You have been moved into a different team to improve team balance\nYou are now on: ", ColoredTeamName(selected.team)));
1043 }
1044
1045 // code from here on is just to support maps that don't have team entities
1046 void tdm_spawnteam (string teamname, float teamcolor)
1047 {
1048         entity e;
1049         e = spawn();
1050         e.classname = "tdm_team";
1051         e.netname = teamname;
1052         e.cnt = teamcolor;
1053         e.team = e.cnt + 1;
1054 }
1055
1056 // spawn some default teams if the map is not set up for tdm
1057 void tdm_spawnteams()
1058 {
1059         float numteams;
1060
1061         numteams = autocvar_g_tdm_teams_override;
1062         if(numteams < 2)
1063                 numteams = autocvar_g_tdm_teams;
1064         numteams = bound(2, numteams, 4);
1065
1066         tdm_spawnteam("Red", COLOR_TEAM1-1);
1067         tdm_spawnteam("Blue", COLOR_TEAM2-1);
1068         if(numteams >= 3)
1069                 tdm_spawnteam("Yellow", COLOR_TEAM3-1);
1070         if(numteams >= 4)
1071                 tdm_spawnteam("Pink", COLOR_TEAM4-1);
1072 }
1073
1074 void tdm_delayedinit()
1075 {
1076         // if no teams are found, spawn defaults
1077         if (find(world, classname, "tdm_team") == world)
1078                 tdm_spawnteams();
1079 }
1080
1081 void tdm_init()
1082 {
1083         InitializeEntity(world, tdm_delayedinit, INITPRIO_GAMETYPE);
1084 }