]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
fix _sv_init handling
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3
4 string GetMapname();
5 void GotoNextMap();
6 void ShuffleMaplist()
7 float() DoNextMapOverride;
8
9 void SetDefaultAlpha()
10 {
11         if(cvar("g_running_guns"))
12         {
13                 default_player_alpha = -1;
14                 default_weapon_alpha = +1;
15         }
16         else if(g_cloaked)
17         {
18                 default_player_alpha = cvar("g_balance_cloaked_alpha");
19                 default_weapon_alpha = default_player_alpha;
20         }
21         else
22         {
23                 default_player_alpha = cvar("g_player_alpha");
24                 if(default_player_alpha <= 0)
25                         default_player_alpha = 1;
26                 default_weapon_alpha = default_player_alpha;
27         }
28 }
29
30 void fteqcc_testbugs()
31 {
32         float a, b;
33
34         if(!cvar("developer_fteqccbugs"))
35                 return;
36
37         dprint("*** fteqcc test: checking for bugs...\n");
38
39         a = 1;
40         b = 5;
41         if(sqrt(a) - sqrt(b - a) == 0)
42                 dprint("*** fteqcc test: found same-function-twice bug\n");
43         else
44                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
45
46         world.frags = -10;
47         world.enemy = world;
48         world.enemy.frags += 10;
49         if(world.frags > 0.2 || world.frags < -0.2) // don't error out if it's just roundoff errors
50                 dprint("*** fteqcc test: found += bug\n");
51         else
52                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
53         world.frags = 0;
54 }
55
56 void GotoFirstMap()
57 {
58         if(cvar("_sv_init"))
59         {
60                 cvar_set("_sv_init", "0");
61                 if(cvar("g_maplist_shuffle"))
62                         ShuffleMaplist();
63                 tokenize(cvar_string("g_maplist"));
64                 if(argv(0) != GetMapname())
65                 {
66                         cvar_set("nextmap", argv(0));
67
68 #ifdef MAPINFO
69                         MapInfo_Enumerate();
70                         while(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures()))
71                         {
72                         }
73 #endif
74
75                         if(!DoNextMapOverride())
76                                 GotoNextMap();
77                 }
78         }
79 }
80
81 float world_already_spawned;
82 void worldspawn (void)
83 {
84         float globhandle, i, n;
85
86         dprint_load(); // load dprint status from cvar
87
88         if(world_already_spawned)
89                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
90         world_already_spawned = TRUE;
91
92         sv_cheats = cvar("sv_cheats");
93
94         /*
95         TODO sound pack system
96         // initialize sound pack system
97         soundpack = cvar_string("g_soundpack");
98         if(soundpack != "")
99                 soundpack = strcat(soundpack, "/");
100         soundpack = strzone(soundpack);
101         */
102
103         // gamemode related things
104         precache_model ("models/misc/chatbubble.spr");
105         precache_model ("models/misc/teambubble.spr");
106         if (cvar("g_runematch"))
107         {
108                 precache_model ("models/runematch/curse.mdl");
109                 precache_model ("models/runematch/rune.mdl");
110         }
111
112         // Precache all player models if desired
113         if (cvar("sv_precacheplayermodels"))
114         {
115                 globhandle = search_begin("models/player/*.zym", TRUE, FALSE);
116                 n = search_getsize(globhandle);
117                 for(i = 0; i < n; ++i)
118                 {
119                         //print(search_getfilename(globhandle, i), "\n");
120                         precache_model(search_getfilename(globhandle, i));
121                 }
122                 search_end(globhandle);
123                 //precache_model("models/player/carni.zym");
124                 //precache_model("models/player/crash.zym");
125                 //precache_model("models/player/grunt.zym");
126                 //precache_model("models/player/headhunter.zym");
127                 //precache_model("models/player/insurrectionist.zym");
128                 //precache_model("models/player/jeandarc.zym");
129                 //precache_model("models/player/lurk.zym");
130                 //precache_model("models/player/lycanthrope.zym");
131                 //precache_model("models/player/marine.zym");
132                 //precache_model("models/player/nexus.zym");
133                 //precache_model("models/player/pyria.zym");
134                 //precache_model("models/player/shock.zym");
135                 //precache_model("models/player/skadi.zym");
136                 //precache_model("models/player/specop.zym");
137                 //precache_model("models/player/visitant.zym");
138         }
139
140         if (g_footsteps)
141         {
142                 precache_sound ("misc/footstep01.wav");
143                 precache_sound ("misc/footstep02.wav");
144                 precache_sound ("misc/footstep03.wav");
145                 precache_sound ("misc/footstep04.wav");
146                 precache_sound ("misc/footstep05.wav");
147                 precache_sound ("misc/footstep06.wav");
148         }
149
150         // gore and miscellaneous sounds
151         //precache_sound ("misc/h2ohit.wav");
152         precache_model ("models/gibs/bloodyskull.md3");
153         precache_model ("models/gibs/chunk.mdl");
154         precache_model ("models/gibs/eye.md3");
155         precache_model ("models/gibs/gib1.md3");
156         precache_model ("models/gibs/gib1.mdl");
157         precache_model ("models/gibs/gib2.mdl");
158         precache_model ("models/gibs/gib3.mdl");
159         precache_model ("models/gibs/gib5.md3");
160         precache_model ("models/hook.md3");
161         precache_sound ("misc/armorimpact.wav");
162         precache_sound ("misc/bodyimpact1.wav");
163         precache_sound ("misc/bodyimpact2.wav");
164         precache_sound ("misc/gib.wav");
165         precache_sound ("misc/gib_splat01.wav");
166         precache_sound ("misc/gib_splat02.wav");
167         precache_sound ("misc/gib_splat03.wav");
168         precache_sound ("misc/gib_splat04.wav");
169         precache_sound ("misc/hit.wav");
170         precache_sound ("misc/hitground1.wav");
171         precache_sound ("misc/hitground2.wav");
172         precache_sound ("misc/hitground3.wav");
173         precache_sound ("misc/hitground4.wav");
174         precache_sound ("misc/null.wav");
175         precache_sound ("misc/spawn.wav");
176         precache_sound ("misc/talk.wav");
177         precache_sound ("misc/teleport.wav");
178         precache_sound ("player/lava.wav");
179         precache_sound ("player/slime.wav");
180
181         // announcer sounds - male
182         //precache_sound ("announcer/male/electrobitch.wav");
183         precache_sound ("announcer/male/03kills.wav");
184         precache_sound ("announcer/male/05kills.wav");
185         precache_sound ("announcer/male/10kills.wav");
186         precache_sound ("announcer/male/15kills.wav");
187         precache_sound ("announcer/male/20kills.wav");
188         precache_sound ("announcer/male/25kills.wav");
189         precache_sound ("announcer/male/30kills.wav");
190         precache_sound ("announcer/male/botlike.wav");
191         precache_sound ("announcer/male/yoda.wav");
192
193         // announcer sounds - robotic
194         precache_sound ("announcer/robotic/1fragleft.wav");
195         precache_sound ("announcer/robotic/1minuteremains.wav");
196         precache_sound ("announcer/robotic/2fragsleft.wav");
197         precache_sound ("announcer/robotic/3fragsleft.wav");
198         if (g_minstagib)
199         {
200                 precache_sound ("announcer/robotic/lastsecond.wav");
201                 precache_sound ("announcer/robotic/narrowly.wav");
202                 precache_sound ("announcer/robotic/1.wav");
203                 precache_sound ("announcer/robotic/2.wav");
204                 precache_sound ("announcer/robotic/3.wav");
205                 precache_sound ("announcer/robotic/4.wav");
206                 precache_sound ("announcer/robotic/5.wav");
207                 precache_sound ("announcer/robotic/6.wav");
208                 precache_sound ("announcer/robotic/7.wav");
209                 precache_sound ("announcer/robotic/8.wav");
210                 precache_sound ("announcer/robotic/9.wav");
211                 precache_sound ("announcer/robotic/10.wav");
212         }
213
214         // common weapon precaches
215         precache_sound ("weapons/weapon_switch.wav");
216         precache_sound ("weapons/weaponpickup.wav");
217         if (g_grappling_hook)
218         {
219                 precache_sound ("weapons/hook_fire.wav"); // hook
220                 precache_sound ("weapons/hook_impact.wav"); // hook
221         }
222
223         if (cvar("sv_precacheweapons") || g_nixnex)
224         {
225                 //precache weapon models/sounds
226                 local float wep;
227                 wep = WEP_FIRST;
228                 while (wep <= WEP_LAST)
229                 {
230                         weapon_action(wep, WR_PRECACHE);
231                         wep = wep + 1;
232                 }
233         }
234
235         // plays music for the level if there is any
236         if (self.noise)
237         {
238                 precache_sound (self.noise);
239                 ambientsound ('0 0 0', self.noise, 1.00, ATTN_NONE);
240         }
241
242         // 0 normal
243         lightstyle(0, "m");
244
245         // 1 FLICKER (first variety)
246         lightstyle(1, "mmnmmommommnonmmonqnmmo");
247
248         // 2 SLOW STRONG PULSE
249         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
250
251         // 3 CANDLE (first variety)
252         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
253
254         // 4 FAST STROBE
255         lightstyle(4, "mamamamamama");
256
257         // 5 GENTLE PULSE 1
258         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
259
260         // 6 FLICKER (second variety)
261         lightstyle(6, "nmonqnmomnmomomno");
262
263         // 7 CANDLE (second variety)
264         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
265
266         // 8 CANDLE (third variety)
267         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
268
269         // 9 SLOW STROBE (fourth variety)
270         lightstyle(9, "aaaaaaaazzzzzzzz");
271
272         // 10 FLUORESCENT FLICKER
273         lightstyle(10, "mmamammmmammamamaaamammma");
274
275         // 11 SLOW PULSE NOT FADE TO BLACK
276         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
277
278         // styles 32-62 are assigned by the light program for switchable lights
279
280         // 63 testing
281         lightstyle(63, "a");
282
283         player_count = 0;
284         lms_lowest_lives = 0;
285         lms_next_place = 0;
286
287         GotoFirstMap();
288
289         bot_waypoints_for_items = cvar("g_waypoints_for_items");
290         if(bot_waypoints_for_items == 1)
291                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
292                         bot_waypoints_for_items = 0;
293
294         if(cvar("g_campaign"))
295                 CampaignPreInit();
296
297         InitGameplayMode();
298
299         WaypointSprite_Init();
300
301         //if (cvar("g_domination"))
302         //      dom_init();
303
304         local entity head;
305         head = nextent(world);
306         maxclients = 0;
307         while(head)
308         {
309                 maxclients++;
310                 head = nextent(head);
311         }
312
313         GameLogInit(); // prepare everything
314         if(cvar("sv_eventlog"))
315         {
316                 local string s;
317                 GameLogEcho(":logversion:2", FALSE);
318                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
319                 s = strcat(s, ftos(random()));
320                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
321                 s = ":gameinfo:mutators:LIST";
322                 if(g_grappling_hook)
323                         s = strcat(s, ":grappling_hook");
324                 if(!cvar("g_use_ammunition"))
325                         s = strcat(s, ":no_use_ammunition");
326                 if(!cvar("g_pickup_items"))
327                         s = strcat(s, ":no_pickup_items");
328                 if(g_instagib)
329                         s = strcat(s, ":instagib");
330                 if(g_rocketarena)
331                         s = strcat(s, ":rockerarena");
332                 if(g_nixnex)
333                         s = strcat(s, ":nixnex");
334                 if(g_vampire)
335                         s = strcat(s, ":vampire");
336                 if(g_laserguided_missile)
337                         s = strcat(s, ":laserguided_missile");
338                 if(g_norecoil)
339                         s = strcat(s, ":norecoil");
340                 if(g_midair)
341                         s = strcat(s, ":midair");
342                 if(g_minstagib)
343                         s = strcat(s, ":minstagib");
344                 GameLogEcho(s, FALSE);
345                 GameLogEcho(":gameinfo:end", FALSE);
346         }
347
348         cvar_set("nextmap", "");
349
350         SetDefaultAlpha();
351
352         if(cvar("g_campaign"))
353                 CampaignPostInit();
354
355         fteqcc_testbugs();
356
357         readlevelcvars();
358
359         Ban_LoadBans();
360
361 #ifdef MAPINFO
362         MapInfo_Enumerate();
363         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures());
364 #endif
365 }
366
367 void light (void)
368 {
369         //makestatic (self); // Who the f___ did that?
370         remove(self);
371 }
372
373 float( string pFilename ) TryFile =
374 {
375         local float lHandle;
376         dprint("TryFile(\"", pFilename, "\")\n");
377         lHandle = fopen( pFilename, FILE_READ );
378         if( lHandle != -1 ) {
379                 fclose( lHandle );
380                 return TRUE;
381         } else {
382                 return FALSE;
383         }
384 };
385
386 string GetGametype()
387 {
388         if (game == GAME_DEATHMATCH)
389                 return "dm";
390         else if (game == GAME_TEAM_DEATHMATCH)
391                 return "tdm";
392         else if (game == GAME_DOMINATION)
393                 return "dom";
394         else if (game == GAME_CTF)
395                 return "ctf";
396         else if (game == GAME_RUNEMATCH)
397                 return "rune";
398         else if (game == GAME_LMS)
399                 return "lms";
400         else if (game == GAME_KEYHUNT)
401                 return "kh";
402         else if (game == GAME_ONSLAUGHT)
403                 return "ons";
404         else if (game == GAME_ASSAULT)
405                 return "as";
406         return "dm";
407 }
408
409 float IsSameGametype(string mapcfgname)
410 {
411 #ifdef MAPINFO
412         return TRUE; // can't change game type by map name here
413 #else
414         string gt;
415         gt = GetGametype();
416         if(substring(mapcfgname, 0, strlen(gt) + 1) == strcat(gt, "_"))
417                 return TRUE;
418         return FALSE;
419 #endif
420 }
421
422 string getmapname_stored;
423 string GetMapname()
424 {
425 #ifdef MAPINFO
426         return mapname;
427 #else
428         if(getmapname_stored == "")
429                 getmapname_stored = strzone(strcat(GetGametype(), "_", mapname));
430         return getmapname_stored;
431 #endif
432 }
433
434 float Map_Count, Map_Current;
435 string Map_Current_Name;
436
437 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
438 float GetMaplistPosition()
439 {
440         float pos, idx;
441         string map;
442
443         map = GetMapname();
444         idx = cvar("g_maplist_index");
445
446         if(idx >= 0)
447                 if(idx < Map_Count)
448                         if(map == argv(idx))
449                                 return idx;
450
451         for(pos = 0; pos < Map_Count; ++pos)
452                 if(map == argv(pos))
453                         return pos;
454
455         // resume normal maplist rotation if current map is not in g_maplist
456         return idx;
457 }
458
459 float MapHasRightSize(string map)
460 {
461         // open map size restriction file
462         float fh;
463         dprint("opensize "); dprint(map);
464         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
465         if(fh >= 0)
466         {
467                 float mapmin, mapmax;
468                 dprint(": ok, ");
469                 mapmin = stof(fgets(fh));
470                 mapmax = stof(fgets(fh));
471                 fclose(fh);
472                 if(player_count < mapmin)
473                 {
474                         dprint("not enough\n");
475                         return FALSE;
476                 }
477                 if(player_count > mapmax)
478                 {
479                         dprint("too many\n");
480                         return FALSE;
481                 }
482                 dprint("right size\n");
483                 return TRUE;
484         }
485         dprint(": not found\n");
486         return TRUE;
487 }
488
489 #ifdef MAPINFO
490 #else
491 string Map_Filename(float position)
492 {
493         // FIXME unused
494         return strcat("maps/", argv(position), ".mapcfg");
495 }
496 #endif
497
498 string strwords(string s, float w)
499 {
500         float endpos;
501         for(endpos = 0; w && endpos >= 0; --w)
502                 endpos = strstrofs(s, " ", endpos + 1);
503         if(endpos < 0)
504                 return s;
505         else
506                 return substring(s, 0, endpos);
507 }
508
509 float strhasword(string s, string w)
510 {
511         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
512 }
513
514 void Map_MarkAsRecent(string m)
515 {
516         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
517 }
518
519 float Map_IsRecent(string m)
520 {
521         return strhasword(cvar_string("g_maplist_mostrecent"), m);
522 }
523
524 float(float position, float pass) Map_Check =
525 {
526         string filename;
527         string map_next;
528         map_next = argv(position);
529         if(pass <= 1)
530         {
531                 if(map_next == Map_Current_Name) // same map again in first pass?
532                         return 0;
533                 if(Map_IsRecent(map_next))
534                         return 0;
535         }
536 #ifdef MAPINFO
537         if(MapInfo_CheckMap(argv(position)))
538 #else
539         filename = Map_Filename(position);
540         if(TryFile(filename))
541 #endif
542         {
543                 if(pass == 2)
544                         return 1;
545                 if(MapHasRightSize(argv(position)))
546                         return 1;
547                 return 0;
548         }
549         else
550                 dprint( "Couldn't find '", filename, "'..\n" );
551
552         return 0;
553 }
554
555 void(string nextmapname) Map_Goto_SetStr =
556 {
557         if(getmapname_stored != "")
558                 strunzone(getmapname_stored);
559         if(nextmapname == "")
560                 getmapname_stored = "";
561         else
562                 getmapname_stored = strzone(nextmapname);
563 }
564
565 void(float position) Map_Goto_SetFloat =
566 {
567         cvar_set("g_maplist_index", ftos(position));
568         Map_Goto_SetStr(argv(position));
569 }
570
571 void() GameResetCfg =
572 {
573 #ifdef MAPINFO
574         // settings persist, except...
575         if(cvar("g_campaign"))
576                 localcmd("\nexec mutator_reset.cfg\n");
577         localcmd("\nsettemp_restore\n");
578 #else
579         // if an exit cfg is defined by exiting map, exec it.
580         string exit_cfg;
581         exit_cfg = cvar_string("exit_cfg");
582         if(exit_cfg != "")
583                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
584
585         localcmd("exec game_reset.cfg\n");
586 #endif
587
588         Ban_SaveBans();
589 };
590
591 void() Map_Goto =
592 {
593         Map_MarkAsRecent(getmapname_stored);
594         GameResetCfg();
595 #ifdef MAPINFO
596         MapInfo_LoadMap(getmapname_stored);
597 #else
598         localcmd(strcat("exec \"maps/", getmapname_stored ,".mapcfg\"\n"));
599 #endif
600 }
601
602 // return codes of map selectors:
603 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
604 //   -2 = permanent failure
605 float() MaplistMethod_Iterate = // usual method
606 {
607         float pass, i;
608
609         for(pass = 1; pass <= 2; ++pass)
610         {
611                 for(i = 1; i < Map_Count; ++i)
612                 {
613                         float mapindex;
614                         mapindex = math_mod(i + Map_Current, Map_Count);
615                         if(Map_Check(mapindex, pass))
616                                 return mapindex;
617                 }
618         }
619         return -1;
620 }
621
622 float() MaplistMethod_Repeat = // fallback method
623 {
624         if(Map_Check(Map_Current, 2))
625                 return Map_Current;
626         return -2;
627 }
628
629 float() MaplistMethod_Random = // random map selection
630 {
631         float i, imax;
632
633         imax = 42;
634
635         for(i = 0; i <= imax; ++i)
636         {
637                 float mapindex;
638                 mapindex = math_mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
639                 if(Map_Check(mapindex, 1))
640                         return mapindex;
641         }
642         return -1;
643 }
644
645 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
646 // the exponent sets a bias on the map selection:
647 // the higher the exponent, the less likely "shortly repeated" same maps are
648 {
649         float i, j, imax, insertpos;
650
651         imax = 42;
652
653         if(Map_Count <= 1)
654                 return 0; // only one map, then always play this one
655
656         for(i = 0; i <= imax; ++i)
657         {
658                 string newlist;
659
660                 // now reinsert this at another position
661                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
662                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
663                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
664                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
665
666                 // insert the current map there
667                 newlist = "";
668 #ifdef MAPINFO
669                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
670                         newlist = strcat(newlist, " ", argv(j));
671                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
672                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
673                         newlist = strcat(newlist, " ", argv(j));
674                 newlist = substring(newlist, 1, strlen(newlist) - 1);
675 #else
676                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
677                         newlist = strcat(newlist, "'", argv(j), "'");
678                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
679                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
680                         newlist = strcat(newlist, "'", argv(j), "'");
681 #endif
682                 cvar_set("g_maplist", newlist);
683                 Map_Count = tokenize(newlist);
684
685                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
686                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
687                 if(Map_Check(Map_Current, 1))
688                         return Map_Current;
689         }
690         return -1;
691 }
692
693 void() Maplist_Init =
694 {
695         string temp;
696         temp = cvar_string("g_maplist");
697         Map_Count = tokenize(temp);
698         if(Map_Count == 0)
699         {
700                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
701 #ifdef MAPINFO
702                 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps());
703 #else
704                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
705 #endif
706                 Map_Count = tokenize(temp);
707         }
708         if(Map_Count == 0)
709                 error("empty maplist, cannot select a new map");
710         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
711
712         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
713         // this may or may not be correct, but who cares, in the worst case a map
714         // isn't chosen in the first pass that should have been
715 }
716
717 string() GetNextMap =
718 {
719         float nextMap;
720
721         Maplist_Init();
722         nextMap = -1;
723
724         if(nextMap == -1)
725                 if(cvar("g_maplist_shuffle") > 0)
726                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
727
728         if(nextMap == -1)
729                 if(cvar("g_maplist_selectrandom"))
730                         nextMap = MaplistMethod_Random();
731
732         if(nextMap == -1)
733                 nextMap = MaplistMethod_Iterate();
734
735         if(nextMap == -1)
736                 nextMap = MaplistMethod_Repeat();
737
738         if(nextMap >= 0)
739         {
740                 Map_Goto_SetFloat(nextMap);
741                 return getmapname_stored;
742         }
743
744         return "";
745 };
746
747 float() DoNextMapOverride =
748 {
749         Ban_SaveBans();
750
751         if(cvar("g_campaign"))
752         {
753                 CampaignPostIntermission();
754                 alreadychangedlevel = TRUE;
755                 return TRUE;
756         }
757         if(cvar("quit_when_empty"))
758         {
759                 if(player_count <= currentbots)
760                 {
761                         localcmd("quit\n");
762                         alreadychangedlevel = TRUE;
763                         return TRUE;
764                 }
765         }
766         if(cvar_string("quit_and_redirect") != "")
767         {
768                 redirection_target = strzone(cvar_string("quit_and_redirect"));
769                 alreadychangedlevel = TRUE;
770                 return TRUE;
771         }
772         if (cvar("samelevel")) // if samelevel is set, stay on same level
773         {
774                 // this does not work because it tries to exec maps/nexdm01.mapcfg (which doesn't exist, it should be trying maps/dm_nexdm01.mapcfg for example)
775                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
776                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
777                 localcmd("restart\n");
778                 //changelevel (mapname);
779                 alreadychangedlevel = TRUE;
780                 return TRUE;
781         }
782         if(cvar_string("nextmap") != "")
783 #ifdef MAPINFO
784                 if(MapInfo_CheckMap(cvar_string("nextmap")))
785 #else
786                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
787 #endif
788                 {
789                         Map_Goto_SetStr(cvar_string("nextmap"));
790                         Map_Goto();
791                         alreadychangedlevel = TRUE;
792                         return TRUE;
793                 }
794         if(cvar("lastlevel"))
795         {
796                 GameResetCfg();
797                 localcmd("set lastlevel 0\ntogglemenu\n");
798                 alreadychangedlevel = TRUE;
799                 return TRUE;
800         }
801         return FALSE;
802 };
803
804 void() GotoNextMap =
805 {
806         //local string nextmap;
807         //local float n, nummaps;
808         //local string s;
809         if (alreadychangedlevel)
810                 return;
811         alreadychangedlevel = TRUE;
812
813         {
814                 string nextMap;
815                 float allowReset;
816
817                 for(allowReset = 1; allowReset >= 0; --allowReset)
818                 {
819                         nextMap = GetNextMap();
820                         if(nextMap != "")
821                                 break;
822
823                         if(allowReset)
824                         {
825                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
826 #ifdef MAPINFO
827                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
828 #else
829                                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
830 #endif
831                         }
832                         else
833                         {
834                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
835                         }
836                 }
837                 Map_Goto();
838         }
839 };
840
841
842 /*
843 ============
844 IntermissionThink
845
846 When the player presses attack or jump, change to the next level
847 ============
848 */
849 .float autoscreenshot;
850 void() MapVote_Start;
851 void() MapVote_Think;
852 float mapvote_initialized;
853 void() IntermissionThink =
854 {
855         FixIntermissionClient(self);
856
857         if(cvar("sv_autoscreenshot"))
858         if(self.autoscreenshot > 0)
859         if(time > self.autoscreenshot)
860         {
861                 self.autoscreenshot = -1;
862                 if(clienttype(self) == CLIENTTYPE_REAL)
863                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
864                 return;
865         }
866
867         if (time < intermission_exittime)
868                 return;
869
870         if(!mapvote_initialized)
871                 if (time < intermission_exittime + 10 && !self.button0 && !self.button2 && !self.button3 && !self.button6 && !self.buttonuse)
872                         return;
873
874         MapVote_Start();
875 };
876
877 /*
878 ============
879 FindIntermission
880
881 Returns the entity to view from
882 ============
883 */
884 /*
885 entity() FindIntermission =
886 {
887         local   entity spot;
888         local   float cyc;
889
890 // look for info_intermission first
891         spot = find (world, classname, "info_intermission");
892         if (spot)
893         {       // pick a random one
894                 cyc = random() * 4;
895                 while (cyc > 1)
896                 {
897                         spot = find (spot, classname, "info_intermission");
898                         if (!spot)
899                                 spot = find (spot, classname, "info_intermission");
900                         cyc = cyc - 1;
901                 }
902                 return spot;
903         }
904
905 // then look for the start position
906         spot = find (world, classname, "info_player_start");
907         if (spot)
908                 return spot;
909
910 // testinfo_player_start is only found in regioned levels
911         spot = find (world, classname, "testplayerstart");
912         if (spot)
913                 return spot;
914
915 // then look for the start position
916         spot = find (world, classname, "info_player_deathmatch");
917         if (spot)
918                 return spot;
919
920         //objerror ("FindIntermission: no spot");
921         return world;
922 };
923 */
924
925 /*
926 ===============================================================================
927
928 RULES
929
930 ===============================================================================
931 */
932
933 void(float final) DumpStats =
934 {
935         local float file;
936         local string s;
937         local float to_console;
938         local float to_eventlog;
939         local float to_file;
940
941         to_console = cvar("sv_logscores_console");
942         to_eventlog = cvar("sv_eventlog");
943         to_file = cvar("sv_logscores_file");
944
945         if(!final)
946         {
947                 to_console = TRUE; // always print printstats replies
948                 to_eventlog = FALSE; // but never print them to the event log
949         }
950
951         if(to_eventlog)
952                 if(cvar("sv_eventlog_console"))
953                         to_console = FALSE; // otherwise we get the output twice
954
955         if(final)
956                 s = ":scores:";
957         else
958                 s = ":status:";
959         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
960
961         if(to_console)
962                 ServerConsoleEcho(s, FALSE);
963         if(to_eventlog)
964                 GameLogEcho(s, FALSE);
965         if(to_file)
966         {
967                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
968                 if(file == -1)
969                         to_file = FALSE;
970                 else
971                         fputs(file, strcat(s, "\n"));
972         }
973
974         FOR_EACH_CLIENT(other)
975         {
976                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
977                 {
978                         s = strcat(":player:", ftos(other.frags), ":");
979                         s = strcat(s, ftos(other.deaths), ":");
980                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
981                         s = strcat(s, ftos(other.team), ":");
982
983                         if(to_console)
984                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
985                         if(to_eventlog)
986                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
987                         if(to_file)
988                                 fputs(file, strcat(s, other.netname, "\n"));
989                 }
990         }
991
992         if(to_console)
993                 ServerConsoleEcho(":end", FALSE);
994         if(to_eventlog)
995                 GameLogEcho(":end", FALSE);
996         if(to_file)
997         {
998                 fputs(file, ":end\n");
999                 fclose(file);
1000         }
1001 }
1002
1003 void FixIntermissionClient(entity e)
1004 {
1005         if(!e.autoscreenshot) // initial call
1006         {
1007                 e.angles = e.v_angle;
1008                 e.angles_x = -e.angles_x;
1009                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1010                 e.health = -2342;
1011                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1012                 e.solid = SOLID_NOT;
1013                 e.movetype = MOVETYPE_NONE;
1014                 e.takedamage = DAMAGE_NO;
1015                 if(e.weaponentity)
1016                         e.weaponentity.effects = EF_NODRAW;
1017                 stuffcmd(e, "\nscr_printspeed 1000000\n");
1018                 if(clienttype(e) == CLIENTTYPE_REAL)
1019                 {
1020                         msg_entity = e;
1021                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1022                 }
1023         }
1024
1025         //e.velocity = '0 0 0';
1026         //e.fixangle = TRUE;
1027
1028         // TODO halt weapon animation
1029 }
1030
1031
1032 /*
1033 go to the next level for deathmatch
1034 only called if a time or frag limit has expired
1035 */
1036 void() NextLevel =
1037 {
1038         float minTotalFrags;
1039         float maxTotalFrags;
1040         float score;
1041         float f;
1042
1043         gameover = TRUE;
1044
1045         intermission_running = 1;
1046
1047 // enforce a wait time before allowing changelevel
1048         if(player_count > 0)
1049                 intermission_exittime = time + cvar("sv_mapchange_delay");
1050         else
1051                 intermission_exittime = -1;
1052
1053         WriteByte (MSG_ALL, SVC_CDTRACK);
1054         WriteByte (MSG_ALL, 3);
1055         WriteByte (MSG_ALL, 3);
1056
1057         //pos = FindIntermission ();
1058
1059         VoteReset();
1060
1061         DumpStats(TRUE);
1062
1063         if(cvar("sv_eventlog"))
1064                 GameLogEcho(":gameover", FALSE);
1065
1066         GameLogClose();
1067
1068         FOR_EACH_CLIENT(other)
1069         {
1070                 FixIntermissionClient(other);
1071
1072                 if(other.winning)
1073                         bprint(other.netname, " ^7wins.\n");
1074         }
1075
1076         minTotalFrags = 0;
1077         maxTotalFrags = 0;
1078         FOR_EACH_PLAYER(other)
1079         {
1080                 if(maxTotalFrags < other.totalfrags)
1081                         maxTotalFrags = other.totalfrags;
1082                 if(minTotalFrags > other.totalfrags)
1083                         minTotalFrags = other.totalfrags;
1084         }
1085
1086         if(!currentbots)
1087         {
1088                 FOR_EACH_PLAYER(other)
1089                 {
1090                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1091                         f = bound(0, other.play_time / max(time, 1), 1);
1092                         // store some statistics?
1093                 }
1094         }
1095
1096         if(cvar("g_campaign"))
1097                 CampaignPreIntermission();
1098
1099         // WriteByte (MSG_ALL, SVC_INTERMISSION);
1100 };
1101
1102 /*
1103 ============
1104 CheckRules_Player
1105
1106 Exit deathmatch games upon conditions
1107 ============
1108 */
1109 void() CheckRules_Player =
1110 {
1111         if (gameover)   // someone else quit the game already
1112                 return;
1113
1114         if(self.deadflag == DEAD_NO)
1115                 self.play_time += frametime;
1116
1117         // fixme: don't check players; instead check dom_team and ctf_team entities
1118         //   (div0: and that in CheckRules_World please)
1119 };
1120
1121 float checkrules_oneminutewarning;
1122 float checkrules_leaderfrags;
1123 float tdm_max_score, tdm_old_score;
1124
1125 float checkrules_equality;
1126 float checkrules_overtimewarning;
1127 float checkrules_overtimeend;
1128
1129 void() InitiateOvertime =
1130 {
1131         if(!checkrules_overtimeend)
1132                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1133 }
1134
1135 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1136 float WINNING_YES = 1; // winner found
1137 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1138 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1139
1140 float(float fraglimitreached, float equality) GetWinningCode =
1141 {
1142         if(equality)
1143                 if(fraglimitreached)
1144                         return WINNING_STARTOVERTIME;
1145                 else
1146                         return WINNING_NEVER;
1147         else
1148                 if(fraglimitreached)
1149                         return WINNING_YES;
1150                 else
1151                         return WINNING_NO;
1152 }
1153
1154 // set the .winning flag for exactly those players with a given field value
1155 void(.float field, float value) SetWinners =
1156 {
1157         entity head;
1158         FOR_EACH_PLAYER(head)
1159                 head.winning = (head.field == value);
1160 }
1161
1162 // set the .winning flag for those players with a given field value
1163 void(.float field, float value) AddWinners =
1164 {
1165         entity head;
1166         FOR_EACH_PLAYER(head)
1167                 if(head.field == value)
1168                         head.winning = 1;
1169 }
1170
1171 // clear the .winning flags
1172 void(void) ClearWinners =
1173 {
1174         entity head;
1175         FOR_EACH_PLAYER(head)
1176                 head.winning = 0;
1177 }
1178
1179 // Onslaught winning condition:
1180 // game terminates if only one team has a working generator (or none)
1181 float() WinningCondition_Onslaught =
1182 {
1183         entity head;
1184         local float t1, t2, t3, t4;
1185         // first check if the game has ended
1186         t1 = t2 = t3 = t4 = 0;
1187         head = find(world, classname, "onslaught_generator");
1188         while (head)
1189         {
1190                 if (head.health > 0)
1191                 {
1192                         if (head.team == COLOR_TEAM1) t1 = 1;
1193                         if (head.team == COLOR_TEAM2) t2 = 1;
1194                         if (head.team == COLOR_TEAM3) t3 = 1;
1195                         if (head.team == COLOR_TEAM4) t4 = 1;
1196                 }
1197                 head = find(head, classname, "onslaught_generator");
1198         }
1199         if (t1 + t2 + t3 + t4 < 2)
1200         {
1201                 // game over, only one team remains (or none)
1202                 ClearWinners();
1203                 if (t1) SetWinners(team, COLOR_TEAM1);
1204                 if (t2) SetWinners(team, COLOR_TEAM2);
1205                 if (t3) SetWinners(team, COLOR_TEAM3);
1206                 if (t4) SetWinners(team, COLOR_TEAM4);
1207                 dprint("Have a winner, ending game.\n");
1208                 return WINNING_YES;
1209         }
1210
1211         // Two or more teams remain
1212         return WINNING_NO;
1213 }
1214
1215 float() LMS_NewPlayerLives =
1216 {
1217         float fl;
1218         fl = cvar("fraglimit");
1219         if(fl == 0)
1220                 fl = 999;
1221
1222         // first player has left the game for dying too much? Nobody else can get in.
1223         if(lms_lowest_lives < 1)
1224                 return FALSE;
1225
1226         if(!cvar("g_lms_join_anytime"))
1227                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1228                         return FALSE;
1229
1230         return bound(1, lms_lowest_lives, fl);
1231 }
1232
1233 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1234 // they win. Otherwise the defending team wins once the timelimit passes.
1235 void assault_new_round();
1236 float() WinningCondition_Assault =
1237 {
1238         local float status;
1239         status = WINNING_NO;
1240
1241         // as the timelimit has not yet passed just assume the defending team will win
1242         if(assault_attacker_team == COLOR_TEAM1)
1243         {
1244                 SetWinners(team, COLOR_TEAM2);
1245         }
1246         else
1247         {
1248                 SetWinners(team, COLOR_TEAM1);
1249         }       
1250                 
1251         local entity ent;
1252         ent = find(world, classname, "target_assault_roundend");
1253         if(ent)
1254         {
1255                 if(ent.winning) // round end has been triggered by attacking team
1256                 {
1257                         SetWinners(team, assault_attacker_team);
1258                         if(assault_attacker_team == COLOR_TEAM1)
1259                         {
1260                                 team1_score = team1_score + 50;
1261                         }
1262                         else
1263                         {
1264                                 team2_score = team2_score + 50;
1265                         }
1266
1267                         if(ent.cnt == 1) // this was the second round
1268                         {
1269                                 status = WINNING_YES;
1270                         }
1271                         else
1272                         {
1273                                 cvar_set("timelimit", ftos((2*time)/60));
1274                                 assault_new_round();
1275                         }
1276                 }               
1277         }
1278
1279         return status;
1280
1281 }
1282
1283
1284 // LMS winning condition: game terminates if and only if there's at most one
1285 // one player who's living lives. Top two scores being equal cancels the time
1286 // limit.
1287 float() WinningCondition_LMS =
1288 {
1289         entity head;
1290         float have_player;
1291         float have_players;
1292         float l;
1293
1294         have_player = FALSE;
1295         have_players = FALSE;
1296         l = LMS_NewPlayerLives();
1297
1298         head = find(world, classname, "player");
1299         if(head)
1300                 have_player = TRUE;
1301         head = find(head, classname, "player");
1302         if(head)
1303                 have_players = TRUE;
1304
1305         if(have_player)
1306         {
1307                 // we have at least one player
1308                 if(have_players)
1309                 {
1310                         // two or more active players - continue with the game
1311                 }
1312                 else
1313                 {
1314                         // exactly one player?
1315                         if(l)
1316                         {
1317                                 // but no game has taken place yet
1318                         }
1319                         else
1320                         {
1321                                 // a winner!
1322                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1323                                 dprint("Have a winner, ending game.\n");
1324                                 return WINNING_YES;
1325                         }
1326                 }
1327         }
1328         else
1329         {
1330                 // nobody is playing at all...
1331                 if(l)
1332                 {
1333                         // wait for players...
1334                 }
1335                 else
1336                 {
1337                         // SNAFU (maybe a draw game?)
1338                         ClearWinners();
1339                         dprint("No players, ending game.\n");
1340                         return WINNING_YES;
1341                 }
1342         }
1343
1344         // When we get here, we have at least two players who are actually LIVING,
1345         // or one player who is still waiting for a victim to join the server. Now
1346         // check if the top two players have equal score.
1347
1348         checkrules_leaderfrags = 0;
1349         checkrules_equality = FALSE;
1350         FOR_EACH_PLAYER(head)
1351         {
1352                 if(head.frags > checkrules_leaderfrags)
1353                 {
1354                         checkrules_leaderfrags = head.frags;
1355                         checkrules_equality = FALSE;
1356                 }
1357                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1358                         checkrules_equality = TRUE;
1359         }
1360
1361         SetWinners(frags, checkrules_leaderfrags);
1362
1363         // The top two players have the same amount of lives? No timelimit then,
1364         // enter overtime...
1365
1366         if(checkrules_equality)
1367                 return WINNING_NEVER;
1368
1369         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1370         return WINNING_NO;
1371 }
1372
1373 // DM winning condition: game terminates if a player reached the fraglimit,
1374 // unless the first two players have the same score. The latter case also
1375 // breaks the time limit.
1376 float(float fraglimit) WinningCondition_MaxIndividualScore =
1377 {
1378         float checkrules_oldleaderfrags;
1379         entity head;
1380
1381         checkrules_oldleaderfrags = checkrules_leaderfrags;
1382         checkrules_leaderfrags = 0;
1383         checkrules_equality = FALSE;
1384         FOR_EACH_PLAYER(head)
1385         {
1386                 if(head.frags > checkrules_leaderfrags)
1387                 {
1388                         checkrules_leaderfrags = head.frags;
1389                         checkrules_equality = FALSE;
1390                 }
1391                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1392                         checkrules_equality = TRUE;
1393         }
1394
1395         if(checkrules_leaderfrags > 0)
1396                 SetWinners(frags, checkrules_leaderfrags);
1397         else
1398                 ClearWinners();
1399
1400         if (!cvar("g_runematch"))
1401                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1402                 {
1403                         if (checkrules_leaderfrags == fraglimit - 1)
1404                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1405                         else if (checkrules_leaderfrags == fraglimit - 2)
1406                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1407                         else if (checkrules_leaderfrags == fraglimit - 3)
1408                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1409                 }
1410
1411         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1412 }
1413
1414 float(float fraglimit) WinningConditionBase_Teamplay =
1415 {
1416         tdm_old_score = tdm_max_score;
1417         tdm_max_score = max4(team1_score, team2_score, team3_score, team4_score);
1418
1419         checkrules_equality =
1420         (
1421                 (tdm_max_score > 0)
1422                 &&
1423                 (
1424                           (team1_score == tdm_max_score)
1425                         + (team2_score == tdm_max_score)
1426                         + (team3_score == tdm_max_score)
1427                         + (team4_score == tdm_max_score)
1428                         >= 2));
1429
1430         ClearWinners();
1431         if(tdm_max_score > 0)
1432         {
1433                 if(team1_score == tdm_max_score)
1434                         AddWinners(team, COLOR_TEAM1);
1435                 if(team2_score == tdm_max_score)
1436                         AddWinners(team, COLOR_TEAM2);
1437                 if(team3_score == tdm_max_score)
1438                         AddWinners(team, COLOR_TEAM3);
1439                 if(team4_score == tdm_max_score)
1440                         AddWinners(team, COLOR_TEAM4);
1441         }
1442
1443         if(!cvar("g_runematch") && !cvar("g_domination"))
1444                 if(tdm_max_score != tdm_old_score)
1445                 {
1446                         if(tdm_max_score == fraglimit - 1)
1447                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1448                         else if(tdm_max_score == fraglimit - 2)
1449                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1450                         else if(tdm_max_score == fraglimit - 3)
1451                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1452                 }
1453
1454         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1455 }
1456
1457 // TDM winning condition: game terminates if a team's score sum reached the
1458 // fraglimit, unless the first two teams have the same total score. The latter
1459 // case also breaks the time limit.
1460 float(float fraglimit) WinningCondition_MaxTeamSum =
1461 {
1462         entity head;
1463
1464         team1_score = team2_score = team3_score = team4_score = 0;
1465
1466         FOR_EACH_PLAYER(head)
1467         {
1468                 if(head.team == COLOR_TEAM1)
1469                         team1_score += head.frags;
1470                 else if(head.team == COLOR_TEAM2)
1471                         team2_score += head.frags;
1472                 else if(head.team == COLOR_TEAM3)
1473                         team3_score += head.frags;
1474                 else if(head.team == COLOR_TEAM4)
1475                         team4_score += head.frags;
1476         }
1477
1478         return WinningConditionBase_Teamplay(fraglimit);
1479 }
1480
1481 // DOM/CTF winning condition: game terminates if the max of a team's players'
1482 // score reached the fraglimit, unless the first two teams have the same
1483 // maximum score. The latter case also breaks the time limit.
1484 float(float fraglimit) WinningCondition_MaxTeamMax =
1485 {
1486         entity head;
1487
1488         team1_score = team2_score = team3_score = team4_score = 0;
1489
1490         FOR_EACH_PLAYER(head)
1491         {
1492                 if(head.team == COLOR_TEAM1)
1493                 {
1494                         if(head.frags > team1_score)
1495                                 team1_score = head.frags;
1496                 }
1497                 else if(head.team == COLOR_TEAM2)
1498                 {
1499                         if(head.frags > team2_score)
1500                                 team2_score = head.frags;
1501                 }
1502                 else if(head.team == COLOR_TEAM3)
1503                 {
1504                         if(head.frags > team3_score)
1505                                 team3_score = head.frags;
1506                 }
1507                 else if(head.team == COLOR_TEAM4)
1508                 {
1509                         if(head.frags > team4_score)
1510                                 team4_score = head.frags;
1511                 }
1512         }
1513
1514         return WinningConditionBase_Teamplay(fraglimit);
1515 }
1516
1517 void print_to(entity e, string s)
1518 {
1519         if(e)
1520                 sprint(e, strcat(s, "\n"));
1521         else
1522                 ServerConsoleEcho(s, TRUE);
1523 }
1524
1525 void PrintScoreboardFor(entity e, string name, string colorcode, float whichteam)
1526 {
1527         entity head;
1528         float v;
1529         float teamvalue;
1530         float fragtotal;
1531         string s;
1532         float found;
1533         found = FALSE;
1534         teamvalue = 0;
1535         FOR_EACH_PLAYER(head)
1536         {
1537                 if(!whichteam || head.team == whichteam)
1538                 {
1539                         if(name != "")
1540                                 if(!found)
1541                                         print_to(e, strcat(" ", colorcode, name, ":"));
1542                         found = TRUE;
1543                         fragtotal = fragtotal + head.frags;
1544                         s = ftos(head.frags);
1545                         s = strcat(s, "/", ftos(head.deaths));
1546                         s = strcat(s, " @ ", ftos(head.ping));
1547                         if(clienttype(head) == CLIENTTYPE_BOT)
1548                                 s = strcat(s, "botms");
1549                         else
1550                                 s = strcat(s, "ms");
1551                         v = PlayerValue(head);
1552                         teamvalue += v;
1553                         s = strcat(s, " / ", ftos(v));
1554                         print_to(e, strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"));
1555                 }
1556         }
1557         if(whichteam && found)
1558         {
1559                 s = ftos(fragtotal);
1560                 s = strcat(s, " / ", ftos(teamvalue));
1561                 print_to(e, strcat(colorcode, "  (total: ", s, ")"));
1562         }
1563 }
1564
1565 void PrintScoreboard(entity e)
1566 {
1567         print_to(e, strcat("Time:      ", ftos(time / 60)));
1568         print_to(e, strcat("Timelimit: ", ftos(cvar("timelimit"))));
1569         print_to(e, strcat("Fraglimit: ", ftos(cvar("fraglimit"))));
1570         print_to(e, "Scoreboard:");
1571         if(teams_matter)
1572         {
1573                 PrintScoreboardFor(e, "Red", "^1", COLOR_TEAM1);
1574                 PrintScoreboardFor(e, "Blue", "^4", COLOR_TEAM2);
1575                 PrintScoreboardFor(e, "Yellow", "^3", COLOR_TEAM3);
1576                 PrintScoreboardFor(e, "Pink", "^6", COLOR_TEAM4);
1577         }
1578         else
1579         {
1580                 PrintScoreboardFor(e, "", "^7", 0);
1581         }
1582         print_to(e, ".");
1583 }
1584
1585 void ShuffleMaplist()
1586 {
1587         string result;
1588         float start;
1589         float litems;
1590         float selected;
1591         float i;
1592
1593         result = cvar_string("g_maplist");
1594         litems = tokenize(result);
1595
1596         for(start = 0; start < litems - 1; ++start)
1597         {
1598                 result = "";
1599
1600                 // select a random item
1601                 selected = ceil(random() * (litems - start) + start) - 1;
1602
1603                 // shift this item to the place start
1604 #ifdef MAPINFO
1605                 for(i = 0; i < start; ++i)
1606                         result = strcat(result, " ", argv(i));
1607                 result = strcat(result, " ", argv(selected));
1608                 for(i = start; i < litems; ++i)
1609                         if(i != selected)
1610                                 result = strcat(result, " ", argv(i));
1611                 result = substring(result, 1, strlen(result) - 1);
1612 #else
1613                 for(i = 0; i < start; ++i)
1614                         result = strcat(result, "'", argv(i), "'");
1615                 result = strcat(result, "'", argv(selected), "'");
1616                 for(i = start; i < litems; ++i)
1617                         if(i != selected)
1618                                 result = strcat(result, "'", argv(i), "'");
1619 #endif
1620
1621                 litems = tokenize(result);
1622
1623                 //dprint(result, "\n");
1624         }
1625
1626         cvar_set("g_maplist", result);
1627 }
1628
1629 /*
1630 ============
1631 CheckRules_World
1632
1633 Exit deathmatch games upon conditions
1634 ============
1635 */
1636 void() CheckRules_World =
1637 {
1638         local float status;
1639         local float timelimit;
1640         local float fraglimit;
1641
1642         VoteThink();
1643         MapVote_Think();
1644
1645         SetDefaultAlpha();
1646
1647         /*
1648         MapVote_Think should now do that part
1649         if (intermission_running)
1650                 if (time >= intermission_exittime + 60)
1651                 {
1652                         if(!DoNextMapOverride())
1653                                 GotoNextMap();
1654                         return;
1655                 }
1656         */
1657
1658         if (gameover)   // someone else quit the game already
1659         {
1660                 if(player_count == 0) // Nobody there? Then let's go to the next map
1661                         MapVote_Start();
1662                         // this will actually check the player count in the next frame
1663                         // again, but this shouldn't hurt
1664                 return;
1665         }
1666
1667         timelimit = cvar("timelimit") * 60;
1668         fraglimit = cvar("fraglimit");
1669
1670         if(checkrules_overtimeend)
1671         {
1672                 if(!checkrules_overtimewarning)
1673                 {
1674                         checkrules_overtimewarning = TRUE;
1675                         //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1676                         bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1677                 }
1678         }
1679         else
1680         {
1681                 if (timelimit && time >= timelimit)
1682                         InitiateOvertime();
1683         }
1684
1685         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1686         {
1687                 NextLevel();
1688                 return;
1689         }
1690
1691         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1692         {
1693                 checkrules_oneminutewarning = TRUE;
1694                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1695         }
1696
1697         status = WINNING_NO;
1698         if(g_assault)
1699         {
1700                 status = WinningCondition_Assault();
1701         }
1702         else if(g_lms)
1703         {
1704                 status = WinningCondition_LMS();
1705         }
1706         else if (g_onslaught)
1707         {
1708                 status = WinningCondition_Onslaught();
1709         }
1710         else
1711         {
1712                 if(teams_matter)
1713                 {
1714                         if(g_tdm || cvar("g_runematch") || g_ctf || cvar("g_domination") || g_keyhunt)
1715                                 status = WinningCondition_MaxTeamSum(fraglimit);
1716                         //else if()
1717                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1718                         else
1719                         {
1720                                 dprint("div0: How can this happen?\n");
1721                                 status = WinningCondition_MaxTeamMax(fraglimit);
1722                         }
1723                 }
1724                 else
1725                         status = WinningCondition_MaxIndividualScore(fraglimit);
1726         }
1727
1728         if(status == WINNING_STARTOVERTIME)
1729         {
1730                 status = WINNING_NEVER;
1731                 InitiateOvertime();
1732         }
1733
1734         if(status == WINNING_NEVER)
1735                 // equality cases! Nobody wins if the overtime ends in a draw.
1736                 ClearWinners();
1737
1738         if(checkrules_overtimeend)
1739                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1740                         status = WINNING_YES;
1741
1742         if(status == WINNING_YES)
1743                 NextLevel();
1744 };
1745
1746 float randsel_value;
1747 float randsel_priority;
1748 float randsel_count;
1749 void RandSel_Init()
1750 {
1751         randsel_value = -1;
1752         randsel_priority = -1;
1753         randsel_count = -1;
1754 }
1755 void RandSel_Add(float priority, float value)
1756 {
1757         if(priority > randsel_priority)
1758         {
1759                 randsel_priority = priority;
1760                 randsel_value = value;
1761                 randsel_count = 1;
1762         }
1763         else if(priority == randsel_priority)
1764         {
1765                 randsel_count += 1;
1766                 if(ceil(random() * randsel_count) == 1)
1767                         randsel_value = value;
1768         }
1769 }
1770
1771 float mapvote_nextthink;
1772 float mapvote_initialized;
1773 float mapvote_keeptwotime;
1774 float mapvote_timeout;
1775 string mapvote_message;
1776
1777 #define MAPVOTE_COUNT 10
1778 float mapvote_count;
1779 string mapvote_maps[MAPVOTE_COUNT];
1780 float mapvote_maps_suggested[MAPVOTE_COUNT];
1781 string mapvote_suggestions[MAPVOTE_COUNT];
1782 float mapvote_suggestion_ptr;
1783 float mapvote_maxlen;
1784 float mapvote_voters;
1785 float mapvote_votes[MAPVOTE_COUNT];
1786 float mapvote_run;
1787 .float mapvote;
1788
1789 void MapVote_ClearAllVotes()
1790 {
1791         FOR_EACH_CLIENT(other)
1792                 other.mapvote = 0;
1793 }
1794
1795 string MapVote_Suggest(string m)
1796 {
1797         float i;
1798         if(m == "")
1799                 return "That's not how to use this command.";
1800         if(!cvar("g_maplist_votable_suggestions"))
1801                 return "Suggestions are not accepted on this server.";
1802         if(mapvote_initialized)
1803                 return "Can't suggest - voting is already in progress!";
1804 #ifdef MAPINFO
1805         m = MapInfo_FixName(m);
1806         if(!m)
1807                 return "The map you suggested is not available on this server.";
1808 #endif
1809         if(!cvar("g_maplist_votable_suggestions_change_gametype"))
1810                 if(!IsSameGametype(m))
1811                         return "This server does not allow changing the game type by map suggestions.";
1812         if(!cvar("g_maplist_votable_override_mostrecent"))
1813                 if(Map_IsRecent(m))
1814                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1815
1816 #ifdef MAPINFO
1817         if(!MapInfo_CheckMap(m))
1818                 return "The map you suggested does not support the current game mode.";
1819 #else
1820         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1821                 return "The map you suggested is not available on this server.";
1822 #endif
1823         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1824                 if(mapvote_suggestions[i] == m)
1825                         return "This map was already suggested.";
1826         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1827         {
1828                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1829         }
1830         else
1831         {
1832                 i = mapvote_suggestion_ptr;
1833                 mapvote_suggestion_ptr += 1;
1834         }
1835         if(mapvote_suggestions[i] != "")
1836                 strunzone(mapvote_suggestions[i]);
1837         mapvote_suggestions[i] = strzone(m);
1838         GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid), ":", self.netname), TRUE);
1839         return "Suggestion accepted.";
1840 }
1841
1842 void MapVote_AddVotable(string nextMap, float isSuggestion)
1843 {
1844         float j;
1845         if(nextMap == "")
1846                 return;
1847         for(j = 0; j < mapvote_count; ++j)
1848                 if(mapvote_maps[j] == nextMap)
1849                         return;
1850         if(strlen(nextMap) > mapvote_maxlen)
1851                 mapvote_maxlen = strlen(nextMap);
1852         mapvote_maps[mapvote_count] = strzone(nextMap);
1853         mapvote_maps_suggested[mapvote_count] = isSuggestion;
1854         mapvote_count += 1;
1855 }
1856
1857 void MapVote_Init()
1858 {
1859         float i;
1860         float nmax, smax;
1861
1862         MapVote_ClearAllVotes();
1863
1864         nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1865         smax = min(nmax, cvar("g_maplist_votable_suggestions"));
1866         mapvote_count = 0;
1867
1868         for(i = 0; i < 100 && mapvote_count < smax; ++i)
1869                 MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
1870
1871         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1872                 MapVote_AddVotable(GetNextMap(), FALSE);
1873
1874         if(mapvote_count == 0)
1875         {
1876                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1877 #ifdef MAPINFO
1878                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
1879 #else
1880                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
1881 #endif
1882                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1883                         MapVote_AddVotable(GetNextMap(), FALSE);
1884         }
1885
1886         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1887
1888         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1889         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1890         if(mapvote_count < 3 || mapvote_keeptwotime <= time)
1891                 mapvote_keeptwotime = 0;
1892         mapvote_message = "Choose a map and press its key!";
1893 }
1894 float MapVote_Finished(float mappos)
1895 {
1896         string result;
1897         float i;
1898
1899         result = strcat(":vote:finished:", mapvote_maps[mappos]);
1900         result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1901         for(i = 0; i < mapvote_count; ++i)
1902                 if(i != mappos)
1903                         if(mapvote_maps[i] != "")
1904                         {
1905                                 result = strcat(result, ":", mapvote_maps[i]);
1906                                 result = strcat(result, ":", ftos(mapvote_votes[i]));
1907                         }
1908         GameLogEcho(result, FALSE);
1909         if(mapvote_maps_suggested[mappos])
1910                 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
1911
1912         FOR_EACH_REALCLIENT(other)
1913                 FixClientCvars(other);
1914
1915         Map_Goto_SetStr(mapvote_maps[mappos]);
1916         Map_Goto();
1917         alreadychangedlevel = TRUE;
1918         return TRUE;
1919 }
1920 void MapVote_CheckRules_1()
1921 {
1922         float i;
1923
1924         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1925         {
1926                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1927                 mapvote_votes[i] = 0;
1928         }
1929
1930         mapvote_voters = 0;
1931         FOR_EACH_REALCLIENT(other)
1932         {
1933                 ++mapvote_voters;
1934                 if(other.mapvote)
1935                 {
1936                         i = other.mapvote - 1;
1937                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
1938                         mapvote_votes[i] = mapvote_votes[i] + 1;
1939                 }
1940         }
1941 }
1942
1943 float MapVote_CheckRules_2()
1944 {
1945         float i;
1946         float firstPlace, secondPlace;
1947         float firstPlaceVotes, secondPlaceVotes;
1948         string result;
1949
1950         RandSel_Init();
1951         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1952                 RandSel_Add(mapvote_votes[i], i);
1953         firstPlace = randsel_value;
1954         firstPlaceVotes = randsel_priority;
1955         //dprint("First place: ", ftos(firstPlace), "\n");
1956         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
1957
1958         RandSel_Init();
1959         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1960                 if(i != firstPlace)
1961                         RandSel_Add(mapvote_votes[i], i);
1962         secondPlace = randsel_value;
1963         secondPlaceVotes = randsel_priority;
1964         //dprint("Second place: ", ftos(secondPlace), "\n");
1965         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
1966
1967         if(firstPlace == -1)
1968                 error("No first place in map vote... WTF?");
1969
1970         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters - firstPlaceVotes) < firstPlaceVotes)
1971                 return MapVote_Finished(firstPlace);
1972
1973         if(mapvote_keeptwotime)
1974                 if(time > mapvote_keeptwotime || (mapvote_voters - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
1975                 {
1976                         mapvote_message = "Now decide between the TOP TWO!";
1977                         mapvote_keeptwotime = 0;
1978                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
1979                         result = strcat(result, ":", ftos(firstPlaceVotes));
1980                         result = strcat(result, ":", mapvote_maps[secondPlace]);
1981                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
1982                         for(i = 0; i < mapvote_count; ++i)
1983                                 if(i != firstPlace)
1984                                         if(i != secondPlace)
1985                                                 if(mapvote_maps[i] != "")
1986                                                 {
1987                                                         result = strcat(result, ":", mapvote_maps[i]);
1988                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
1989                                                         strunzone(mapvote_maps[i]);
1990                                                         mapvote_maps[i] = "";
1991                                                 }
1992                         GameLogEcho(result, FALSE);
1993                 }
1994
1995         return FALSE;
1996 }
1997 void MapVote_Tick()
1998 {
1999         string msgstr;
2000         string tmp;
2001         float i;
2002         float keeptwo;
2003
2004         keeptwo = mapvote_keeptwotime;
2005         MapVote_CheckRules_1(); // count
2006         if(MapVote_CheckRules_2()) // decide
2007                 return;
2008
2009         FOR_EACH_REALCLIENT(other)
2010         {
2011                 // hide scoreboard again
2012                 if(other.health != 2342)
2013                 {
2014                         other.health = 2342;
2015                         other.impulse = 0;
2016                         if(clienttype(other) == CLIENTTYPE_REAL)
2017                         {
2018                                 stuffcmd(other, "\nin_bind 7 1 \"impulse 1\"; in_bind 7 2 \"impulse 2\"; in_bind 7 3 \"impulse 3\"; in_bind 7 4 \"impulse 4\"; in_bind 7 5 \"impulse 5\"; in_bind 7 6 \"impulse 6\"; in_bind 7 7 \"impulse 7\"; in_bind 7 8 \"impulse 8\"; in_bind 7 9 \"impulse 9\"; in_bind 7 0 \"impulse 10\"; in_bind 7 KP_1 \"impulse 1\"; in_bind 7 KP_2 \"impulse 2\"; in_bind 7 KP_3 \"impulse 3\"; in_bind 7 KP_4 \"impulse 4\"; in_bind 7 KP_5 \"impulse 5\"; in_bind 7 KP_6 \"impulse 6\"; in_bind 7 KP_7 \"impulse 7\"; in_bind 7 KP_8 \"impulse 8\"; in_bind 7 KP_9 \"impulse 9\"; in_bind 7 KP_0 \"impulse 10\"; in_bindmap 7 0\n");
2019                                 msg_entity = other;
2020                                 WriteByte(MSG_ONE, SVC_FINALE);
2021                                 WriteString(MSG_ONE, "");
2022                                 /*
2023                                 for(i = 0; i < mapvote_count; ++i)
2024                                         if(mapvote_maps[i] != "")
2025                                         {
2026                                                 tmp = mapvote_maps[i];
2027                                                 sprint(other, strcat("map voting: type ^1impulse ", ftos(i+1), "^7 to vote for ", tmp, "\n"));
2028                                         }
2029                                 */
2030                         }
2031                 }
2032
2033                 // notify about keep-two
2034                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2035                         play2(other, "misc/invshot.wav");
2036
2037                 // clear possibly invalid votes
2038                 if(mapvote_maps[other.mapvote - 1] == "")
2039                         other.mapvote = 0;
2040                 // use impulses as new vote
2041                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2042                         if(mapvote_maps[other.impulse - 1] != "")
2043                                 other.mapvote = other.impulse;
2044                 other.impulse = 0;
2045         }
2046
2047         MapVote_CheckRules_1(); // just count
2048
2049         FOR_EACH_REALCLIENT(other)
2050         {
2051                 // display voting screen
2052                 msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2053                 msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2054                 msgstr = strcat(msgstr, mapvote_message);
2055                 msgstr = strcat(msgstr, "\n\n");
2056                 for(i = 0; i < mapvote_count; ++i)
2057                         if(mapvote_maps[i] == "")
2058                                 msgstr = strcat(msgstr, "\n");
2059                         else
2060                         {
2061                                 tmp = mapvote_maps[i];
2062                                 tmp = strpad(mapvote_maxlen, tmp);
2063                                 tmp = strcat(ftos(math_mod(i + 1, 10)), ": ", tmp);
2064                                 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2065                                 if(mapvote_votes[i] != 1)
2066                                         tmp = strcat(tmp, "s");
2067                                 tmp = strcat(tmp, ")");
2068                                 tmp = strpad(mapvote_maxlen + 15, tmp);
2069                                 if(other.mapvote == i + 1)
2070                                         msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2071                                 else
2072                                         msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2073                         }
2074                 i = ceil(mapvote_timeout - time);
2075                 msgstr = strcat(msgstr, "\n\n", ftos(i), " second");
2076                 if(i != 1)
2077                         msgstr = strcat(msgstr, "s");
2078                 msgstr = strcat(msgstr, " left");
2079
2080                 centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2081         }
2082 }
2083 void MapVote_Start()
2084 {
2085         if(mapvote_run)
2086                 return;
2087
2088 #ifdef MAPINFO
2089         MapInfo_Enumerate();
2090         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures()))
2091 #endif
2092                 mapvote_run = TRUE;
2093 }
2094 void MapVote_Think()
2095 {
2096         if(!mapvote_run)
2097                 return;
2098
2099         if(alreadychangedlevel)
2100                 return;
2101
2102         if(time < mapvote_nextthink)
2103                 return;
2104         //dprint("tick\n");
2105
2106         mapvote_nextthink = time + 0.5;
2107
2108         if(!mapvote_initialized)
2109         {
2110                 mapvote_initialized = TRUE;
2111                 if(DoNextMapOverride())
2112                         return;
2113                 if(!cvar("g_maplist_votable") || player_count <= 0)
2114                 {
2115                         GotoNextMap();
2116                         return;
2117                 }
2118                 MapVote_Init();
2119         }
2120
2121         MapVote_Tick();
2122 };
2123
2124 string GotoMap(string m)
2125 {
2126 #ifdef MAPINFO
2127         if(!MapInfo_CheckMap(m))
2128 #else
2129         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2130 #endif
2131                 return "The map you chose is not available on this server.";
2132         cvar_set("nextmap", m);
2133         cvar_set("timelimit", "-1");
2134         if(mapvote_initialized || alreadychangedlevel)
2135         {
2136                 if(DoNextMapOverride())
2137                         return "Map switch initiated.";
2138                 else
2139                         return "Hm... no. For some reason I like THIS map more.";
2140         }
2141         else
2142                 return "Map switch will happen after scoreboard.";
2143 }
2144
2145
2146 void EndFrame()
2147 {
2148         FOR_EACH_REALCLIENT(self)
2149         {
2150                 if(self.classname == "spectator")
2151                 {
2152                         if(self.enemy.hitsound)
2153                                 play2(self, "misc/hit.wav");
2154                 }
2155                 else
2156                 {
2157                         if(self.hitsound)
2158                                 play2(self, "misc/hit.wav");
2159                 }
2160         }
2161         FOR_EACH_CLIENT(self)
2162                 self.hitsound = FALSE;
2163 }
2164
2165
2166 /*
2167  * RedirectionThink:
2168  * returns TRUE if redirecting
2169  */
2170 float redirection_timeout;
2171 float redirection_nextthink;
2172 float RedirectionThink()
2173 {
2174         float clients_found;
2175
2176         if(redirection_target == "")
2177                 return FALSE;
2178
2179         if(!redirection_timeout)
2180         {
2181                 cvar_set("sv_public", "-2");
2182                 redirection_timeout = time + 0.5; // this will only try twice... should be able to keep more clients
2183                 if(redirection_target == "self")
2184                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2185                 else
2186                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2187         }
2188
2189         if(time < redirection_nextthink)
2190                 return TRUE;
2191
2192         redirection_nextthink = time + 1;
2193
2194         clients_found = 0;
2195         FOR_EACH_REALCLIENT(self)
2196         {
2197                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2198                 if(redirection_target == "self")
2199                         stuffcmd(self, "\ndisconnect; reconnect\n");
2200                 else
2201                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2202                 ++clients_found;
2203         }
2204
2205         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2206
2207         if(time > redirection_timeout || clients_found == 0)
2208                 localcmd("\nwait; wait; wait; quit\n");
2209
2210         return TRUE;
2211 }