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