]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/teamplay.qc
allow server admins to stop a running vote with 'sv_cmd vstop'.. not sure if it will...
[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(self.welcomemessage_time > time) return;
358         self.welcomemessage_time = time + self.cvar_scr_centertime * 0.6;
359
360         if(cvar("g_campaign"))
361         {
362                 centerprint(pl, campaign_message);
363                 return;
364         }
365
366         if(!self.button7)
367         {
368                 if(self.classname == "observer")
369                 {
370                         if(g_lms && self.frags <= 0 && self.frags > -666)
371                                 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"));
372                         else if(g_lms && self.frags == -666)
373                                 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"));
374                 }
375                 else if(self.classname == "spectator")
376                 {
377                         if ((g_lms && self.frags < 1) || g_arena)
378                                 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"));
379                         else
380                                 return centerprint_atprio(self, CENTERPRIO_SPAM, 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"));
381                 }
382         }
383
384         if(g_minstagib)
385                 mutator = "^2Minstagib ^1";
386         else if(g_instagib)
387                 mutator = "^2Instagib ^1";
388         else if(g_rocketarena)
389                 mutator = "^2Rocketarena ^1";
390         else if(g_nixnex)
391                 mutator = "^2No Items Nexuiz ^1";
392
393         if(g_midair) {
394                 // to protect against unheedingly made changes
395                 if (modifications) {
396                         modifications = strcat(modifications, ", ");
397                 }
398                 modifications = "midair";
399         }
400         if(g_vampire) {
401                 if (modifications) {
402                         modifications = strcat(modifications, ", ");
403                 }
404                 modifications = strcat(modifications, "vampire");
405         }
406         if(g_laserguided_missile) {
407                 if (modifications) {
408                         modifications = strcat(modifications, ", ");
409                 }
410                 modifications = strcat(modifications, "laser-guided-missiles");
411         }
412
413         local string versionmessage;
414         versionmessage = GetClientVersionMessage(self.version);
415
416         s = strcat(s, NEWLINES, "This is Nexuiz ", cvar_string("g_nexuizversion"), "\n", versionmessage);
417         s = strcat(s, "^8\n\nmatch type is ^1", mutator, gamemode_name, "^8\n");
418
419         if(modifications != "")
420                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
421
422         if(time < restart_countdown)
423                 s = strcat(s, "\n^1Game starts in ", ftos(ceil(restart_countdown-time)), " seconds^7");
424
425         s = strzone(s);
426
427         if (g_grappling_hook)
428                 s = strcat(s, "\n\n^8grappling hook is enabled, press 'e' to use it\n");
429
430         if(cache_lastmutatormsg != cvar_string("g_mutatormsg"))
431         {
432                 if(cache_lastmutatormsg)
433                         strunzone(cache_lastmutatormsg);
434                 if(cache_mutatormsg)
435                         strunzone(cache_mutatormsg);
436                 cache_lastmutatormsg = strzone(cvar_string("g_mutatormsg"));
437                 cache_mutatormsg = strzone(wordwrap(cache_lastmutatormsg, 50));
438         }
439
440         if (cache_mutatormsg != "") {
441                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
442         }
443         
444         if(cache_lastmotd != cvar_string("sv_motd"))
445         {
446                 if(cache_lastmotd)
447                         strunzone(cache_lastmotd);
448                 if(cache_motd)
449                         strunzone(cache_motd);
450                 cache_lastmotd = strzone(cvar_string("sv_motd"));
451                 cache_motd = strzone(wordwrap(cache_lastmotd, 50));
452         }
453
454         if (cache_motd != "") {
455                 s = strcat(s, "\n\n^8MOTD: ^7", cache_motd);
456         }
457
458         s = strcat(s, "\n");
459         if(cvar("fraglimit"))
460         {
461                 padding = "";
462                 if(cvar("timelimit"))
463                         padding = "        ";
464                         //        " minutes"
465                 s = strcat(s, "\n^8frag limit: ^7", cvar_string("fraglimit"), padding);
466         }
467         if(cvar("timelimit"))
468                 s = strcat(s, "\n^8time limit: ^7", cvar_string("timelimit"), " minutes");
469
470         s = strzone(s);
471
472         centerprint(pl, s);
473         //sprint(pl, s);
474
475         strunzone(s);
476 }
477
478
479 void SetPlayerColors(entity pl, float _color)
480 {
481         /*string s;
482         s = ftos(cl);
483         stuffcmd(pl, strcat("color ", s, " ", s, "\n")  );
484         pl.team = cl + 1;
485         //pl.clientcolors = pl.clientcolors - (pl.clientcolors & 15) + cl;
486         pl.clientcolors = 16*cl + cl;*/
487
488         float pants, shirt;
489         pants = _color & 0x0F;
490         shirt = _color & 0xF0;
491
492
493         if(teamplay) {
494                 setcolor(pl, 16*pants + pants);
495         } else {
496                 setcolor(pl, shirt + pants);
497         }
498 }
499
500 void SetPlayerTeam(entity pl, float t, float s, float noprint)
501 {
502         float _color;
503
504         if(t == 4)
505                 _color = COLOR_TEAM4 - 1;
506         else if(t == 3)
507                 _color = COLOR_TEAM3 - 1;
508         else if(t == 2)
509                 _color = COLOR_TEAM2 - 1;
510         else
511                 _color = COLOR_TEAM1 - 1;
512
513         SetPlayerColors(pl,_color);
514
515         if(!noprint && t != s)
516         {
517                 //bprint(pl.netname, " has changed to ", TeamNoName(t), "\n");
518                 bprint(pl.netname, "^7 has changed from ", TeamNoName(s), " to ", TeamNoName(t), "\n");
519         }
520
521         if(t != s)
522                 LogTeamchange(pl);
523 }
524
525
526
527
528
529
530 // set c1...c4 to show what teams are allowed
531 void CheckAllowedTeams (entity for_whom)
532 {
533         string teament_name;
534         float dm;
535         entity head;
536
537 //      if(!dom && !ctf)
538 //              dm = 1;
539
540         c1 = c2 = c3 = c4 = -1;
541         cb1 = cb2 = cb3 = cb4 = 0;
542
543         // onslaught is special
544         if(g_onslaught)
545         {
546                 head = findchain(classname, "onslaught_generator");
547                 while (head)
548                 {
549                         if (head.team == COLOR_TEAM1) c1 = 0;
550                         if (head.team == COLOR_TEAM2) c2 = 0;
551                         if (head.team == COLOR_TEAM3) c3 = 0;
552                         if (head.team == COLOR_TEAM4) c4 = 0;
553                         head = head.chain;
554                 }
555                 return;
556         }
557
558         if(g_domination)
559                 teament_name = "dom_team";
560         else if(g_ctf)
561                 teament_name = "ctf_team";
562         else if(g_tdm)
563                 teament_name = "tdm_team";
564         else if(g_assault)
565         {
566                 c1 = c2 = 0; // Assault always has 2 teams
567                 return;
568         }
569         else
570         {
571                 // cover anything else by treating it like tdm with no teams spawned
572                 if(g_keyhunt)
573                         dm = kh_teams;
574                 else
575                         dm = cvar("g_tdm_teams");
576                 if(dm < 2)
577                         error("g_tdm_teams < 2, not enough teams to play team deathmatch\n");
578
579                 if(dm >= 4)
580                 {
581                         c1 = c2 = c3 = c4 = 0;
582                 }
583                 else if(dm >= 3)
584                 {
585                         c1 = c2 = c3 = 0;
586                 }
587                 else// if(dm >= 2)
588                 {
589                         c1 = c2 = 0;
590                 }
591                 return;
592         }
593
594         // first find out what teams are allowed
595         head = find(world, classname, teament_name);
596         while(head)
597         {
598                 if(!(g_domination && head.netname == ""))
599                 {
600                         if(head.team == COLOR_TEAM1)
601                         {
602                                 c1 = 0;
603                         }
604                         if(head.team == COLOR_TEAM2)
605                         {
606                                 c2 = 0;
607                         }
608                         if(head.team == COLOR_TEAM3)
609                         {
610                                 c3 = 0;
611                         }
612                         if(head.team == COLOR_TEAM4)
613                         {
614                                 c4 = 0;
615                         }
616                 }
617                 head = find(head, classname, teament_name);
618         }
619
620         if(cvar("bot_vs_human") > 0)
621         {
622                 // bots are all blue
623                 if(clienttype(for_whom) == CLIENTTYPE_BOT)
624                         c1 = c3 = c4 = -1;
625                 else
626                         c2 = -1;
627         }
628         else if(cvar("bot_vs_human") < 0)
629         {
630                 // bots are all red
631                 if(clienttype(for_whom) == CLIENTTYPE_BOT)
632                         c2 = c3 = c4 = -1;
633                 else
634                         c1 = -1;
635         }
636 }
637
638 float PlayerValue(entity p)
639 {
640         if(IsTeamBalanceForced() == 1)
641                 return 1;
642         return 1;
643 }
644
645 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
646 // teams that are allowed will now have their player counts stored in c1...c4
647 void GetTeamCounts(entity ignore)
648 {
649         entity head;
650         float value, bvalue;
651         // now count how many players are on each team already
652
653         // FIXME: also find and memorize the lowest-scoring bot on each team (in case players must be shuffled around)
654         // also remember the lowest-scoring player
655
656         FOR_EACH_PLAYER(head)
657         {
658                 if(head != ignore)// && head.netname != "")
659                 {
660                         value = PlayerValue(head);
661                         if(clienttype(head) == CLIENTTYPE_BOT)
662                                 bvalue = value;
663                         else
664                                 bvalue = 0;
665                         if(head.team == COLOR_TEAM1)
666                         {
667                                 if(c1 >= 0)
668                                 {
669                                         c1 = c1 + value;
670                                         cb1 = cb1 + bvalue;
671                                 }
672                         }
673                         if(head.team == COLOR_TEAM2)
674                         {
675                                 if(c2 >= 0)
676                                 {
677                                         c2 = c2 + value;
678                                         cb2 = cb2 + bvalue;
679                                 }
680                         }
681                         if(head.team == COLOR_TEAM3)
682                         {
683                                 if(c3 >= 0)
684                                 {
685                                         c3 = c3 + value;
686                                         cb3 = cb3 + bvalue;
687                                 }
688                         }
689                         if(head.team == COLOR_TEAM4)
690                         {
691                                 if(c4 >= 0)
692                                 {
693                                         c4 = c4 + value;
694                                         cb4 = cb4 + bvalue;
695                                 }
696                         }
697                 }
698         }
699 }
700
701 // returns # of smallest team (1, 2, 3, 4)
702 // NOTE: Assumes CheckAllowedTeams has already been called!
703 float FindSmallestTeam(entity pl, float ignore_pl)
704 {
705         float totalteams, smallestteam, smallestteam_count, smallestteam_score, balance_type;
706         totalteams = 0;
707
708         // find out what teams are available
709         //CheckAllowedTeams();
710
711         // make sure there are at least 2 teams to join
712         if(c1 >= 0)
713                 totalteams = totalteams + 1;
714         if(c2 >= 0)
715                 totalteams = totalteams + 1;
716         if(c3 >= 0)
717                 totalteams = totalteams + 1;
718         if(c4 >= 0)
719                 totalteams = totalteams + 1;
720
721         if(cvar("bot_vs_human"))
722                 totalteams += 1;
723
724         if(totalteams <= 1)
725         {
726                 if(g_domination)
727                         error("Too few teams available for domination\n");
728                 else if(g_ctf)
729                         error("Too few teams available for ctf\n");
730                 else if(g_keyhunt)
731                         error("Too few teams available for key hunt\n");
732                 else
733                         error("Too few teams available for team deathmatch\n");
734         }
735
736
737         // count how many players are in each team
738         if(ignore_pl)
739                 GetTeamCounts(pl);
740         else
741                 GetTeamCounts(world);
742
743         // c1...c4 now have counts of each team
744         // figure out which is smallest, giving priority to the team the player is already on as a tie-breaker
745
746         smallestteam = 0;
747         smallestteam_count = 999999999;
748         smallestteam_score = 999999999;
749
750         // 2 gives priority to what team you're already on, 1 goes in order
751         // 2 doesn't seem to work though...
752         balance_type = 1;
753
754         if(bots_would_leave)
755         //if(pl.classname != "player")
756         if(clienttype(pl) != CLIENTTYPE_BOT)
757         {
758                 c1 -= cb1 * 255.0/256;
759                 c2 -= cb2 * 255.0/256;
760                 c3 -= cb3 * 255.0/256;
761                 c4 -= cb4 * 255.0/256;
762         }
763
764         if(balance_type == 1)
765         {
766                 if(c1 >= 0 && (c1 < smallestteam_count || (c1 <= smallestteam_count && team1_score < smallestteam_score)))
767                 {
768                         smallestteam = 1;
769                         smallestteam_count = c1;
770                         smallestteam_score = team1_score;
771                 }
772                 if(c2 >= 0 && (c2 < smallestteam_count || (c2 <= smallestteam_count && team2_score < smallestteam_score)))
773                 {
774                         smallestteam = 2;
775                         smallestteam_count = c2;
776                         smallestteam_score = team2_score;
777                 }
778                 if(c3 >= 0 && (c3 < smallestteam_count || (c3 <= smallestteam_count && team3_score < smallestteam_score)))
779                 {
780                         smallestteam = 3;
781                         smallestteam_count = c3;
782                         smallestteam_score = team3_score;
783                 }
784                 if(c4 >= 0 && (c4 < smallestteam_count || (c4 <= smallestteam_count && team4_score < smallestteam_score)))
785                 {
786                         smallestteam = 4;
787                         smallestteam_count = c4;
788                         smallestteam_score = team4_score;
789                 }
790         }
791         else
792         {
793                 if(c1 >= 0 && (c1 < smallestteam_count ||
794                                         (c1 == smallestteam_count && self.team == COLOR_TEAM1) ) )
795                 {
796                         smallestteam = 1;
797                         smallestteam_count = c1;
798                 }
799                 if(c2 >= 0 && c2 < (c2 < smallestteam_count ||
800                                         (c2 == smallestteam_count && self.team == COLOR_TEAM2) ) )
801                 {
802                         smallestteam = 2;
803                         smallestteam_count = c2;
804                 }
805                 if(c3 >= 0 && c3 < (c3 < smallestteam_count ||
806                                         (c3 == smallestteam_count && self.team == COLOR_TEAM3) ) )
807                 {
808                         smallestteam = 3;
809                         smallestteam_count = c3;
810                 }
811                 if(c4 >= 0 && c4 < (c4 < smallestteam_count ||
812                                         (c4 == smallestteam_count && self.team == COLOR_TEAM4) ) )
813                 {
814                         smallestteam = 4;
815                         smallestteam_count = c4;
816                 }
817         }
818
819         return smallestteam;
820 }
821
822 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam)
823 {
824         float smallest, selectedteam;
825
826         // don't join a team if we're not playing a team game
827         if(!cvar("teamplay") && !g_domination && !g_ctf && !g_keyhunt)
828                 return 0;
829
830         // find out what teams are available
831         CheckAllowedTeams(pl);
832
833         if(g_domination)
834         {
835                 if(cvar("g_domination_default_teams") < 3)
836                         c3 = 999999999;
837                 if(cvar("g_domination_default_teams") < 4)
838                         c4 = 999999999;
839         }
840
841         // if we don't care what team he ends up on, put him on whatever team he entered as.
842         // if he's not on a valid team, then let other code put him on the smallest team
843         if(!forcebestteam)
844         {
845                 if(     c1 >= 0 && pl.team == COLOR_TEAM1)
846                         selectedteam = pl.team;
847                 else if(c2 >= 0 && pl.team == COLOR_TEAM2)
848                         selectedteam = pl.team;
849                 else if(c3 >= 0 && pl.team == COLOR_TEAM3)
850                         selectedteam = pl.team;
851                 else if(c4 >= 0 && pl.team == COLOR_TEAM4)
852                         selectedteam = pl.team;
853                 else
854                         selectedteam = -1;
855                 if(selectedteam > 0)
856                 {
857                         if(!only_return_best)
858                         {
859                                 SetPlayerColors(pl, selectedteam - 1);
860                                 LogTeamchange(pl);
861                         }
862                         return selectedteam;
863                 }
864                 // otherwise end up on the smallest team (handled below)
865         }
866
867         smallest = FindSmallestTeam(pl, TRUE);
868
869
870         if(!only_return_best)
871         {
872                 TeamchangeFrags(self);
873                 if(smallest == 1)
874                 {
875                         SetPlayerColors(pl, COLOR_TEAM1 - 1);
876                 }
877                 else if(smallest == 2)
878                 {
879                         SetPlayerColors(pl, COLOR_TEAM2 - 1);
880                 }
881                 else if(smallest == 3)
882                 {
883                         SetPlayerColors(pl, COLOR_TEAM3 - 1);
884                 }
885                 else if(smallest == 4)
886                 {
887                         SetPlayerColors(pl, COLOR_TEAM4 - 1);
888                 }
889                 else
890                 {
891                         error("smallest team: invalid team\n");
892                 }
893                 LogTeamchange(pl);
894                 if(pl.deadflag == DEAD_NO)
895                         Damage(pl, pl, pl, 100000, DEATH_TEAMCHANGE, pl.origin, '0 0 0');
896         }
897
898         return smallest;
899 }
900
901
902 void SV_ChangeTeam(float _color)
903 {
904         float scolor, dcolor, steam, dteam, dbotcount, scount, dcount;
905
906         // in normal deathmatch we can just apply the color and we're done
907         if(!cvar("teamplay")) {
908                 SetPlayerColors(self, _color);
909                 return;
910         }
911
912         scolor = self.clientcolors & 0x0F;
913         dcolor = _color & 0x0F;
914
915         if(scolor == COLOR_TEAM1 - 1)
916                 steam = 1;
917         else if(scolor == COLOR_TEAM2 - 1)
918                 steam = 2;
919         else if(scolor == COLOR_TEAM3 - 1)
920                 steam = 3;
921         else if(scolor == COLOR_TEAM4 - 1)
922                 steam = 4;
923         if(dcolor == COLOR_TEAM1 - 1)
924                 dteam = 1;
925         else if(dcolor == COLOR_TEAM2 - 1)
926                 dteam = 2;
927         else if(dcolor == COLOR_TEAM3 - 1)
928                 dteam = 3;
929         else if(dcolor == COLOR_TEAM4 - 1)
930                 dteam = 4;
931
932         CheckAllowedTeams(self);
933
934         if(dteam == 1 && c1 < 0) dteam = 4;
935         if(dteam == 4 && c4 < 0) dteam = 3;
936         if(dteam == 3 && c3 < 0) dteam = 2;
937         if(dteam == 2 && c2 < 0) dteam = 1;
938
939         // not changing teams
940         if(scolor == dcolor)
941         {
942                 //bprint("same team change\n");
943                 SetPlayerTeam(self, dteam, steam, TRUE);
944                 return;
945         }
946
947         if(cvar("teamplay"))
948         {
949                 if(cvar("g_campaign") || cvar("g_changeteam_banned"))
950                 {
951                         sprint(self, "Team changes not allowed\n");
952                         return; // changing teams is not allowed
953                 }
954
955                 if(!cvar("g_campaign") && cvar("g_balance_teams_prevent_imbalance"))
956                 {
957                         // only allow changing to a smaller or equal size team
958
959                         // find out what teams are available
960                         //CheckAllowedTeams();
961                         // count how many players on each team
962                         GetTeamCounts(world);
963
964                         // get desired team
965                         if(dteam == 1 && c1 >= 0)//dcolor == COLOR_TEAM1 - 1)
966                         {
967                                 dcount = c1;
968                                 dbotcount = cb1;
969                         }
970                         else if(dteam == 2 && c2 >= 0)//dcolor == COLOR_TEAM2 - 1)
971                         {
972                                 dcount = c2;
973                                 dbotcount = cb2;
974                         }
975                         else if(dteam == 3 && c3 >= 0)//dcolor == COLOR_TEAM3 - 1)
976                         {
977                                 dcount = c3;
978                                 dbotcount = cb3;
979                         }
980                         else if(dteam == 4 && c4 >= 0)//dcolor == COLOR_TEAM4 - 1)
981                         {
982                                 dcount = c4;
983                                 dbotcount = cb4;
984                         }
985                         else
986                         {
987                                 sprint(self, "Cannot change to an invalid team\n");
988
989                                 return;
990                         }
991
992                         // get starting team
993                         if(steam == 1)//scolor == COLOR_TEAM1 - 1)
994                                 scount = c1;
995                         else if(steam == 2)//scolor == COLOR_TEAM2 - 1)
996                                 scount = c2;
997                         else if(steam == 3)//scolor == COLOR_TEAM3 - 1)
998                                 scount = c3;
999                         else if(steam == 4)//scolor == COLOR_TEAM4 - 1)
1000                                 scount = c4;
1001
1002                         if(scount) // started at a valid, nonempty team
1003                         {
1004                                 // check if we're trying to change to a larger team that doens't have bots to swap with
1005                                 if(dcount >= scount && dbotcount <= 0)
1006                                 {
1007                                         sprint(self, "Cannot change to a larger team\n");
1008                                         return; // can't change to a larger team
1009                                 }
1010                         }
1011                 }
1012         }
1013
1014 //      bprint("allow change teams from ", ftos(steam), " to ", ftos(dteam), "\n");
1015
1016         if(cvar("teamplay") && self.classname == "player" && steam != dteam)
1017         {
1018                 // reduce frags during a team change
1019                 TeamchangeFrags(self);
1020         }
1021
1022         SetPlayerTeam(self, dteam, steam, FALSE);
1023
1024         if(cvar("teamplay") && self.classname == "player" && steam != dteam)
1025         {
1026                 // kill player when changing teams
1027                 if(self.deadflag == DEAD_NO)
1028                         Damage(self, self, self, 100000, DEATH_TEAMCHANGE, self.origin, '0 0 0');
1029         }
1030 }
1031
1032 void ShufflePlayerOutOfTeam (float source_team)
1033 {
1034         float smallestteam, smallestteam_count, steam;
1035         float lowest_bot_score, lowest_player_score;
1036         entity head, lowest_bot, lowest_player, selected;
1037
1038         smallestteam = 0;
1039         smallestteam_count = 999999999;
1040
1041         if(c1 >= 0 && c1 < smallestteam_count)
1042         {
1043                 smallestteam = 1;
1044                 smallestteam_count = c1;
1045         }
1046         if(c2 >= 0 && c2 < smallestteam_count)
1047         {
1048                 smallestteam = 2;
1049                 smallestteam_count = c2;
1050         }
1051         if(c3 >= 0 && c3 < smallestteam_count)
1052         {
1053                 smallestteam = 3;
1054                 smallestteam_count = c3;
1055         }
1056         if(c4 >= 0 && c4 < smallestteam_count)
1057         {
1058                 smallestteam = 4;
1059                 smallestteam_count = c4;
1060         }
1061
1062         if(!smallestteam)
1063         {
1064                 bprint("warning: no smallest team\n");
1065                 return;
1066         }
1067
1068         if(source_team == 1)
1069                 steam = COLOR_TEAM1;
1070         else if(source_team == 2)
1071                 steam = COLOR_TEAM2;
1072         else if(source_team == 3)
1073                 steam = COLOR_TEAM3;
1074         else if(source_team == 4)
1075                 steam = COLOR_TEAM4;
1076
1077         lowest_bot = world;
1078         lowest_bot_score = 999999999;
1079         lowest_player = world;
1080         lowest_player_score = 999999999;
1081
1082         // find the lowest-scoring player & bot of that team
1083         FOR_EACH_PLAYER(head)
1084         {
1085                 if(head.team == steam)
1086                 {
1087                         if(head.isbot)
1088                         {
1089                                 if(head.frags < lowest_bot_score)
1090                                 {
1091                                         lowest_bot = head;
1092                                         lowest_bot_score = head.frags;
1093                                 }
1094                         }
1095                         else
1096                         {
1097                                 if(head.frags < lowest_player_score)
1098                                 {
1099                                         lowest_player = head;
1100                                         lowest_player_score = head.frags;
1101                                 }
1102                         }
1103                 }
1104         }
1105
1106         // prefers to move a bot...
1107         if(lowest_bot != world)
1108                 selected = lowest_bot;
1109         // but it will move a player if it has to
1110         else
1111                 selected = lowest_player;
1112         // don't do anything if it couldn't find anyone
1113         if(!selected)
1114         {
1115                 bprint("warning: couldn't find a player to move from team\n");
1116                 return;
1117         }
1118
1119         // smallest team gains a member
1120         if(smallestteam == 1)
1121         {
1122                 c1 = c1 + 1;
1123         }
1124         else if(smallestteam == 2)
1125         {
1126                 c2 = c2 + 1;
1127         }
1128         else if(smallestteam == 3)
1129         {
1130                 c3 = c3 + 1;
1131         }
1132         else if(smallestteam == 4)
1133         {
1134                 c4 = c4 + 1;
1135         }
1136         else
1137         {
1138                 bprint("warning: destination team invalid\n");
1139                 return;
1140         }
1141         // source team loses a member
1142         if(source_team == 1)
1143         {
1144                 c1 = c1 + 1;
1145         }
1146         else if(source_team == 2)
1147         {
1148                 c2 = c2 + 2;
1149         }
1150         else if(source_team == 3)
1151         {
1152                 c3 = c3 + 3;
1153         }
1154         else if(source_team == 4)
1155         {
1156                 c4 = c4 + 4;
1157         }
1158         else
1159         {
1160                 bprint("warning: source team invalid\n");
1161                 return;
1162         }
1163
1164         // move the player to the new team
1165         TeamchangeFrags(selected);
1166         SetPlayerTeam(selected, smallestteam, source_team, FALSE);
1167
1168         if(selected.deadflag == DEAD_NO)
1169                 Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE, selected.origin, '0 0 0');
1170         centerprint(selected, strcat("You have been moved into a different team to improve team balance\nYou are now on: ", ColoredTeamName(selected.team)));
1171 }
1172
1173 float lastRebalanceInfo;
1174 void CauseRebalance(float source_team, float howmany_toomany)
1175 {
1176         float steam;
1177         entity head;
1178
1179         if(IsTeamBalanceForced() == 1)
1180         {
1181                 bprint("Rebalancing Teams\n");
1182                 ShufflePlayerOutOfTeam(source_team);
1183         }
1184         else
1185         {
1186                 if(howmany_toomany < cvar("g_balance_teams_complain"))
1187                         return;
1188                 if(time < lastRebalanceInfo + 90)
1189                         return;
1190                 lastRebalanceInfo = time;
1191                 if(source_team == 1)
1192                         steam = COLOR_TEAM1;
1193                 else if(source_team == 2)
1194                         steam = COLOR_TEAM2;
1195                 else if(source_team == 3)
1196                         steam = COLOR_TEAM3;
1197                 else if(source_team == 4)
1198                         steam = COLOR_TEAM4;
1199                 ServerConsoleEcho(strcat("Team ", ftos(source_team), " too large, complaining."), TRUE);
1200                 FOR_EACH_REALPLAYER(head)
1201                 {
1202                         if(head.team == steam)
1203                         {
1204                                 sprint(head, "\{1}\{13}^3SERVER NOTICE:^7 One of you please change teams!\n");
1205                                 centerprint_atprio(head, CENTERPRIO_REBALANCE, "^3SERVER NOTICE:\n\n^7Someone of you please change teams!");
1206                         }
1207                 }
1208         }
1209 }
1210
1211 // part of g_balance_teams_force
1212 // occasionally perform an audit of the teams to make
1213 // sure they're more or less balanced in player count.
1214 void AuditTeams()
1215 {
1216         float numplayers, numteams, smallest, toomany;
1217         float balance;
1218         balance = IsTeamBalanceForced();
1219         if(balance == 0)
1220                 return;
1221
1222         if(audit_teams_time > time)
1223                 return;
1224
1225         audit_teams_time = time + 4 + random();
1226
1227 //      bprint("Auditing teams\n");
1228
1229         CheckAllowedTeams(world);
1230         GetTeamCounts(world);
1231
1232
1233         numteams = numplayers = smallest = 0;
1234         if(c1 >= 0)
1235         {
1236                 numteams = numteams + 1;
1237                 numplayers = numplayers + c1;
1238                 smallest = c1;
1239         }
1240         if(c2 >= 0)
1241         {
1242                 numteams = numteams + 1;
1243                 numplayers = numplayers + c2;
1244                 if(c2 < smallest)
1245                         smallest = c2;
1246         }
1247         if(c3 >= 0)
1248         {
1249                 numteams = numteams + 1;
1250                 numplayers = numplayers + c3;
1251                 if(c3 < smallest)
1252                         smallest = c3;
1253         }
1254         if(c4 >= 0)
1255         {
1256                 numteams = numteams + 1;
1257                 numplayers = numplayers + c4;
1258                 if(c4 < smallest)
1259                         smallest = c4;
1260         }
1261
1262         if(numplayers <= 0)
1263                 return; // no players to move around
1264         if(numteams < 2)
1265                 return; // don't bother shuffling if for some reason there aren't any teams
1266
1267         toomany = smallest + 1;
1268
1269         if(c1 && c1 > toomany)
1270                 CauseRebalance(1, c1 - toomany);
1271         if(c2 && c2 > toomany)
1272                 CauseRebalance(2, c2 - toomany);
1273         if(c3 && c3 > toomany)
1274                 CauseRebalance(3, c3 - toomany);
1275         if(c4 && c4 > toomany)
1276                 CauseRebalance(4, c4 - toomany);
1277
1278         // if teams are still unbalanced, balance them further in the next audit,
1279         // which will happen sooner (keep doing rapid audits until things are in order)
1280         audit_teams_time = time + 0.7 + random()*0.3;
1281 }
1282
1283
1284
1285 /*void(entity e, float first) UpdateTeamScore =
1286 {
1287         clientno = e.FIXME;
1288         if(first)
1289         {
1290                 WriteByte (MSG_ALL, SVC_UPDATENAME);
1291                 WriteByte (MSG_ALL, clientno);
1292                 WriteString (MSG_ALL, e.netname);
1293
1294                 WriteByte (MSG_ALL, SVC_UPDATECOLORS);
1295                 WriteByte (MSG_ALL, clientno);
1296                 WriteByte (MSG_ALL, e.b_shirt * 16 + who.b_pants);
1297         }
1298
1299         WriteByte (MSG_ALL, SVC_UPDATEFRAGS);
1300         WriteByte (MSG_ALL, clientno);
1301         WriteShort (MSG_ALL, e.frags + 10000);
1302 };
1303
1304 */
1305
1306
1307 // code from here on is just to support maps that don't have team entities
1308 void tdm_spawnteam (string teamname, float teamcolor)
1309 {
1310         local entity e;
1311         e = spawn();
1312         e.classname = "tdm_team";
1313         e.netname = teamname;
1314         e.cnt = teamcolor;
1315         e.team = e.cnt + 1;
1316 };
1317
1318 // spawn some default teams if the map is not set up for tdm
1319 void() tdm_spawnteams =
1320 {
1321         float numteams;
1322
1323         numteams = cvar("g_tdm_teams");
1324
1325         tdm_spawnteam("Red", COLOR_TEAM1-1);
1326         tdm_spawnteam("Blue", COLOR_TEAM2-1);
1327         if(numteams >= 3)
1328                 tdm_spawnteam("Yellow", COLOR_TEAM3-1);
1329         if(numteams >= 4)
1330                 tdm_spawnteam("Pink", COLOR_TEAM4-1);
1331 };
1332
1333 void() tdm_delayedinit =
1334 {
1335         self.think = SUB_Remove;
1336         self.nextthink = time;
1337         // if no teams are found, spawn defaults
1338         if (find(world, classname, "tdm_team") == world)
1339                 tdm_spawnteams();
1340 };
1341
1342 void() tdm_init =
1343 {
1344         local entity e;
1345         e = spawn();
1346         e.think = tdm_delayedinit;
1347         e.nextthink = time + 0.1;
1348 };
1349
1350