]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/teamplay.qc
fixed out-of-range g_maplist_position causing runaway loop
[divverent/nexuiz.git] / data / qcsrc / server / teamplay.qc
1 float GAME_DEATHMATCH           = 1;
2 float GAME_TEAM_DEATHMATCH      = 2;
3 float GAME_DOMINATION           = 3;
4 float GAME_CTF                  = 4;
5 float GAME_RUNEMATCH            = 5;
6 float GAME_LMS                  = 6;
7 float GAME_ARENA                = 7;
8
9
10 // client counts for each team
11 float c1, c2, c3, c4;
12 // # of bots on those teams
13 float cb1, cb2, cb3, cb4;
14
15 float g_domination, g_ctf, g_tdm;
16
17 float audit_teams_time;
18
19 void TeamchangeFrags(entity e)
20 {
21         if(e.classname == "player")
22         {
23                 // reduce frags during a team change
24                 DistributeFragsAmongTeam(e, (e.clientcolors & 0x0F) + 1, 1 - cvar("g_changeteam_fragtransfer") / 100);
25         }
26 }
27
28 string TeamName(float t)
29 {
30         // fixme: Search for team entities and get their .netname's!
31         if(t == COLOR_TEAM1)
32                 return "Red Team";
33         if(t == COLOR_TEAM2)
34                 return "Blue Team";
35         if(t == COLOR_TEAM3)
36                 return "Pink Team";
37         if(t == COLOR_TEAM4)
38                 return "Yellow Team";
39         return "Neutral Team";
40 }
41 string ColoredTeamName(float t)
42 {
43         // fixme: Search for team entities and get their .netname's!
44         if(t == COLOR_TEAM1)
45                 return "^1Red Team^7";
46         if(t == COLOR_TEAM2)
47                 return "^4Blue Team^7";
48         if(t == COLOR_TEAM3)
49                 return "^6Pink Team^7";
50         if(t == COLOR_TEAM4)
51                 return "^3Yellow Team^7";
52         return "Neutral Team";
53 }
54 string TeamNoName(float t)
55 {
56         // fixme: Search for team entities and get their .netname's!
57         if(t == 1)
58                 return "Red Team";
59         if(t == 2)
60                 return "Blue Team";
61         if(t == 3)
62                 return "Pink Team";
63         if(t == 4)
64                 return "Yellow Team";
65         return "Neutral Team";
66 }
67
68 void dom_init();
69 void ctf_init();
70 void runematch_init();
71 void tdm_init();
72
73 void(entity pl) LogTeamchange =
74 {
75         string str;
76         if(!cvar("sv_eventlog"))
77                 return;
78         if(pl.playerid < 1)
79                 return;
80         str = strcat(":team:", ftos(pl.playerid), ":");
81         str = strcat(str, ftos(pl.team));
82         GameLogEcho(str, FALSE);
83 }
84
85 void ResetGameCvars()
86 {
87         cvar_set("g_tdm", "0");
88         cvar_set("g_domination", "0");
89         cvar_set("g_ctf", "0");
90         cvar_set("g_runematch", "0");
91         cvar_set("g_lms", "0");
92         cvar_set("g_arena", "0");
93         cvar_set("teamplay", "0");
94
95
96         cvar_set("exit_cfg", "");
97 }
98
99 void ActivateTeamplay()
100 {
101         float teamplay_default;
102         teamplay_default = cvar("teamplay_default");
103
104         if(teamplay_default)
105                 cvar_set("teamplay", ftos(teamplay_default));
106         else
107                 cvar_set("teamplay", "3");
108 }
109
110 void InitGameplayMode()
111 {
112         float fraglimit_override, timelimit_override;
113
114         VoteReset();
115
116         game = cvar ("gamecfg");        // load game options
117
118         // game cvars get reset before map changes
119         // then map's cfg sets them as desired
120
121         // FIXME: also set a message or game mode name to print to players when the join
122
123         // set both here, gamemode can override it later
124         timelimit_override = cvar("timelimit_override");
125         fraglimit_override = cvar("fraglimit_override");
126
127         if(game == GAME_DOMINATION || cvar("g_domination"))
128         {
129                 ResetGameCvars();
130                 game = GAME_DOMINATION;
131                 cvar_set("g_domination", "1");
132
133                 ActivateTeamplay();
134
135                 fraglimit_override = cvar("g_domination_point_limit");
136
137                 gamemode_name = "Domination";
138                 teams_matter = 1;
139         }
140         else if(game == GAME_CTF || cvar("g_ctf"))
141         {
142                 ResetGameCvars();
143                 game = GAME_CTF;
144                 cvar_set("g_ctf", "1");
145
146                 ActivateTeamplay();
147
148                 fraglimit_override = cvar("g_ctf_capture_limit");
149
150                 gamemode_name = "Capture the Flag";
151                 teams_matter = 1;
152         }
153         else if((game == GAME_RUNEMATCH || cvar("g_runematch")) && !cvar("g_minstagib"))
154         {
155                 game = GAME_RUNEMATCH;
156                 cvar_set("g_runematch", "1");
157
158                 if(cvar("deathmatch_force_teamplay"))
159                         ActivateTeamplay();
160
161                 fraglimit_override = cvar("g_runematch_point_limit");
162
163                 gamemode_name = "Rune Match";
164                 if(cvar("teamplay"))
165                         teams_matter = 1;
166                 else
167                         teams_matter = 0;
168         }
169         else if(game == GAME_DEATHMATCH || game == GAME_TEAM_DEATHMATCH || cvar("g_tdm"))
170         {
171                 if(!cvar("deathmatch"))
172                         cvar_set("deathmatch", "1");
173
174
175                 if(game == GAME_TEAM_DEATHMATCH || cvar("g_tdm") || cvar("deathmatch_force_teamplay"))
176                 {
177                         ResetGameCvars();
178                         game = GAME_TEAM_DEATHMATCH;
179                         gamemode_name = "Team Deathmatch";
180                         ActivateTeamplay();
181                         teams_matter = 1;
182                         cvar_set("g_tdm", "1");
183                 }
184                 else
185                 {
186                         ResetGameCvars();
187                         game = GAME_DEATHMATCH;
188                         gamemode_name = "Deathmatch";
189                         teams_matter = 0;
190                 }
191
192                 fraglimit_override = cvar("fraglimit_override");
193         }
194         else if(game == GAME_LMS || cvar("g_lms"))
195         {
196                 ResetGameCvars();
197                 game = GAME_LMS;
198                 cvar_set("g_lms", "1");
199                 fraglimit_override = cvar("g_lms_lives_override");
200                 if(fraglimit_override == 0)
201                         fraglimit_override = -1;
202                 gamemode_name = "Last Man Standing";
203                 teams_matter = 0;
204                 lms_lowest_lives = 999;
205         }
206         else if(game == GAME_ARENA || cvar("g_arena"))
207         {
208                 ResetGameCvars();
209                 game = GAME_ARENA;
210                 cvar_set("g_arena", "1");
211                 fraglimit_override = cvar("g_arena_point_limit");
212                 maxspawned = cvar("g_arena_maxspawned");
213                 if(maxspawned < 2)
214                         maxspawned = 2;
215                 arena_roundbased = cvar("g_arena_roundbased");
216                 gamemode_name = "Arena";
217                 teams_matter = 0;
218         }
219         else
220         {
221                 // we can only assume...
222                 ResetGameCvars();
223                 gamemode_name = "Deathmatch";
224                 teams_matter = 0;
225         }
226 /*      else if(game == GAME_TEAM_DEATHMATCH)
227         {
228                 if(!cvar("deathmatch"))
229                         cvar_set("deathmatch", "1");
230
231                 //if(!cvar("teamplay"))
232                 //      cvar_set("teamplay", "3");
233                 ActivateTeamplay();
234
235                 fraglimit_override = cvar("fraglimit_override");
236         }*/
237
238         // enforce the server's universal frag/time limits
239         if(!cvar("g_campaign"))
240         {
241                 if(fraglimit_override >= 0)
242                         cvar_set("fraglimit", ftos(fraglimit_override));
243                 if(timelimit_override >= 0)
244                         cvar_set("timelimit", ftos(timelimit_override));
245         }
246
247         if (game == GAME_DOMINATION)//cvar("g_domination"))
248                 dom_init();
249         else if (game == GAME_CTF)//cvar("g_ctf"))
250                 ctf_init();
251         else if (game == GAME_RUNEMATCH)//cvar("g_runematch"))
252                 runematch_init();
253         else if (game == GAME_TEAM_DEATHMATCH)//cvar("g_runematch"))
254                 tdm_init();
255
256         // those mutators rule each other out
257         if(cvar("g_minstagib"))
258         {
259                 cvar_set("g_instagib", "0");
260                 cvar_set("g_rocketarena", "0");
261         }
262         if(cvar("g_instagib"))
263         {
264                 cvar_set("g_minstagib", "0");
265                 cvar_set("g_rocketarena", "0");
266         }
267         if(cvar("g_rocketarena"))
268         {
269                 cvar_set("g_instagib", "0");
270                 cvar_set("g_minstagib", "0");
271         }
272
273         registercvar("_motd", "");
274         registercvar("_mutatormsg", "");
275         cvar_set("_motd", wordwrap(cvar_string("sv_motd"), 50));
276         cvar_set("_mutatormsg", wordwrap(cvar_string("g_mutatormsg"), 50));
277
278         g_domination = cvar("g_domination");
279         g_ctf = cvar("g_ctf");
280         g_tdm = cvar("g_tdm");
281 }
282
283 string GetClientVersionMessage(float v) {
284         local string versionmsg;
285         if (v == 1) {
286                 versionmsg = "^1client is too old to get versioninfo.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nUPDATE!!! (http://www.nexuiz.com)^8";
287                 // either that or someone wants to be funny
288         } else if (v != cvar("gameversion")) {
289                 if(v < cvar("gameversion")) {
290                         versionmsg = "^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8";
291                 } else {
292                         versionmsg = "^3This server is using an outdated Nexuiz version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8";
293                 }
294         } else {
295                 versionmsg = "^2client version and server version are compatible.^8";
296         }
297         return strzone(versionmsg);
298
299 }
300
301
302 void PrintWelcomeMessage(entity pl)
303 {
304         string s, mutator, modifications, padding;
305
306         /*if(self.welcomemessage_time < time)
307                 return;
308         if(self.welcomemessage_time2 > time)
309                 return;
310         self.welcomemessage_time2 = time + 0.8; */
311
312         if(self.classname == "observer")
313         {
314                 if(cvar("g_lms") && self.frags <= 0 && self.frags > -666)
315                         return centermsg_setall(strcat(newlines, "^1You have no more lives left\nwait for next round\n\n\n^7press attack to spectate other players"));
316                 else if(cvar("g_lms") && self.frags == -666)
317                         return centermsg_setall(strcat(newlines, "^1Match has already begun\nwait for next round\n\n\n^7press attack to spectate other players"));
318         }
319         else if(self.classname == "spectator")
320         {
321                 if ((cvar("g_lms") && self.frags < 1) || cvar("g_arena"))
322                         return centermsg_setall(strcat(newlines, "spectating ", self.enemy.netname, "\n\n\n^7press attack for next player\npress attack2 for free fly mode"));
323                 else
324                         return centermsg_setall(strcat(newlines, "spectating ", self.enemy.netname, "\n\n\n^7press jump to play\n^7press attack for next player\npress attack2 for free fly mode"));
325         }
326
327
328         if(self.welcomemessage_time2 > time) return;
329         self.welcomemessage_time2 = time + 1.0;
330
331         if(cvar("g_campaign"))
332         {
333                 centermsg_setallfor(pl, campaign_message);
334                 return;
335         }
336
337         if(cvar("g_minstagib"))
338                 mutator = "^2Minstagib ^1";
339         else if(cvar("g_instagib"))
340                 mutator = "^2Instagib ^1";
341         else if(cvar("g_rocketarena"))
342                 mutator = "^2Rocketarena ^1";
343         else if(cvar("g_nixnex"))
344                 mutator = "^2No Items Nexuiz ^1";
345
346         if(cvar("g_midair")) {
347                 // to protect against unheedingly made changes
348                 if (modifications) {
349                         modifications = strcat(modifications, ", ");
350                 }
351                 modifications = "midair";
352         }
353         if(cvar("g_vampire")) {
354                 if (modifications) {
355                         modifications = strcat(modifications, ", ");
356                 }
357                 modifications = strcat(modifications, "vampire");
358         }
359         if(cvar("g_laserguided_missile")) {
360                 if (modifications) {
361                         modifications = strcat(modifications, ", ");
362                 }
363                 modifications = strcat(modifications, "laser-guided-missiles");
364         }
365
366         local string versionmessage;
367         versionmessage = GetClientVersionMessage(self.version);
368
369         s = strcat(s, newlines, "This is Nexuiz ", cvar_string("g_nexuizversion"), "\n", versionmessage);
370         s = strcat(s, "^8\n\nmatch type is ^1", mutator, gamemode_name, "^8\n");
371
372         if(modifications != "")
373                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
374
375         if((self.classname == "observer" || self.classname == "spectator") && self.version == cvar("gameversion")) {
376                 if(!cvar("g_arena"))
377                         s = strcat(s,"^7\n\n\npress jump to play\npress attack to spectate other players\n\n");
378                 else if(player_count < 2 && arena_roundbased)
379                 {
380                         s = strcat(s, "\n\n\n^1waiting for second player to start match^7\n\n");
381                 }
382                 else
383                 {
384                         s = strcat(s, "\n\n\n");
385                         if(champion)
386                                 s = strcat(s, "^7current champion is: ", champion.netname, "\n\n");
387                         s = strcat(s,"^7press attack to spectate other players\n\n");
388                 }
389         }
390
391
392         s = strzone(s);
393
394         if (cvar("g_grappling_hook"))
395                 s = strcat(s, "\n\n^8grappling hook is enabled, press 'e' to use it\n");
396
397         if (cvar_string("_mutatormsg") != "") {
398                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cvar_string("_mutatormsg"));
399         }
400
401         if (cvar_string("_motd") != "") {
402                 s = strcat(s, "\n\n^8MOTD: ^7", cvar_string("_motd"));
403         }
404
405         s = strcat(s, "\n");
406         if(cvar("fraglimit"))
407         {
408                 padding = "";
409                 if(cvar("timelimit"))
410                         padding = "        ";
411                         //        " minutes"
412                 s = strcat(s, "\n^8frag limit: ^7", cvar_string("fraglimit"), padding);
413         }
414         if(cvar("timelimit"))
415                 s = strcat(s, "\n^8time limit: ^7", cvar_string("timelimit"), " minutes");
416
417         s = strzone(s);
418
419         centermsg_setallfor(pl, s);
420         //sprint(pl, s);
421
422         strunzone(s);
423 }
424
425
426 void SetPlayerColors(entity pl, float _color)
427 {
428         /*string s;
429         s = ftos(cl);
430         stuffcmd(pl, strcat("color ", s, " ", s, "\n")  );
431         pl.team = cl + 1;
432         //pl.clientcolors = pl.clientcolors - (pl.clientcolors & 15) + cl;
433         pl.clientcolors = 16*cl + cl;*/
434
435         float pants, shirt;
436         pants = _color & 0x0F;
437         shirt = _color & 0xF0;
438
439
440         if(teamplay) {
441                 setcolor(pl, 16*pants + pants);
442         } else {
443                 setcolor(pl, shirt + pants);
444         }
445 }
446
447 void SetPlayerTeam(entity pl, float t, float s, float noprint)
448 {
449         float _color;
450
451         if(t == 4)
452                 _color = COLOR_TEAM4 - 1;
453         else if(t == 3)
454                 _color = COLOR_TEAM3 - 1;
455         else if(t == 2)
456                 _color = COLOR_TEAM2 - 1;
457         else
458                 _color = COLOR_TEAM1 - 1;
459
460         SetPlayerColors(pl,_color);
461
462         if(!noprint && t != s)
463         {
464                 //bprint(strcat(pl.netname, " has changed to ", TeamNoName(t), "\n"));
465                 bprint(strcat(pl.netname, "^7 has changed from ", TeamNoName(s), " to ", TeamNoName(t), "\n"));
466         }
467
468         if(t != s)
469                 LogTeamchange(pl);
470 }
471
472
473
474
475
476
477 // set c1...c4 to show what teams are allowed
478 void CheckAllowedTeams ()
479 {
480         string teament_name;
481         float dm;
482         entity head;
483
484 //      if(!dom && !ctf)
485 //              dm = 1;
486
487         c1 = c2 = c3 = c4 = -1;
488         cb1 = cb2 = cb3 = cb4 = 0;
489
490         if(g_domination)
491                 teament_name = "dom_team";
492         else if(g_ctf)
493                 teament_name = "ctf_team";
494         else if(g_tdm)
495                 teament_name = "tdm_team";
496         else
497         {
498                 // cover anything else by treating it like tdm with no teams spawned
499                 dm = cvar("g_tdm_teams");
500                 if(dm < 2)
501                         error("g_tdm_teams < 2, not enough teams to play team deathmatch\n");
502
503                 if(dm >= 4)
504                 {
505                         c1 = c2 = c3 = c4 = 0;
506                 }
507                 else if(dm >= 3)
508                 {
509                         c1 = c2 = c3 = 0;
510                 }
511                 else// if(dm >= 2)
512                 {
513                         c1 = c2 = 0;
514                 }
515                 return;
516         }
517
518         // first find out what teams are allowed
519         head = find(world, classname, teament_name);
520         while(head)
521         {
522                 if(!(g_domination && head.netname == ""))
523                 {
524                         if(head.team == COLOR_TEAM1)
525                         {
526                                 c1 = 0;
527                         }
528                         if(head.team == COLOR_TEAM2)
529                         {
530                                 c2 = 0;
531                         }
532                         if(head.team == COLOR_TEAM3)
533                         {
534                                 c3 = 0;
535                         }
536                         if(head.team == COLOR_TEAM4)
537                         {
538                                 c4 = 0;
539                         }
540                 }
541                 head = find(head, classname, teament_name);
542         }
543 }
544
545 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
546 // teams that are allowed will now have their player counts stored in c1...c4
547 void GetTeamCounts(entity ignore)
548 {
549         entity head;
550         // now count how many players are on each team already
551
552         // FIXME: also find and memorize the lowest-scoring bot on each team (in case players must be shuffled around)
553         // also remember the lowest-scoring player
554
555         head = find(world, classname, "player");
556         while(head)
557         {
558                 if(head != ignore)// && head.netname != "")
559                 {
560                         if(head.team == COLOR_TEAM1)
561                         {
562                                 if(c1 >= 0)
563                                 {
564                                         c1 = c1 + 1;
565                                         cb1 = cb1 + 1;
566                                 }
567                         }
568                         if(head.team == COLOR_TEAM2)
569                         {
570                                 if(c2 >= 0)
571                                 {
572                                         c2 = c2 + 1;
573                                         cb2 = cb2 + 1;
574                                 }
575                         }
576                         if(head.team == COLOR_TEAM3)
577                         {
578                                 if(c3 >= 0)
579                                 {
580                                         c3 = c3 + 1;
581                                         cb3 = cb3 + 1;
582                                 }
583                         }
584                         if(head.team == COLOR_TEAM4)
585                         {
586                                 if(c4 >= 0)
587                                 {
588                                         c4 = c4 + 1;
589                                         cb4 = cb4 + 1;
590                                 }
591                         }
592                 }
593                 head = find(head, classname, "player");
594         }
595 }
596
597 // returns # of smallest team (1, 2, 3, 4)
598 // NOTE: Assumes CheckAllowedTeams has already been called!
599 float FindSmallestTeam(entity pl, float ignore_pl)
600 {
601         float totalteams, smallestteam, smallestteam_count, balance_type;
602         totalteams = 0;
603
604         // find out what teams are available
605         //CheckAllowedTeams();
606
607         // make sure there are at least 2 teams to join
608         if(c1 >= 0)
609                 totalteams = totalteams + 1;
610         if(c2 >= 0)
611                 totalteams = totalteams + 1;
612         if(c3 >= 0)
613                 totalteams = totalteams + 1;
614         if(c4 >= 0)
615                 totalteams = totalteams + 1;
616
617         if(totalteams <= 1)
618         {
619                 if(g_domination)
620                         error("Too few teams available for domination\n");
621                 else if(g_ctf)
622                         error("Too few teams available for ctf\n");
623                 else
624                         error("Too few teams available for team deathmatch\n");
625         }
626
627
628         // count how many players are in each team
629         if(ignore_pl)
630                 GetTeamCounts(pl);
631         else
632                 GetTeamCounts(world);
633
634         // c1...c4 now have counts of each team
635         // figure out which is smallest, giving priority to the team the player is already on as a tie-breaker
636
637         smallestteam = 0;
638         smallestteam_count = 999;
639
640         // 2 gives priority to what team you're already on, 1 goes in order
641         // 2 doesn't seem to work though...
642         balance_type = 1;
643
644         if(balance_type == 1)
645         {
646                 if(c1 >= 0 && c1 < smallestteam_count)
647                 {
648                         smallestteam = 1;
649                         smallestteam_count = c1;
650                 }
651                 if(c2 >= 0 && c2 < smallestteam_count)
652                 {
653                         smallestteam = 2;
654                         smallestteam_count = c2;
655                 }
656                 if(c3 >= 0 && c3 < smallestteam_count)
657                 {
658                         smallestteam = 3;
659                         smallestteam_count = c3;
660                 }
661                 if(c4 >= 0 && c4 < smallestteam_count)
662                 {
663                         smallestteam = 4;
664                         smallestteam_count = c4;
665                 }
666         }
667         else
668         {
669                 if(c1 >= 0 && (c1 < smallestteam_count ||
670                                         (c1 == smallestteam_count && self.team == COLOR_TEAM1) ) )
671                 {
672                         smallestteam = 1;
673                         smallestteam_count = c1;
674                 }
675                 if(c2 >= 0 && c2 < (c2 < smallestteam_count ||
676                                         (c2 == smallestteam_count && self.team == COLOR_TEAM2) ) )
677                 {
678                         smallestteam = 2;
679                         smallestteam_count = c2;
680                 }
681                 if(c3 >= 0 && c3 < (c3 < smallestteam_count ||
682                                         (c3 == smallestteam_count && self.team == COLOR_TEAM3) ) )
683                 {
684                         smallestteam = 3;
685                         smallestteam_count = c3;
686                 }
687                 if(c4 >= 0 && c4 < (c4 < smallestteam_count ||
688                                         (c4 == smallestteam_count && self.team == COLOR_TEAM4) ) )
689                 {
690                         smallestteam = 4;
691                         smallestteam_count = c4;
692                 }
693         }
694
695         return smallestteam;
696 }
697
698 float JoinBestTeam(entity pl, float only_return_best)
699 {
700         float smallest, selectedteam;
701
702         // don't join a team if we're not playing a team game
703         if(!cvar("teamplay") && !g_domination && !g_ctf)
704                 return 0;
705
706         // find out what teams are available
707         CheckAllowedTeams();
708
709         if(cvar("g_domination"))
710         {
711                 if(cvar("g_domination_default_teams") < 3)
712                         c3 = 9999;
713                 if(cvar("g_domination_default_teams") < 4)
714                         c4 = 9999;
715         }
716
717         // if we don't care what team he ends up on, put him on whatever team he entered as.
718         // if he's not on a valid team, then let other code put him on the smallest team
719         if(!cvar("g_campaign") && !cvar("g_balance_teams") && !cvar("g_balance_teams_force"))
720         {
721                 if(     c1 >= 0 && pl.team == COLOR_TEAM1)
722                         selectedteam = pl.team;
723                 else if(c2 >= 0 && pl.team == COLOR_TEAM2)
724                         selectedteam = pl.team;
725                 else if(c3 >= 0 && pl.team == COLOR_TEAM3)
726                         selectedteam = pl.team;
727                 else if(c4 >= 0 && pl.team == COLOR_TEAM4)
728                         selectedteam = pl.team;
729                 else
730                         selectedteam = -1;
731                 if(selectedteam > 0)
732                 {
733                         if(!only_return_best)
734                         {
735                                 SetPlayerColors(pl, selectedteam - 1);
736                                 LogTeamchange(pl);
737                         }
738                         return selectedteam;
739                 }
740                 // otherwise end up on the smallest team (handled below)
741         }
742
743         smallest = FindSmallestTeam(pl, TRUE);
744
745
746         if(!only_return_best)
747         {
748                 TeamchangeFrags(self);
749                 if(smallest == 1)
750                 {
751                         SetPlayerColors(pl, COLOR_TEAM1 - 1);
752                 }
753                 else if(smallest == 2)
754                 {
755                         SetPlayerColors(pl, COLOR_TEAM2 - 1);
756                 }
757                 else if(smallest == 3)
758                 {
759                         SetPlayerColors(pl, COLOR_TEAM3 - 1);
760                 }
761                 else if(smallest == 4)
762                 {
763                         SetPlayerColors(pl, COLOR_TEAM4 - 1);
764                 }
765                 else
766                 {
767                         error("smallest team: invalid team\n");
768                 }
769                 LogTeamchange(pl);
770                 if(pl.deadflag == DEAD_NO)
771                         Damage(pl, pl, pl, 100000, DEATH_TEAMCHANGE, pl.origin, '0 0 0');
772         }
773
774         return smallest;
775 }
776
777
778 void SV_ChangeTeam(float _color)
779 {
780         float scolor, dcolor, steam, dteam, dbotcount, scount, dcount;
781
782         // in normal deathmatch we can just apply the color and we're done
783         if(!cvar("teamplay")) {
784                 SetPlayerColors(self, _color);
785                 return;
786         }
787
788         scolor = self.clientcolors & 0x0F;
789         dcolor = _color & 0x0F;
790
791         if(scolor == COLOR_TEAM1 - 1)
792                 steam = 1;
793         else if(scolor == COLOR_TEAM2 - 1)
794                 steam = 2;
795         else if(scolor == COLOR_TEAM3 - 1)
796                 steam = 3;
797         else if(scolor == COLOR_TEAM4 - 1)
798                 steam = 4;
799         if(dcolor == COLOR_TEAM1 - 1)
800                 dteam = 1;
801         else if(dcolor == COLOR_TEAM2 - 1)
802                 dteam = 2;
803         else if(dcolor == COLOR_TEAM3 - 1)
804                 dteam = 3;
805         else if(dcolor == COLOR_TEAM4 - 1)
806                 dteam = 4;
807
808         // remap invalid teams in dom & ctf
809         /*
810         if(cvar("g_ctf") && dteam == 3)
811                 dteam = 2;
812         else if(cvar("g_ctf") && dteam == 4)
813                 dteam = 1;
814         else if((cvar("g_domination") && cvar("g_domination_default_teams") < 3) || (cvar("g_tdm") && cvar("g_tdm_teams") < 3))
815         {
816                 if(dteam == 3)
817                         dteam = 2;
818                 else if(dteam == 4)
819                         dteam = 1;
820         }
821         else if((cvar("g_domination") && cvar("g_domination_default_teams") < 4) || (cvar("g_tdm") && cvar("g_tdm_teams") < 4))
822         {
823                 if(dteam == 4)
824                         dteam = 1;
825         }
826         */
827
828         CheckAllowedTeams();
829         if(dteam == 3 && c3 < 0)
830                 dteam = 2;
831         if(dteam == 4 && c4 < 0)
832                 dteam = 1;
833
834         // not changing teams
835         if(scolor == dcolor)
836         {
837                 //bprint("same team change\n");
838                 SetPlayerTeam(self, dteam, steam, TRUE);
839                 return;
840         }
841
842         if(cvar("teamplay"))
843         {
844                 if(cvar("g_campaign") || cvar("g_changeteam_banned"))
845                 {
846                         sprint(self, "Team changes not allowed\n");
847                         return; // changing teams is not allowed
848                 }
849
850                 if(!cvar("g_campaign") && cvar("g_balance_teams_prevent_imbalance"))
851                 {
852                         // only allow changing to a smaller or equal size team
853
854                         // find out what teams are available
855                         CheckAllowedTeams();
856                         // count how many players on each team
857                         GetTeamCounts(world);
858
859                         // get desired team
860                         if(dteam == 1 && c1 >= 0)//dcolor == COLOR_TEAM1 - 1)
861                         {
862                                 dcount = c1;
863                                 dbotcount = cb1;
864                         }
865                         else if(dteam == 2 && c2 >= 0)//dcolor == COLOR_TEAM2 - 1)
866                         {
867                                 dcount = c2;
868                                 dbotcount = cb2;
869                         }
870                         else if(dteam == 3 && c3 >= 0)//dcolor == COLOR_TEAM3 - 1)
871                         {
872                                 dcount = c3;
873                                 dbotcount = cb3;
874                         }
875                         else if(dteam == 4 && c4 >= 0)//dcolor == COLOR_TEAM4 - 1)
876                         {
877                                 dcount = c4;
878                                 dbotcount = cb4;
879                         }
880                         else
881                         {
882                                 sprint(self, "Cannot change to an invalid team\n");
883
884                                 return;
885                         }
886
887                         // get starting team
888                         if(steam == 1)//scolor == COLOR_TEAM1 - 1)
889                                 scount = c1;
890                         else if(steam == 2)//scolor == COLOR_TEAM2 - 1)
891                                 scount = c2;
892                         else if(steam == 3)//scolor == COLOR_TEAM3 - 1)
893                                 scount = c3;
894                         else if(steam == 4)//scolor == COLOR_TEAM4 - 1)
895                                 scount = c4;
896
897                         if(scount) // started at a valid, nonempty team
898                         {
899                                 // check if we're trying to change to a larger team that doens't have bots to swap with
900                                 if(dcount >= scount && dbotcount <= 0)
901                                 {
902                                         sprint(self, "Cannot change to a larger team\n");
903                                         return; // can't change to a larger team
904                                 }
905                         }
906                 }
907         }
908
909 //      bprint(strcat("allow change teams from ", ftos(steam), " to ", ftos(dteam), "\n"));
910
911         if(cvar("teamplay") && self.classname == "player" && steam != dteam)
912         {
913                 // reduce frags during a team change
914                 TeamchangeFrags(self);
915         }
916
917         SetPlayerTeam(self, dteam, steam, FALSE);
918
919         if(cvar("teamplay") && self.classname == "player" && steam != dteam)
920         {
921                 // kill player when changing teams
922                 if(self.deadflag == DEAD_NO)
923                         Damage(self, self, self, 100000, DEATH_TEAMCHANGE, self.origin, '0 0 0');
924         }
925 }
926
927 void ShufflePlayerOutOfTeam (float source_team)
928 {
929         float smallestteam, smallestteam_count, steam;
930         float lowest_bot_score, lowest_player_score;
931         entity head, lowest_bot, lowest_player, selected;
932         string m;
933
934         smallestteam = 0;
935         smallestteam_count = 999;
936
937         if(c1 >= 0 && c1 < smallestteam_count)
938         {
939                 smallestteam = 1;
940                 smallestteam_count = c1;
941         }
942         if(c2 >= 0 && c2 < smallestteam_count)
943         {
944                 smallestteam = 2;
945                 smallestteam_count = c2;
946         }
947         if(c3 >= 0 && c3 < smallestteam_count)
948         {
949                 smallestteam = 3;
950                 smallestteam_count = c3;
951         }
952         if(c4 >= 0 && c4 < smallestteam_count)
953         {
954                 smallestteam = 4;
955                 smallestteam_count = c4;
956         }
957
958         if(!smallestteam)
959         {
960                 bprint("warning: no smallest team\n");
961                 return;
962         }
963
964         if(source_team == 1)
965                 steam = COLOR_TEAM1;
966         else if(source_team == 2)
967                 steam = COLOR_TEAM2;
968         else if(source_team == 3)
969                 steam = COLOR_TEAM3;
970         else if(source_team == 4)
971                 steam = COLOR_TEAM4;
972
973         lowest_bot = world;
974         lowest_bot_score = 9999;
975         lowest_player = world;
976         lowest_player_score = 9999;
977
978         // find the lowest-scoring player & bot of that team
979         head = find(world, classname, "player");
980         while(head)
981         {
982                 if(head.team == steam)
983                 {
984                         if(head.isbot)
985                         {
986                                 if(head.frags < lowest_bot_score)
987                                 {
988                                         lowest_bot = head;
989                                         lowest_bot_score = head.frags;
990                                 }
991                         }
992                         else
993                         {
994                                 if(head.frags < lowest_player_score)
995                                 {
996                                         lowest_player = head;
997                                         lowest_player_score = head.frags;
998                                 }
999                         }
1000                 }
1001                 head = find(head, classname, "player");
1002         }
1003
1004         // prefers to move a bot...
1005         if(lowest_bot != world)
1006                 selected = lowest_bot;
1007         // but it will move a player if it has to
1008         else
1009                 selected = lowest_player;
1010         // don't do anything if it couldn't find anyone
1011         if(!selected)
1012         {
1013                 bprint("warning: couldn't find a player to move from team\n");
1014                 return;
1015         }
1016
1017         // smallest team gains a member
1018         if(smallestteam == 1)
1019         {
1020                 c1 = c1 + 1;
1021         }
1022         else if(smallestteam == 2)
1023         {
1024                 c2 = c2 + 1;
1025         }
1026         else if(smallestteam == 3)
1027         {
1028                 c3 = c3 + 1;
1029         }
1030         else if(smallestteam == 4)
1031         {
1032                 c4 = c4 + 1;
1033         }
1034         else
1035         {
1036                 bprint("warning: destination team invalid\n");
1037                 return;
1038         }
1039         // source team loses a member
1040         if(source_team == 1)
1041         {
1042                 c1 = c1 + 1;
1043         }
1044         else if(source_team == 2)
1045         {
1046                 c2 = c2 + 2;
1047         }
1048         else if(source_team == 3)
1049         {
1050                 c3 = c3 + 3;
1051         }
1052         else if(source_team == 4)
1053         {
1054                 c4 = c4 + 4;
1055         }
1056         else
1057         {
1058                 bprint("warning: source team invalid\n");
1059                 return;
1060         }
1061
1062         // move the player to the new team
1063         SetPlayerTeam(selected, smallestteam, source_team, FALSE);
1064
1065         if(selected.deadflag == DEAD_NO)
1066                         Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE, selected.origin, '0 0 0');
1067         /*
1068         m = "You have been moved into a different team to improve team balance\nYou are now on: ";
1069         if (selected.team == 5)
1070                 m = strcat(m, "^1Red Team");
1071         else if (selected.team == 14)
1072                 m = strcat(m, "^4Blue Team");
1073         else if (selected.team == 10)
1074                 m = strcat(m, "^6Pink Team");
1075         else if (selected.team == 13)
1076                 m = strcat(m, "^3Yellow Team");
1077         centerprint(selected, m);
1078         */
1079 }
1080
1081 // part of g_balance_teams_force
1082 // occasionally perform an audit of the teams to make
1083 // sure they're more or less balanced in player count.
1084 void AuditTeams()
1085 {
1086         float numplayers, numteams, average;
1087         if(cvar("g_campaign"))
1088                 return;
1089         if(!cvar("g_balance_teams_force"))
1090                 return;
1091         if(!cvar("teamplay"))
1092                 return;
1093
1094         if(audit_teams_time > time)
1095                 return;
1096
1097         audit_teams_time = time + 4 + random();
1098
1099 //      bprint("Auditing teams\n");
1100
1101         CheckAllowedTeams();
1102         GetTeamCounts(world);
1103
1104
1105         numteams = numplayers = 0;
1106         if(c1 >= 0)
1107         {
1108                 numteams = numteams + 1;
1109                 numplayers = numplayers + c1;
1110         }
1111         if(c2 >= 0)
1112         {
1113                 numteams = numteams + 1;
1114                 numplayers = numplayers + c2;
1115         }
1116         if(c3 >= 0)
1117         {
1118                 numteams = numteams + 1;
1119                 numplayers = numplayers + c3;
1120         }
1121         if(c4 >= 0)
1122         {
1123                 numteams = numteams + 1;
1124                 numplayers = numplayers + c4;
1125         }
1126
1127         if(numplayers <= 0)
1128                 return; // no players to move around
1129         if(numteams < 2)
1130                 return; // don't bother shuffling if for some reason there aren't any teams
1131
1132         average = ceil(numplayers / numteams);
1133
1134         if(average <= 0)
1135                 return; // that's weird...
1136
1137         if(c1 && c1 > average)
1138         {
1139                 bprint("Rebalancing Teams\n");
1140                 //bprint("Shuffle from team 1\n");
1141                 ShufflePlayerOutOfTeam(1);
1142         }
1143         if(c2 && c2 > average)
1144         {
1145                 bprint("Rebalancing Teams\n");
1146                 //bprint("Shuffle from team 2\n");
1147                 ShufflePlayerOutOfTeam(2);
1148         }
1149         if(c3 && c3 > average)
1150         {
1151                 bprint("Rebalancing Teams\n");
1152                 //bprint("Shuffle from team 3\n");
1153                 ShufflePlayerOutOfTeam(3);
1154         }
1155         if(c4 && c4 > average)
1156         {
1157                 bprint("Rebalancing Teams\n");
1158                 //bprint("Shuffle from team 4\n");
1159                 ShufflePlayerOutOfTeam(4);
1160         }
1161
1162         // if teams are still unbalanced, balance them further in the next audit,
1163         // which will happen sooner (keep doing rapid audits until things are in order)
1164         audit_teams_time = time + 0.7 + random()*0.3;
1165 }
1166
1167
1168
1169 /*void(entity e, float first) UpdateTeamScore =
1170 {
1171         clientno = e.FIXME;
1172         if(first)
1173         {
1174                 WriteByte (MSG_ALL, SVC_UPDATENAME);
1175                 WriteByte (MSG_ALL, clientno);
1176                 WriteString (MSG_ALL, e.netname);
1177
1178                 WriteByte (MSG_ALL, SVC_UPDATECOLORS);
1179                 WriteByte (MSG_ALL, clientno);
1180                 WriteByte (MSG_ALL, e.b_shirt * 16 + who.b_pants);
1181         }
1182
1183         WriteByte (MSG_ALL, SVC_UPDATEFRAGS);
1184         WriteByte (MSG_ALL, clientno);
1185         WriteShort (MSG_ALL, e.frags + 10000);
1186 };
1187
1188 */
1189
1190
1191 // code from here on is just to support maps that don't have team entities
1192 void tdm_spawnteam (string teamname, float teamcolor)
1193 {
1194         local entity e;
1195         e = spawn();
1196         e.classname = "tdm_team";
1197         e.netname = teamname;
1198         e.cnt = teamcolor;
1199         e.team = e.cnt + 1;
1200 };
1201
1202 // spawn some default teams if the map is not set up for tdm
1203 void() tdm_spawnteams =
1204 {
1205         float numteams;
1206
1207         numteams = cvar("g_tdm_teams");
1208
1209         tdm_spawnteam("Red", 4);
1210         tdm_spawnteam("Blue", 13);
1211 };
1212
1213 void() tdm_delayedinit =
1214 {
1215         self.think = SUB_Remove;
1216         self.nextthink = time;
1217         // if no teams are found, spawn defaults
1218         if (find(world, classname, "tdm_team") == world)
1219                 tdm_spawnteams();
1220 };
1221
1222 void() tdm_init =
1223 {
1224         local entity e;
1225         e = spawn();
1226         e.think = tdm_delayedinit;
1227         e.nextthink = time + 0.1;
1228 };
1229
1230