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