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