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