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