]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/teamplay.qc
use the button macros everywhere
[divverent/nexuiz.git] / data / qcsrc / server / teamplay.qc
1 string cache_motd;
2 string cache_mutatormsg;
3 string cache_lastmotd;
4 string cache_lastmutatormsg;
5
6 // client counts for each team
7 float c1, c2, c3, c4;
8 // # of bots on those teams
9 float cb1, cb2, cb3, cb4;
10
11 float audit_teams_time;
12
13 float() IsTeamBalanceForced = {
14         if(intermission_running)
15                 return 0; // no rebalancing whatsoever please
16         if(!cvar("teamplay"))
17                 return 0;
18         if(cvar("g_campaign"))
19                 return 0;
20         if(!cvar("g_balance_teams_force"))
21                 return -1;
22         return 1;
23 }
24
25 void TeamchangeFrags(entity e)
26 {
27         if(e.classname == "player")
28         {
29                 // reduce frags during a team change
30                 DistributeFragsAmongTeam(e, (e.clientcolors & 0x0F) + 1, 1 - cvar("g_changeteam_fragtransfer") / 100);
31         }
32 }
33
34 vector TeamColor(float teem)
35 {
36         switch(teem)
37         {
38                 case COLOR_TEAM1:
39                         return '1 0.0625 0.0625';
40                 case COLOR_TEAM2:
41                         return '0.0625 0.0625 1';
42                 case COLOR_TEAM3:
43                         return '1 1 0.0625';
44                 case COLOR_TEAM4:
45                         return '1 0.0625 1';
46                 default:
47                         return '1 1 1';
48         }
49 }
50
51 string TeamName(float t)
52 {
53         return strcat(Team_ColorName(t), " Team");
54 }
55 string ColoredTeamName(float t)
56 {
57         return strcat(Team_ColorCode(t), Team_ColorName(t), " Team^7");
58 }
59 string TeamNoName(float t)
60 {
61         // fixme: Search for team entities and get their .netname's!
62         if(t == 1)
63                 return "Red Team";
64         if(t == 2)
65                 return "Blue Team";
66         if(t == 3)
67                 return "Yellow Team";
68         if(t == 4)
69                 return "Pink Team";
70         return "Neutral Team";
71 }
72
73 void dom_init();
74 void ctf_init();
75 void runematch_init();
76 void tdm_init();
77
78 void(entity pl) LogTeamchange =
79 {
80         string str;
81         if(!cvar("sv_eventlog"))
82                 return;
83         if(pl.playerid < 1)
84                 return;
85         str = strcat(":team:", ftos(pl.playerid), ":");
86         str = strcat(str, ftos(pl.team));
87         GameLogEcho(str, FALSE);
88 }
89
90 void ResetGameCvars()
91 {
92         cvar_set("g_dm", "0");
93         cvar_set("g_tdm", "0");
94         cvar_set("g_domination", "0");
95         cvar_set("g_ctf", "0");
96         cvar_set("g_runematch", "0");
97         cvar_set("g_lms", "0");
98         cvar_set("g_arena", "0");
99         cvar_set("g_keyhunt", "0");
100         cvar_set("g_assault", "0");
101         cvar_set("g_onslaught", "0");
102         cvar_set("teamplay", "0");
103 }
104
105 void ActivateTeamplay()
106 {
107         float teamplay_default;
108         teamplay_default = cvar("teamplay_default");
109
110         if(teamplay_default)
111                 cvar_set("teamplay", ftos(teamplay_default));
112         else
113                 cvar_set("teamplay", "3");
114 }
115
116 void InitGameplayMode()
117 {
118         float fraglimit_override, timelimit_override;
119
120         VoteReset();
121
122         game = cvar("gamecfg"); // load game options
123
124         // game cvars get reset before map changes
125         // then map's cfg sets them as desired
126
127         // FIXME: also set a message or game mode name to print to players when the join
128
129         // set both here, gamemode can override it later
130         timelimit_override = cvar("timelimit_override");
131         fraglimit_override = cvar("fraglimit_override");
132
133         if(game == GAME_DOMINATION || cvar("g_domination"))
134         {
135                 ResetGameCvars();
136                 game = GAME_DOMINATION;
137                 cvar_set("g_domination", "1");
138
139                 ActivateTeamplay();
140
141                 fraglimit_override = cvar("g_domination_point_limit");
142
143                 gamemode_name = "Domination";
144                 teams_matter = 1;
145         }
146         else if(game == GAME_CTF || cvar("g_ctf"))
147         {
148                 ResetGameCvars();
149                 game = GAME_CTF;
150                 cvar_set("g_ctf", "1");
151
152                 ActivateTeamplay();
153
154                 fraglimit_override = cvar("g_ctf_capture_limit");
155
156                 gamemode_name = "Capture the Flag";
157                 teams_matter = 1;
158         }
159         else if(game == GAME_RUNEMATCH || cvar("g_runematch"))
160         {
161                 game = GAME_RUNEMATCH;
162                 cvar_set("g_runematch", "1");
163                 cvar_set("g_minstagib", "0");
164
165                 if(cvar("deathmatch_force_teamplay"))
166                         ActivateTeamplay();
167
168                 fraglimit_override = cvar("g_runematch_point_limit");
169
170                 gamemode_name = "Rune Match";
171                 if(cvar("teamplay"))
172                         teams_matter = 1;
173                 else
174                         teams_matter = 0;
175         }
176         else if(game == GAME_DEATHMATCH || game == GAME_TEAM_DEATHMATCH || cvar("g_tdm"))
177         {
178                 if(!cvar("deathmatch"))
179                         cvar_set("deathmatch", "1");
180
181
182                 if(game == GAME_TEAM_DEATHMATCH || cvar("g_tdm") || cvar("deathmatch_force_teamplay"))
183                 {
184                         ResetGameCvars();
185                         game = GAME_TEAM_DEATHMATCH;
186                         gamemode_name = "Team Deathmatch";
187                         ActivateTeamplay();
188                         teams_matter = 1;
189                         cvar_set("g_tdm", "1");
190                 }
191                 else
192                 {
193                         ResetGameCvars();
194                         game = GAME_DEATHMATCH;
195                         gamemode_name = "Deathmatch";
196                         teams_matter = 0;
197                 }
198
199                 fraglimit_override = cvar("fraglimit_override");
200         }
201         else if(game == GAME_ASSAULT || cvar("g_assault"))
202         {
203                 ResetGameCvars();
204                 game = GAME_ASSAULT;
205                 gamemode_name = "Assault";
206                 ActivateTeamplay();
207                 teams_matter = 1;
208                 cvar_set("g_assault", "1");
209         }
210         else if(game == GAME_LMS || cvar("g_lms"))
211         {
212                 ResetGameCvars();
213                 game = GAME_LMS;
214                 cvar_set("g_lms", "1");
215                 fraglimit_override = cvar("g_lms_lives_override");
216                 if(fraglimit_override == 0)
217                         fraglimit_override = -1;
218                 gamemode_name = "Last Man Standing";
219                 teams_matter = 0;
220                 lms_lowest_lives = 999;
221         }
222         else if(game == GAME_ARENA || cvar("g_arena"))
223         {
224                 ResetGameCvars();
225                 game = GAME_ARENA;
226                 cvar_set("g_arena", "1");
227                 fraglimit_override = cvar("g_arena_point_limit");
228                 maxspawned = cvar("g_arena_maxspawned");
229                 if(maxspawned < 2)
230                         maxspawned = 2;
231                 arena_roundbased = cvar("g_arena_roundbased");
232                 gamemode_name = "Arena";
233                 teams_matter = 0;
234         }
235         else if(game == GAME_KEYHUNT || cvar("g_keyhunt"))
236         {
237                 ResetGameCvars();
238                 game = GAME_KEYHUNT;
239                 cvar_set("g_keyhunt", "1");
240                 fraglimit_override = cvar("g_keyhunt_point_limit");
241                 ActivateTeamplay();
242                 gamemode_name = "Key Hunt";
243                 teams_matter = 1;
244         }
245         else if(game == GAME_ONSLAUGHT || cvar("g_onslaught"))
246         {
247                 ResetGameCvars();
248                 game = GAME_ONSLAUGHT;
249                 cvar_set("g_onslaught", "1");
250
251                 ActivateTeamplay();
252
253                 gamemode_name = "Onslaught";
254                 teams_matter = 1;
255         }
256         else
257         {
258                 // we can only assume...
259                 ResetGameCvars();
260                 cvar_set("g_dm", "1");
261                 gamemode_name = "Deathmatch";
262                 teams_matter = 0;
263         }
264 /*      else if(game == GAME_TEAM_DEATHMATCH)
265         {
266                 if(!cvar("deathmatch"))
267                         cvar_set("deathmatch", "1");
268
269                 //if(!cvar("teamplay"))
270                 //      cvar_set("teamplay", "3");
271                 ActivateTeamplay();
272
273                 fraglimit_override = cvar("fraglimit_override");
274         }*/
275
276         // those mutators rule each other out
277         if(cvar("g_minstagib"))
278         {
279                 cvar_set("g_instagib", "0");
280                 cvar_set("g_rocketarena", "0");
281         }
282         if(cvar("g_instagib"))
283         {
284                 cvar_set("g_minstagib", "0");
285                 cvar_set("g_rocketarena", "0");
286         }
287         if(cvar("g_rocketarena"))
288         {
289                 cvar_set("g_instagib", "0");
290                 cvar_set("g_minstagib", "0");
291         }
292
293         g_domination = cvar("g_domination");
294         g_ctf = cvar("g_ctf");
295         g_lms = cvar("g_lms");
296         g_tdm = cvar("g_tdm");
297         g_runematch = cvar("g_runematch");
298         g_keyhunt = cvar("g_keyhunt");
299         g_onslaught = cvar("g_onslaught");
300         g_assault = cvar("g_assault");
301         g_arena = cvar("g_arena");
302
303         cache_mutatormsg = strzone("");
304         cache_motd = strzone("");
305         cache_lastmutatormsg = strzone("");
306         cache_lastmotd = strzone("");
307
308         // enforce the server's universal frag/time limits
309         if(!cvar("g_campaign"))
310         {
311                 if(fraglimit_override >= 0)
312                         cvar_set("fraglimit", ftos(fraglimit_override));
313                 if(timelimit_override >= 0)
314                         cvar_set("timelimit", ftos(timelimit_override));
315         }
316
317         if (game == GAME_DOMINATION)//cvar("g_domination"))
318                 dom_init();
319         else if (game == GAME_CTF)//cvar("g_ctf"))
320                 ctf_init();
321         else if (game == GAME_RUNEMATCH)//cvar("g_runematch"))
322                 runematch_init();
323         else if (game == GAME_TEAM_DEATHMATCH)//cvar("g_runematch"))
324                 tdm_init();
325         else if (game == GAME_KEYHUNT)//cvar("g_keyhunt"))
326                 kh_init();
327 }
328
329 string GetClientVersionMessage(float v) {
330         local string versionmsg;
331         if (v == 1) {
332                 versionmsg = "^1client is too old to get versioninfo.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nUPDATE!!! (http://www.nexuiz.com)^8";
333                 // either that or someone wants to be funny
334         } else if (v != cvar("gameversion")) {
335                 if(v < cvar("gameversion")) {
336                         versionmsg = "^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8";
337                 } else {
338                         versionmsg = "^3This server is using an outdated Nexuiz version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8";
339                 }
340         } else {
341                 versionmsg = "^2client version and server version are compatible.^8";
342         }
343         return strzone(versionmsg);
344
345 }
346
347
348 void PrintWelcomeMessage(entity pl)
349 {
350         string s, mutator, modifications, padding;
351
352         /*if(self.welcomemessage_time > time)
353                 return;
354         self.welcomemessage_time = time + 0.8; */
355
356         if(self.cvar_scr_centertime == 0) return;
357         if( !(timeoutStatus >= 1 || (time < restart_countdown) ) ) { //really print the WelcomeMessage to the player every frame when timeout-seconds are shown or the game is restarted, to make sure that the shown number is accurate
358                 if(self.welcomemessage_time > time) return;
359                 self.welcomemessage_time = time + self.cvar_scr_centertime * 0.6;
360         }
361
362         if(cvar("g_campaign"))
363         {
364                 centerprint(pl, campaign_message);
365                 return;
366         }
367
368         if(!self.BUTTON_INFO)
369         {
370                 if(self.classname == "observer")
371                 {
372                         if(g_lms && self.frags <= 0 && self.frags > -666)
373                                 return centerprint_atprio(self, CENTERPRIO_SPAM, strcat(NEWLINES, "^1You have no more lives left\nwait for next round\n\n\n^7press attack to spectate other players"));
374                         else if(g_lms && self.frags == -666)
375                                 return centerprint_atprio(self, CENTERPRIO_SPAM, strcat(NEWLINES, "^1Match has already begun\nwait for next round\n\n\n^7press attack to spectate other players"));
376                 }
377                 else if(self.classname == "spectator")
378                 {
379                         if ((g_lms && self.frags < 1) || g_arena)
380                                 return centerprint_atprio(self, CENTERPRIO_SPAM, strcat(NEWLINES, "spectating ", self.enemy.netname, "\n\n\n^7press attack for next player\npress attack2 for free fly mode"));
381                         else {
382                                 local string specString;
383                                 specString = strcat(NEWLINES, "spectating ", self.enemy.netname, "\n\n\n^7press jump to play\n^7press attack for next player\npress attack2 for free fly mode");
384                                 
385                                 if(time < restart_countdown) //also show the countdown when being a spectator
386                                         specString = strcat(specString, "\n\n^1Game starts in ", ftos(restartAnnouncer.cnt + 1), " seconds^7");
387                                 else if (timeoutStatus != 0)
388                                         specString = strcat(specString, "\n\n", getTimeoutText(1));
389                                 return centerprint_atprio(self, CENTERPRIO_SPAM, specString);
390                         }
391                 }
392         }
393
394         if(g_minstagib)
395                 mutator = "^2Minstagib ^1";
396         else if(g_instagib)
397                 mutator = "^2Instagib ^1";
398         else if(g_rocketarena)
399                 mutator = "^2Rocketarena ^1";
400         else if(g_nixnex)
401                 mutator = "^2No Items Nexuiz ^1";
402
403         if(g_midair) {
404                 // to protect against unheedingly made changes
405                 if (modifications) {
406                         modifications = strcat(modifications, ", ");
407                 }
408                 modifications = "midair";
409         }
410         if(g_vampire) {
411                 if (modifications) {
412                         modifications = strcat(modifications, ", ");
413                 }
414                 modifications = strcat(modifications, "vampire");
415         }
416         if(g_laserguided_missile) {
417                 if (modifications) {
418                         modifications = strcat(modifications, ", ");
419                 }
420                 modifications = strcat(modifications, "laser-guided-missiles");
421         }
422         if(g_tourney) {
423                 if (modifications) {
424                         modifications = strcat(modifications, ", ");
425                 }
426                 modifications = strcat(modifications, "Tournament");
427         }
428
429         local string versionmessage;
430         versionmessage = GetClientVersionMessage(self.version);
431
432         s = strcat(s, NEWLINES, "This is Nexuiz ", cvar_string("g_nexuizversion"), "\n", versionmessage);
433         s = strcat(s, "^8\n\nmatch type is ^1", mutator, gamemode_name, "^8\n");
434
435         if(modifications != "")
436                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
437
438         if(g_tourney) {
439                 if(!tourneyInMatchStage)
440                         s = strcat(s, "\n^8The game is currently in ^3warmup-stage ^8!\n");
441                 else
442                         s = strcat(s, "\n^8The game is currently in ^3match-stage ^8!\n");
443         }
444
445         if(time < restart_countdown)
446                 s = strcat(s, "\n^1Game starts in ", ftos(restartAnnouncer.cnt + 1), " seconds^7");
447
448         if(timeoutStatus != 0)
449                 s = strcat(s, "\n\n", getTimeoutText(1));
450
451         s = strzone(s);
452
453         if (g_grappling_hook)
454                 s = strcat(s, "\n\n^8grappling hook is enabled, press 'e' to use it\n");
455
456         if(cache_lastmutatormsg != cvar_string("g_mutatormsg"))
457         {
458                 if(cache_lastmutatormsg)
459                         strunzone(cache_lastmutatormsg);
460                 if(cache_mutatormsg)
461                         strunzone(cache_mutatormsg);
462                 cache_lastmutatormsg = strzone(cvar_string("g_mutatormsg"));
463                 cache_mutatormsg = strzone(wordwrap(cache_lastmutatormsg, 50));
464         }
465
466         if (cache_mutatormsg != "") {
467                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
468         }
469         
470         if(cache_lastmotd != cvar_string("sv_motd"))
471         {
472                 if(cache_lastmotd)
473                         strunzone(cache_lastmotd);
474                 if(cache_motd)
475                         strunzone(cache_motd);
476                 cache_lastmotd = strzone(cvar_string("sv_motd"));
477                 cache_motd = strzone(wordwrap(cache_lastmotd, 50));
478         }
479
480         if (cache_motd != "") {
481                 s = strcat(s, "\n\n^8MOTD: ^7", cache_motd);
482         }
483
484         s = strcat(s, "\n");
485         if(cvar("fraglimit"))
486         {
487                 padding = "";
488                 if(cvar("timelimit"))
489                         padding = "        ";
490                         //        " minutes"
491                 s = strcat(s, "\n^8frag limit: ^7", cvar_string("fraglimit"), padding);
492         }
493         if(cvar("timelimit"))
494                 s = strcat(s, "\n^8time limit: ^7", cvar_string("timelimit"), " minutes");
495
496         s = strzone(s);
497
498         centerprint(pl, s);
499         //sprint(pl, s);
500
501         strunzone(s);
502 }
503
504
505 void SetPlayerColors(entity pl, float _color)
506 {
507         /*string s;
508         s = ftos(cl);
509         stuffcmd(pl, strcat("color ", s, " ", s, "\n")  );
510         pl.team = cl + 1;
511         //pl.clientcolors = pl.clientcolors - (pl.clientcolors & 15) + cl;
512         pl.clientcolors = 16*cl + cl;*/
513
514         float pants, shirt;
515         pants = _color & 0x0F;
516         shirt = _color & 0xF0;
517
518
519         if(teamplay) {
520                 setcolor(pl, 16*pants + pants);
521         } else {
522                 setcolor(pl, shirt + pants);
523         }
524 }
525
526 void SetPlayerTeam(entity pl, float t, float s, float noprint)
527 {
528         float _color;
529
530         if(t == 4)
531                 _color = COLOR_TEAM4 - 1;
532         else if(t == 3)
533                 _color = COLOR_TEAM3 - 1;
534         else if(t == 2)
535                 _color = COLOR_TEAM2 - 1;
536         else
537                 _color = COLOR_TEAM1 - 1;
538
539         SetPlayerColors(pl,_color);
540
541         if(!noprint && t != s)
542         {
543                 //bprint(pl.netname, " has changed to ", TeamNoName(t), "\n");
544                 bprint(pl.netname, "^7 has changed from ", TeamNoName(s), " to ", TeamNoName(t), "\n");
545         }
546
547         if(t != s)
548                 LogTeamchange(pl);
549 }
550
551
552
553
554
555
556 // set c1...c4 to show what teams are allowed
557 void CheckAllowedTeams (entity for_whom)
558 {
559         string teament_name;
560         float dm;
561         entity head;
562
563 //      if(!dom && !ctf)
564 //              dm = 1;
565
566         c1 = c2 = c3 = c4 = -1;
567         cb1 = cb2 = cb3 = cb4 = 0;
568
569         // onslaught is special
570         if(g_onslaught)
571         {
572                 head = findchain(classname, "onslaught_generator");
573                 while (head)
574                 {
575                         if (head.team == COLOR_TEAM1) c1 = 0;
576                         if (head.team == COLOR_TEAM2) c2 = 0;
577                         if (head.team == COLOR_TEAM3) c3 = 0;
578                         if (head.team == COLOR_TEAM4) c4 = 0;
579                         head = head.chain;
580                 }
581                 return;
582         }
583
584         if(g_domination)
585                 teament_name = "dom_team";
586         else if(g_ctf)
587                 teament_name = "ctf_team";
588         else if(g_tdm)
589                 teament_name = "tdm_team";
590         else if(g_assault)
591         {
592                 c1 = c2 = 0; // Assault always has 2 teams
593                 return;
594         }
595         else
596         {
597                 // cover anything else by treating it like tdm with no teams spawned
598                 if(g_keyhunt)
599                         dm = kh_teams;
600                 else
601                         dm = cvar("g_tdm_teams");
602                 if(dm < 2)
603                         error("g_tdm_teams < 2, not enough teams to play team deathmatch\n");
604
605                 if(dm >= 4)
606                 {
607                         c1 = c2 = c3 = c4 = 0;
608                 }
609                 else if(dm >= 3)
610                 {
611                         c1 = c2 = c3 = 0;
612                 }
613                 else// if(dm >= 2)
614                 {
615                         c1 = c2 = 0;
616                 }
617                 return;
618         }
619
620         // first find out what teams are allowed
621         head = find(world, classname, teament_name);
622         while(head)
623         {
624                 if(!(g_domination && head.netname == ""))
625                 {
626                         if(head.team == COLOR_TEAM1)
627                         {
628                                 c1 = 0;
629                         }
630                         if(head.team == COLOR_TEAM2)
631                         {
632                                 c2 = 0;
633                         }
634                         if(head.team == COLOR_TEAM3)
635                         {
636                                 c3 = 0;
637                         }
638                         if(head.team == COLOR_TEAM4)
639                         {
640                                 c4 = 0;
641                         }
642                 }
643                 head = find(head, classname, teament_name);
644         }
645
646         if(cvar("bot_vs_human") > 0)
647         {
648                 // bots are all blue
649                 if(clienttype(for_whom) == CLIENTTYPE_BOT)
650                         c1 = c3 = c4 = -1;
651                 else
652                         c2 = -1;
653         }
654         else if(cvar("bot_vs_human") < 0)
655         {
656                 // bots are all red
657                 if(clienttype(for_whom) == CLIENTTYPE_BOT)
658                         c2 = c3 = c4 = -1;
659                 else
660                         c1 = -1;
661         }
662 }
663
664 float PlayerValue(entity p)
665 {
666         if(IsTeamBalanceForced() == 1)
667                 return 1;
668         return 1;
669 }
670
671 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
672 // teams that are allowed will now have their player counts stored in c1...c4
673 void GetTeamCounts(entity ignore)
674 {
675         entity head;
676         float value, bvalue;
677         // now count how many players are on each team already
678
679         // FIXME: also find and memorize the lowest-scoring bot on each team (in case players must be shuffled around)
680         // also remember the lowest-scoring player
681
682         FOR_EACH_PLAYER(head)
683         {
684                 if(head != ignore)// && head.netname != "")
685                 {
686                         value = PlayerValue(head);
687                         if(clienttype(head) == CLIENTTYPE_BOT)
688                                 bvalue = value;
689                         else
690                                 bvalue = 0;
691                         if(head.team == COLOR_TEAM1)
692                         {
693                                 if(c1 >= 0)
694                                 {
695                                         c1 = c1 + value;
696                                         cb1 = cb1 + bvalue;
697                                 }
698                         }
699                         if(head.team == COLOR_TEAM2)
700                         {
701                                 if(c2 >= 0)
702                                 {
703                                         c2 = c2 + value;
704                                         cb2 = cb2 + bvalue;
705                                 }
706                         }
707                         if(head.team == COLOR_TEAM3)
708                         {
709                                 if(c3 >= 0)
710                                 {
711                                         c3 = c3 + value;
712                                         cb3 = cb3 + bvalue;
713                                 }
714                         }
715                         if(head.team == COLOR_TEAM4)
716                         {
717                                 if(c4 >= 0)
718                                 {
719                                         c4 = c4 + value;
720                                         cb4 = cb4 + bvalue;
721                                 }
722                         }
723                 }
724         }
725 }
726
727 // returns # of smallest team (1, 2, 3, 4)
728 // NOTE: Assumes CheckAllowedTeams has already been called!
729 float FindSmallestTeam(entity pl, float ignore_pl)
730 {
731         float totalteams, smallestteam, smallestteam_count, smallestteam_score, balance_type;
732         totalteams = 0;
733
734         // find out what teams are available
735         //CheckAllowedTeams();
736
737         // make sure there are at least 2 teams to join
738         if(c1 >= 0)
739                 totalteams = totalteams + 1;
740         if(c2 >= 0)
741                 totalteams = totalteams + 1;
742         if(c3 >= 0)
743                 totalteams = totalteams + 1;
744         if(c4 >= 0)
745                 totalteams = totalteams + 1;
746
747         if(cvar("bot_vs_human"))
748                 totalteams += 1;
749
750         if(totalteams <= 1)
751         {
752                 if(g_domination)
753                         error("Too few teams available for domination\n");
754                 else if(g_ctf)
755                         error("Too few teams available for ctf\n");
756                 else if(g_keyhunt)
757                         error("Too few teams available for key hunt\n");
758                 else
759                         error("Too few teams available for team deathmatch\n");
760         }
761
762         // count how many players are in each team
763         if(ignore_pl)
764                 GetTeamCounts(pl);
765         else
766                 GetTeamCounts(world);
767
768         // c1...c4 now have counts of each team
769         // figure out which is smallest, giving priority to the team the player is already on as a tie-breaker
770
771         smallestteam = 0;
772         smallestteam_count = 999999999;
773         smallestteam_score = 999999999;
774
775         // 2 gives priority to what team you're already on, 1 goes in order
776         // 2 doesn't seem to work though...
777         balance_type = 1;
778
779         if(bots_would_leave)
780         //if(pl.classname != "player")
781         if(clienttype(pl) != CLIENTTYPE_BOT)
782         {
783                 c1 -= cb1 * 255.0/256;
784                 c2 -= cb2 * 255.0/256;
785                 c3 -= cb3 * 255.0/256;
786                 c4 -= cb4 * 255.0/256;
787         }
788
789         if(balance_type == 1)
790         {
791                 if(c1 >= 0 && (c1 < smallestteam_count || (c1 <= smallestteam_count && team1_score < smallestteam_score)))
792                 {
793                         smallestteam = 1;
794                         smallestteam_count = c1;
795                         smallestteam_score = team1_score;
796                 }
797                 if(c2 >= 0 && (c2 < smallestteam_count || (c2 <= smallestteam_count && team2_score < smallestteam_score)))
798                 {
799                         smallestteam = 2;
800                         smallestteam_count = c2;
801                         smallestteam_score = team2_score;
802                 }
803                 if(c3 >= 0 && (c3 < smallestteam_count || (c3 <= smallestteam_count && team3_score < smallestteam_score)))
804                 {
805                         smallestteam = 3;
806                         smallestteam_count = c3;
807                         smallestteam_score = team3_score;
808                 }
809                 if(c4 >= 0 && (c4 < smallestteam_count || (c4 <= smallestteam_count && team4_score < smallestteam_score)))
810                 {
811                         smallestteam = 4;
812                         smallestteam_count = c4;
813                         smallestteam_score = team4_score;
814                 }
815         }
816         else
817         {
818                 if(c1 >= 0 && (c1 < smallestteam_count ||
819                                         (c1 == smallestteam_count && self.team == COLOR_TEAM1) ) )
820                 {
821                         smallestteam = 1;
822                         smallestteam_count = c1;
823                 }
824                 if(c2 >= 0 && c2 < (c2 < smallestteam_count ||
825                                         (c2 == smallestteam_count && self.team == COLOR_TEAM2) ) )
826                 {
827                         smallestteam = 2;
828                         smallestteam_count = c2;
829                 }
830                 if(c3 >= 0 && c3 < (c3 < smallestteam_count ||
831                                         (c3 == smallestteam_count && self.team == COLOR_TEAM3) ) )
832                 {
833                         smallestteam = 3;
834                         smallestteam_count = c3;
835                 }
836                 if(c4 >= 0 && c4 < (c4 < smallestteam_count ||
837                                         (c4 == smallestteam_count && self.team == COLOR_TEAM4) ) )
838                 {
839                         smallestteam = 4;
840                         smallestteam_count = c4;
841                 }
842         }
843
844         return smallestteam;
845 }
846
847 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam)
848 {
849         float smallest, selectedteam;
850
851         // don't join a team if we're not playing a team game
852         if(!cvar("teamplay") && !g_domination && !g_ctf && !g_keyhunt)
853                 return 0;
854
855         // find out what teams are available
856         CheckAllowedTeams(pl);
857
858         if(g_domination)
859         {
860                 // <div0> WHY? TODO
861                 if(cvar("g_domination_default_teams") < 3)
862                         c3 = 999999999;
863                 if(cvar("g_domination_default_teams") < 4)
864                         c4 = 999999999;
865         }
866
867         // if we don't care what team he ends up on, put him on whatever team he entered as.
868         // if he's not on a valid team, then let other code put him on the smallest team
869         if(!forcebestteam)
870         {
871                 if(     c1 >= 0 && pl.team == COLOR_TEAM1)
872                         selectedteam = pl.team;
873                 else if(c2 >= 0 && pl.team == COLOR_TEAM2)
874                         selectedteam = pl.team;
875                 else if(c3 >= 0 && pl.team == COLOR_TEAM3)
876                         selectedteam = pl.team;
877                 else if(c4 >= 0 && pl.team == COLOR_TEAM4)
878                         selectedteam = pl.team;
879                 else
880                         selectedteam = -1;
881                 if(selectedteam > 0)
882                 {
883                         if(!only_return_best)
884                         {
885                                 SetPlayerColors(pl, selectedteam - 1);
886                                 LogTeamchange(pl);
887                         }
888                         return selectedteam;
889                 }
890                 // otherwise end up on the smallest team (handled below)
891         }
892
893         smallest = FindSmallestTeam(pl, TRUE);
894
895
896         if(!only_return_best)
897         {
898                 TeamchangeFrags(self);
899                 if(smallest == 1)
900                 {
901                         SetPlayerColors(pl, COLOR_TEAM1 - 1);
902                 }
903                 else if(smallest == 2)
904                 {
905                         SetPlayerColors(pl, COLOR_TEAM2 - 1);
906                 }
907                 else if(smallest == 3)
908                 {
909                         SetPlayerColors(pl, COLOR_TEAM3 - 1);
910                 }
911                 else if(smallest == 4)
912                 {
913                         SetPlayerColors(pl, COLOR_TEAM4 - 1);
914                 }
915                 else
916                 {
917                         error("smallest team: invalid team\n");
918                 }
919                 LogTeamchange(pl);
920                 if(pl.deadflag == DEAD_NO)
921                         Damage(pl, pl, pl, 100000, DEATH_TEAMCHANGE, pl.origin, '0 0 0');
922         }
923
924         return smallest;
925 }
926
927
928 void SV_ChangeTeam(float _color)
929 {
930         float scolor, dcolor, steam, dteam, dbotcount, scount, dcount;
931
932         // in normal deathmatch we can just apply the color and we're done
933         if(!cvar("teamplay")) {
934                 SetPlayerColors(self, _color);
935                 return;
936         }
937
938         scolor = self.clientcolors & 0x0F;
939         dcolor = _color & 0x0F;
940
941         if(scolor == COLOR_TEAM1 - 1)
942                 steam = 1;
943         else if(scolor == COLOR_TEAM2 - 1)
944                 steam = 2;
945         else if(scolor == COLOR_TEAM3 - 1)
946                 steam = 3;
947         else if(scolor == COLOR_TEAM4 - 1)
948                 steam = 4;
949         if(dcolor == COLOR_TEAM1 - 1)
950                 dteam = 1;
951         else if(dcolor == COLOR_TEAM2 - 1)
952                 dteam = 2;
953         else if(dcolor == COLOR_TEAM3 - 1)
954                 dteam = 3;
955         else if(dcolor == COLOR_TEAM4 - 1)
956                 dteam = 4;
957
958         CheckAllowedTeams(self);
959
960         if(dteam == 1 && c1 < 0) dteam = 4;
961         if(dteam == 4 && c4 < 0) dteam = 3;
962         if(dteam == 3 && c3 < 0) dteam = 2;
963         if(dteam == 2 && c2 < 0) dteam = 1;
964
965         // not changing teams
966         if(scolor == dcolor)
967         {
968                 //bprint("same team change\n");
969                 SetPlayerTeam(self, dteam, steam, TRUE);
970                 return;
971         }
972
973         if(cvar("teamplay"))
974         {
975                 if(cvar("g_campaign") || cvar("g_changeteam_banned"))
976                 {
977                         sprint(self, "Team changes not allowed\n");
978                         return; // changing teams is not allowed
979                 }
980
981                 if(!cvar("g_campaign") && cvar("g_balance_teams_prevent_imbalance"))
982                 {
983                         // only allow changing to a smaller or equal size team
984
985                         // find out what teams are available
986                         //CheckAllowedTeams();
987                         // count how many players on each team
988                         GetTeamCounts(world);
989
990                         // get desired team
991                         if(dteam == 1 && c1 >= 0)//dcolor == COLOR_TEAM1 - 1)
992                         {
993                                 dcount = c1;
994                                 dbotcount = cb1;
995                         }
996                         else if(dteam == 2 && c2 >= 0)//dcolor == COLOR_TEAM2 - 1)
997                         {
998                                 dcount = c2;
999                                 dbotcount = cb2;
1000                         }
1001                         else if(dteam == 3 && c3 >= 0)//dcolor == COLOR_TEAM3 - 1)
1002                         {
1003                                 dcount = c3;
1004                                 dbotcount = cb3;
1005                         }
1006                         else if(dteam == 4 && c4 >= 0)//dcolor == COLOR_TEAM4 - 1)
1007                         {
1008                                 dcount = c4;
1009                                 dbotcount = cb4;
1010                         }
1011                         else
1012                         {
1013                                 sprint(self, "Cannot change to an invalid team\n");
1014
1015                                 return;
1016                         }
1017
1018                         // get starting team
1019                         if(steam == 1)//scolor == COLOR_TEAM1 - 1)
1020                                 scount = c1;
1021                         else if(steam == 2)//scolor == COLOR_TEAM2 - 1)
1022                                 scount = c2;
1023                         else if(steam == 3)//scolor == COLOR_TEAM3 - 1)
1024                                 scount = c3;
1025                         else if(steam == 4)//scolor == COLOR_TEAM4 - 1)
1026                                 scount = c4;
1027
1028                         if(scount) // started at a valid, nonempty team
1029                         {
1030                                 // check if we're trying to change to a larger team that doens't have bots to swap with
1031                                 if(dcount >= scount && dbotcount <= 0)
1032                                 {
1033                                         sprint(self, "Cannot change to a larger team\n");
1034                                         return; // can't change to a larger team
1035                                 }
1036                         }
1037                 }
1038         }
1039
1040 //      bprint("allow change teams from ", ftos(steam), " to ", ftos(dteam), "\n");
1041
1042         if(cvar("teamplay") && self.classname == "player" && steam != dteam)
1043         {
1044                 // reduce frags during a team change
1045                 TeamchangeFrags(self);
1046         }
1047
1048         SetPlayerTeam(self, dteam, steam, FALSE);
1049
1050         if(cvar("teamplay") && self.classname == "player" && steam != dteam)
1051         {
1052                 // kill player when changing teams
1053                 if(self.deadflag == DEAD_NO)
1054                         Damage(self, self, self, 100000, DEATH_TEAMCHANGE, self.origin, '0 0 0');
1055         }
1056 }
1057
1058 void ShufflePlayerOutOfTeam (float source_team)
1059 {
1060         float smallestteam, smallestteam_count, steam;
1061         float lowest_bot_score, lowest_player_score;
1062         entity head, lowest_bot, lowest_player, selected;
1063
1064         smallestteam = 0;
1065         smallestteam_count = 999999999;
1066
1067         if(c1 >= 0 && c1 < smallestteam_count)
1068         {
1069                 smallestteam = 1;
1070                 smallestteam_count = c1;
1071         }
1072         if(c2 >= 0 && c2 < smallestteam_count)
1073         {
1074                 smallestteam = 2;
1075                 smallestteam_count = c2;
1076         }
1077         if(c3 >= 0 && c3 < smallestteam_count)
1078         {
1079                 smallestteam = 3;
1080                 smallestteam_count = c3;
1081         }
1082         if(c4 >= 0 && c4 < smallestteam_count)
1083         {
1084                 smallestteam = 4;
1085                 smallestteam_count = c4;
1086         }
1087
1088         if(!smallestteam)
1089         {
1090                 bprint("warning: no smallest team\n");
1091                 return;
1092         }
1093
1094         if(source_team == 1)
1095                 steam = COLOR_TEAM1;
1096         else if(source_team == 2)
1097                 steam = COLOR_TEAM2;
1098         else if(source_team == 3)
1099                 steam = COLOR_TEAM3;
1100         else if(source_team == 4)
1101                 steam = COLOR_TEAM4;
1102
1103         lowest_bot = world;
1104         lowest_bot_score = 999999999;
1105         lowest_player = world;
1106         lowest_player_score = 999999999;
1107
1108         // find the lowest-scoring player & bot of that team
1109         FOR_EACH_PLAYER(head)
1110         {
1111                 if(head.team == steam)
1112                 {
1113                         if(head.isbot)
1114                         {
1115                                 if(head.frags < lowest_bot_score)
1116                                 {
1117                                         lowest_bot = head;
1118                                         lowest_bot_score = head.frags;
1119                                 }
1120                         }
1121                         else
1122                         {
1123                                 if(head.frags < lowest_player_score)
1124                                 {
1125                                         lowest_player = head;
1126                                         lowest_player_score = head.frags;
1127                                 }
1128                         }
1129                 }
1130         }
1131
1132         // prefers to move a bot...
1133         if(lowest_bot != world)
1134                 selected = lowest_bot;
1135         // but it will move a player if it has to
1136         else
1137                 selected = lowest_player;
1138         // don't do anything if it couldn't find anyone
1139         if(!selected)
1140         {
1141                 bprint("warning: couldn't find a player to move from team\n");
1142                 return;
1143         }
1144
1145         // smallest team gains a member
1146         if(smallestteam == 1)
1147         {
1148                 c1 = c1 + 1;
1149         }
1150         else if(smallestteam == 2)
1151         {
1152                 c2 = c2 + 1;
1153         }
1154         else if(smallestteam == 3)
1155         {
1156                 c3 = c3 + 1;
1157         }
1158         else if(smallestteam == 4)
1159         {
1160                 c4 = c4 + 1;
1161         }
1162         else
1163         {
1164                 bprint("warning: destination team invalid\n");
1165                 return;
1166         }
1167         // source team loses a member
1168         if(source_team == 1)
1169         {
1170                 c1 = c1 + 1;
1171         }
1172         else if(source_team == 2)
1173         {
1174                 c2 = c2 + 2;
1175         }
1176         else if(source_team == 3)
1177         {
1178                 c3 = c3 + 3;
1179         }
1180         else if(source_team == 4)
1181         {
1182                 c4 = c4 + 4;
1183         }
1184         else
1185         {
1186                 bprint("warning: source team invalid\n");
1187                 return;
1188         }
1189
1190         // move the player to the new team
1191         TeamchangeFrags(selected);
1192         SetPlayerTeam(selected, smallestteam, source_team, FALSE);
1193
1194         if(selected.deadflag == DEAD_NO)
1195                 Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE, selected.origin, '0 0 0');
1196         centerprint(selected, strcat("You have been moved into a different team to improve team balance\nYou are now on: ", ColoredTeamName(selected.team)));
1197 }
1198
1199 float lastRebalanceInfo;
1200 void CauseRebalance(float source_team, float howmany_toomany)
1201 {
1202         float steam;
1203         entity head;
1204
1205         if(IsTeamBalanceForced() == 1)
1206         {
1207                 bprint("Rebalancing Teams\n");
1208                 ShufflePlayerOutOfTeam(source_team);
1209         }
1210         else
1211         {
1212                 if(howmany_toomany < cvar("g_balance_teams_complain"))
1213                         return;
1214                 if(time < lastRebalanceInfo + 90)
1215                         return;
1216                 lastRebalanceInfo = time;
1217                 if(source_team == 1)
1218                         steam = COLOR_TEAM1;
1219                 else if(source_team == 2)
1220                         steam = COLOR_TEAM2;
1221                 else if(source_team == 3)
1222                         steam = COLOR_TEAM3;
1223                 else if(source_team == 4)
1224                         steam = COLOR_TEAM4;
1225                 ServerConsoleEcho(strcat("Team ", ftos(source_team), " too large, complaining."), TRUE);
1226                 FOR_EACH_REALPLAYER(head)
1227                 {
1228                         if(head.team == steam)
1229                         {
1230                                 sprint(head, "\{1}\{13}^3SERVER NOTICE:^7 One of you please change teams!\n");
1231                                 centerprint_atprio(head, CENTERPRIO_REBALANCE, "^3SERVER NOTICE:\n\n^7Someone of you please change teams!");
1232                         }
1233                 }
1234         }
1235 }
1236
1237 // part of g_balance_teams_force
1238 // occasionally perform an audit of the teams to make
1239 // sure they're more or less balanced in player count.
1240 void AuditTeams()
1241 {
1242         float numplayers, numteams, smallest, toomany;
1243         float balance;
1244         balance = IsTeamBalanceForced();
1245         if(balance == 0)
1246                 return;
1247
1248         if(audit_teams_time > time)
1249                 return;
1250
1251         audit_teams_time = time + 4 + random();
1252
1253 //      bprint("Auditing teams\n");
1254
1255         CheckAllowedTeams(world);
1256         GetTeamCounts(world);
1257
1258
1259         numteams = numplayers = smallest = 0;
1260         if(c1 >= 0)
1261         {
1262                 numteams = numteams + 1;
1263                 numplayers = numplayers + c1;
1264                 smallest = c1;
1265         }
1266         if(c2 >= 0)
1267         {
1268                 numteams = numteams + 1;
1269                 numplayers = numplayers + c2;
1270                 if(c2 < smallest)
1271                         smallest = c2;
1272         }
1273         if(c3 >= 0)
1274         {
1275                 numteams = numteams + 1;
1276                 numplayers = numplayers + c3;
1277                 if(c3 < smallest)
1278                         smallest = c3;
1279         }
1280         if(c4 >= 0)
1281         {
1282                 numteams = numteams + 1;
1283                 numplayers = numplayers + c4;
1284                 if(c4 < smallest)
1285                         smallest = c4;
1286         }
1287
1288         if(numplayers <= 0)
1289                 return; // no players to move around
1290         if(numteams < 2)
1291                 return; // don't bother shuffling if for some reason there aren't any teams
1292
1293         toomany = smallest + 1;
1294
1295         if(c1 && c1 > toomany)
1296                 CauseRebalance(1, c1 - toomany);
1297         if(c2 && c2 > toomany)
1298                 CauseRebalance(2, c2 - toomany);
1299         if(c3 && c3 > toomany)
1300                 CauseRebalance(3, c3 - toomany);
1301         if(c4 && c4 > toomany)
1302                 CauseRebalance(4, c4 - toomany);
1303
1304         // if teams are still unbalanced, balance them further in the next audit,
1305         // which will happen sooner (keep doing rapid audits until things are in order)
1306         audit_teams_time = time + 0.7 + random()*0.3;
1307 }
1308
1309
1310
1311 /*void(entity e, float first) UpdateTeamScore =
1312 {
1313         clientno = e.FIXME;
1314         if(first)
1315         {
1316                 WriteByte (MSG_ALL, SVC_UPDATENAME);
1317                 WriteByte (MSG_ALL, clientno);
1318                 WriteString (MSG_ALL, e.netname);
1319
1320                 WriteByte (MSG_ALL, SVC_UPDATECOLORS);
1321                 WriteByte (MSG_ALL, clientno);
1322                 WriteByte (MSG_ALL, e.b_shirt * 16 + who.b_pants);
1323         }
1324
1325         WriteByte (MSG_ALL, SVC_UPDATEFRAGS);
1326         WriteByte (MSG_ALL, clientno);
1327         WriteShort (MSG_ALL, e.frags + 10000);
1328 };
1329
1330 */
1331
1332
1333 // code from here on is just to support maps that don't have team entities
1334 void tdm_spawnteam (string teamname, float teamcolor)
1335 {
1336         local entity e;
1337         e = spawn();
1338         e.classname = "tdm_team";
1339         e.netname = teamname;
1340         e.cnt = teamcolor;
1341         e.team = e.cnt + 1;
1342 };
1343
1344 // spawn some default teams if the map is not set up for tdm
1345 void() tdm_spawnteams =
1346 {
1347         float numteams;
1348
1349         numteams = cvar("g_tdm_teams");
1350
1351         tdm_spawnteam("Red", COLOR_TEAM1-1);
1352         tdm_spawnteam("Blue", COLOR_TEAM2-1);
1353         if(numteams >= 3)
1354                 tdm_spawnteam("Yellow", COLOR_TEAM3-1);
1355         if(numteams >= 4)
1356                 tdm_spawnteam("Pink", COLOR_TEAM4-1);
1357 };
1358
1359 void() tdm_delayedinit =
1360 {
1361         self.think = SUB_Remove;
1362         self.nextthink = time;
1363         // if no teams are found, spawn defaults
1364         if (find(world, classname, "tdm_team") == world)
1365                 tdm_spawnteams();
1366 };
1367
1368 void() tdm_init =
1369 {
1370         local entity e;
1371         e = spawn();
1372         e.think = tdm_delayedinit;
1373         e.nextthink = time + 0.1;
1374 };
1375
1376