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