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