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