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