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