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