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