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