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