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