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