]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
handle aborting when a mapinfo has been generated in a better way
[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                         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0);
71 #endif
72
73                         if(!DoNextMapOverride())
74                                 GotoNextMap();
75                 }
76         }
77 }
78
79 float world_already_spawned;
80 void worldspawn (void)
81 {
82         float globhandle, i, n;
83
84         dprint_load(); // load dprint status from cvar
85
86         if(world_already_spawned)
87                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
88         world_already_spawned = TRUE;
89
90         sv_cheats = cvar("sv_cheats");
91
92         /*
93         TODO sound pack system
94         // initialize sound pack system
95         soundpack = cvar_string("g_soundpack");
96         if(soundpack != "")
97                 soundpack = strcat(soundpack, "/");
98         soundpack = strzone(soundpack);
99         */
100
101         // gamemode related things
102         precache_model ("models/misc/chatbubble.spr");
103         precache_model ("models/misc/teambubble.spr");
104         if (cvar("g_runematch"))
105         {
106                 precache_model ("models/runematch/curse.mdl");
107                 precache_model ("models/runematch/rune.mdl");
108         }
109
110         // Precache all player models if desired
111         if (cvar("sv_precacheplayermodels"))
112         {
113                 globhandle = search_begin("models/player/*.zym", TRUE, FALSE);
114                 n = search_getsize(globhandle);
115                 for(i = 0; i < n; ++i)
116                 {
117                         //print(search_getfilename(globhandle, i), "\n");
118                         precache_model(search_getfilename(globhandle, i));
119                 }
120                 search_end(globhandle);
121                 //precache_model("models/player/carni.zym");
122                 //precache_model("models/player/crash.zym");
123                 //precache_model("models/player/grunt.zym");
124                 //precache_model("models/player/headhunter.zym");
125                 //precache_model("models/player/insurrectionist.zym");
126                 //precache_model("models/player/jeandarc.zym");
127                 //precache_model("models/player/lurk.zym");
128                 //precache_model("models/player/lycanthrope.zym");
129                 //precache_model("models/player/marine.zym");
130                 //precache_model("models/player/nexus.zym");
131                 //precache_model("models/player/pyria.zym");
132                 //precache_model("models/player/shock.zym");
133                 //precache_model("models/player/skadi.zym");
134                 //precache_model("models/player/specop.zym");
135                 //precache_model("models/player/visitant.zym");
136         }
137
138         if (g_footsteps)
139         {
140                 precache_sound ("misc/footstep01.wav");
141                 precache_sound ("misc/footstep02.wav");
142                 precache_sound ("misc/footstep03.wav");
143                 precache_sound ("misc/footstep04.wav");
144                 precache_sound ("misc/footstep05.wav");
145                 precache_sound ("misc/footstep06.wav");
146         }
147
148         // gore and miscellaneous sounds
149         //precache_sound ("misc/h2ohit.wav");
150         precache_model ("models/gibs/bloodyskull.md3");
151         precache_model ("models/gibs/chunk.mdl");
152         precache_model ("models/gibs/eye.md3");
153         precache_model ("models/gibs/gib1.md3");
154         precache_model ("models/gibs/gib1.mdl");
155         precache_model ("models/gibs/gib2.mdl");
156         precache_model ("models/gibs/gib3.mdl");
157         precache_model ("models/gibs/gib5.md3");
158         precache_model ("models/hook.md3");
159         precache_sound ("misc/armorimpact.wav");
160         precache_sound ("misc/bodyimpact1.wav");
161         precache_sound ("misc/bodyimpact2.wav");
162         precache_sound ("misc/gib.wav");
163         precache_sound ("misc/gib_splat01.wav");
164         precache_sound ("misc/gib_splat02.wav");
165         precache_sound ("misc/gib_splat03.wav");
166         precache_sound ("misc/gib_splat04.wav");
167         precache_sound ("misc/hit.wav");
168         precache_sound ("misc/hitground1.wav");
169         precache_sound ("misc/hitground2.wav");
170         precache_sound ("misc/hitground3.wav");
171         precache_sound ("misc/hitground4.wav");
172         precache_sound ("misc/null.wav");
173         precache_sound ("misc/spawn.wav");
174         precache_sound ("misc/talk.wav");
175         precache_sound ("misc/teleport.wav");
176         precache_sound ("player/lava.wav");
177         precache_sound ("player/slime.wav");
178
179         // announcer sounds - male
180         //precache_sound ("announcer/male/electrobitch.wav");
181         precache_sound ("announcer/male/03kills.wav");
182         precache_sound ("announcer/male/05kills.wav");
183         precache_sound ("announcer/male/10kills.wav");
184         precache_sound ("announcer/male/15kills.wav");
185         precache_sound ("announcer/male/20kills.wav");
186         precache_sound ("announcer/male/25kills.wav");
187         precache_sound ("announcer/male/30kills.wav");
188         precache_sound ("announcer/male/botlike.wav");
189         precache_sound ("announcer/male/yoda.wav");
190
191         // announcer sounds - robotic
192         precache_sound ("announcer/robotic/1fragleft.wav");
193         precache_sound ("announcer/robotic/1minuteremains.wav");
194         precache_sound ("announcer/robotic/2fragsleft.wav");
195         precache_sound ("announcer/robotic/3fragsleft.wav");
196         if (g_minstagib)
197         {
198                 precache_sound ("announcer/robotic/lastsecond.wav");
199                 precache_sound ("announcer/robotic/narrowly.wav");
200                 precache_sound ("announcer/robotic/1.wav");
201                 precache_sound ("announcer/robotic/2.wav");
202                 precache_sound ("announcer/robotic/3.wav");
203                 precache_sound ("announcer/robotic/4.wav");
204                 precache_sound ("announcer/robotic/5.wav");
205                 precache_sound ("announcer/robotic/6.wav");
206                 precache_sound ("announcer/robotic/7.wav");
207                 precache_sound ("announcer/robotic/8.wav");
208                 precache_sound ("announcer/robotic/9.wav");
209                 precache_sound ("announcer/robotic/10.wav");
210         }
211
212         // common weapon precaches
213         precache_sound ("weapons/weapon_switch.wav");
214         precache_sound ("weapons/weaponpickup.wav");
215         if (g_grappling_hook)
216         {
217                 precache_sound ("weapons/hook_fire.wav"); // hook
218                 precache_sound ("weapons/hook_impact.wav"); // hook
219         }
220
221         if (cvar("sv_precacheweapons") || g_nixnex)
222         {
223                 //precache weapon models/sounds
224                 local float wep;
225                 wep = WEP_FIRST;
226                 while (wep <= WEP_LAST)
227                 {
228                         weapon_action(wep, WR_PRECACHE);
229                         wep = wep + 1;
230                 }
231         }
232
233         // plays music for the level if there is any
234         if (self.noise)
235         {
236                 precache_sound (self.noise);
237                 ambientsound ('0 0 0', self.noise, 1.00, ATTN_NONE);
238         }
239
240         // 0 normal
241         lightstyle(0, "m");
242
243         // 1 FLICKER (first variety)
244         lightstyle(1, "mmnmmommommnonmmonqnmmo");
245
246         // 2 SLOW STRONG PULSE
247         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
248
249         // 3 CANDLE (first variety)
250         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
251
252         // 4 FAST STROBE
253         lightstyle(4, "mamamamamama");
254
255         // 5 GENTLE PULSE 1
256         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
257
258         // 6 FLICKER (second variety)
259         lightstyle(6, "nmonqnmomnmomomno");
260
261         // 7 CANDLE (second variety)
262         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
263
264         // 8 CANDLE (third variety)
265         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
266
267         // 9 SLOW STROBE (fourth variety)
268         lightstyle(9, "aaaaaaaazzzzzzzz");
269
270         // 10 FLUORESCENT FLICKER
271         lightstyle(10, "mmamammmmammamamaaamammma");
272
273         // 11 SLOW PULSE NOT FADE TO BLACK
274         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
275
276         // styles 32-62 are assigned by the light program for switchable lights
277
278         // 63 testing
279         lightstyle(63, "a");
280
281         player_count = 0;
282         lms_lowest_lives = 0;
283         lms_next_place = 0;
284
285         GotoFirstMap();
286
287         bot_waypoints_for_items = cvar("g_waypoints_for_items");
288         if(bot_waypoints_for_items == 1)
289                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
290                         bot_waypoints_for_items = 0;
291
292         if(cvar("g_campaign"))
293                 CampaignPreInit();
294
295         InitGameplayMode();
296
297         WaypointSprite_Init();
298
299         //if (cvar("g_domination"))
300         //      dom_init();
301
302         local entity head;
303         head = nextent(world);
304         maxclients = 0;
305         while(head)
306         {
307                 maxclients++;
308                 head = nextent(head);
309         }
310
311         GameLogInit(); // prepare everything
312         if(cvar("sv_eventlog"))
313         {
314                 local string s;
315                 GameLogEcho(":logversion:2", FALSE);
316                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
317                 s = strcat(s, ftos(random()));
318                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
319                 s = ":gameinfo:mutators:LIST";
320                 if(g_grappling_hook)
321                         s = strcat(s, ":grappling_hook");
322                 if(!cvar("g_use_ammunition"))
323                         s = strcat(s, ":no_use_ammunition");
324                 if(!cvar("g_pickup_items"))
325                         s = strcat(s, ":no_pickup_items");
326                 if(g_instagib)
327                         s = strcat(s, ":instagib");
328                 if(g_rocketarena)
329                         s = strcat(s, ":rockerarena");
330                 if(g_nixnex)
331                         s = strcat(s, ":nixnex");
332                 if(g_vampire)
333                         s = strcat(s, ":vampire");
334                 if(g_laserguided_missile)
335                         s = strcat(s, ":laserguided_missile");
336                 if(g_norecoil)
337                         s = strcat(s, ":norecoil");
338                 if(g_midair)
339                         s = strcat(s, ":midair");
340                 if(g_minstagib)
341                         s = strcat(s, ":minstagib");
342                 GameLogEcho(s, FALSE);
343                 GameLogEcho(":gameinfo:end", FALSE);
344         }
345
346         cvar_set("nextmap", "");
347
348         SetDefaultAlpha();
349
350         if(cvar("g_campaign"))
351                 CampaignPostInit();
352
353         fteqcc_testbugs();
354
355         readlevelcvars();
356
357         Ban_LoadBans();
358
359 #ifdef MAPINFO
360         MapInfo_Enumerate();
361         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1);
362 #endif
363 }
364
365 void light (void)
366 {
367         //makestatic (self); // Who the f___ did that?
368         remove(self);
369 }
370
371 float( string pFilename ) TryFile =
372 {
373         local float lHandle;
374         dprint("TryFile(\"", pFilename, "\")\n");
375         lHandle = fopen( pFilename, FILE_READ );
376         if( lHandle != -1 ) {
377                 fclose( lHandle );
378                 return TRUE;
379         } else {
380                 return FALSE;
381         }
382 };
383
384 string GetGametype()
385 {
386         if (game == GAME_DEATHMATCH)
387                 return "dm";
388         else if (game == GAME_TEAM_DEATHMATCH)
389                 return "tdm";
390         else if (game == GAME_DOMINATION)
391                 return "dom";
392         else if (game == GAME_CTF)
393                 return "ctf";
394         else if (game == GAME_RUNEMATCH)
395                 return "rune";
396         else if (game == GAME_LMS)
397                 return "lms";
398         else if (game == GAME_KEYHUNT)
399                 return "kh";
400         else if (game == GAME_ONSLAUGHT)
401                 return "ons";
402         else if (game == GAME_ASSAULT)
403                 return "as";
404         return "dm";
405 }
406
407 float IsSameGametype(string mapcfgname)
408 {
409 #ifdef MAPINFO
410         return TRUE; // can't change game type by map name here
411 #else
412         string gt;
413         gt = GetGametype();
414         if(substring(mapcfgname, 0, strlen(gt) + 1) == strcat(gt, "_"))
415                 return TRUE;
416         return FALSE;
417 #endif
418 }
419
420 string getmapname_stored;
421 string GetMapname()
422 {
423 #ifdef MAPINFO
424         return mapname;
425 #else
426         if(getmapname_stored == "")
427                 getmapname_stored = strzone(strcat(GetGametype(), "_", mapname));
428         return getmapname_stored;
429 #endif
430 }
431
432 float Map_Count, Map_Current;
433 string Map_Current_Name;
434
435 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
436 float GetMaplistPosition()
437 {
438         float pos, idx;
439         string map;
440
441         map = GetMapname();
442         idx = cvar("g_maplist_index");
443
444         if(idx >= 0)
445                 if(idx < Map_Count)
446                         if(map == argv(idx))
447                                 return idx;
448
449         for(pos = 0; pos < Map_Count; ++pos)
450                 if(map == argv(pos))
451                         return pos;
452
453         // resume normal maplist rotation if current map is not in g_maplist
454         return idx;
455 }
456
457 float MapHasRightSize(string map)
458 {
459         // open map size restriction file
460         float fh;
461         dprint("opensize "); dprint(map);
462         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
463         if(fh >= 0)
464         {
465                 float mapmin, mapmax;
466                 dprint(": ok, ");
467                 mapmin = stof(fgets(fh));
468                 mapmax = stof(fgets(fh));
469                 fclose(fh);
470                 if(player_count < mapmin)
471                 {
472                         dprint("not enough\n");
473                         return FALSE;
474                 }
475                 if(player_count > mapmax)
476                 {
477                         dprint("too many\n");
478                         return FALSE;
479                 }
480                 dprint("right size\n");
481                 return TRUE;
482         }
483         dprint(": not found\n");
484         return TRUE;
485 }
486
487 #ifdef MAPINFO
488 #else
489 string Map_Filename(float position)
490 {
491         // FIXME unused
492         return strcat("maps/", argv(position), ".mapcfg");
493 }
494 #endif
495
496 string strwords(string s, float w)
497 {
498         float endpos;
499         for(endpos = 0; w && endpos >= 0; --w)
500                 endpos = strstrofs(s, " ", endpos + 1);
501         if(endpos < 0)
502                 return s;
503         else
504                 return substring(s, 0, endpos);
505 }
506
507 float strhasword(string s, string w)
508 {
509         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
510 }
511
512 void Map_MarkAsRecent(string m)
513 {
514         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
515 }
516
517 float Map_IsRecent(string m)
518 {
519         return strhasword(cvar_string("g_maplist_mostrecent"), m);
520 }
521
522 float(float position, float pass) Map_Check =
523 {
524         string filename;
525         string map_next;
526         map_next = argv(position);
527         if(pass <= 1)
528         {
529                 if(map_next == Map_Current_Name) // same map again in first pass?
530                         return 0;
531                 if(Map_IsRecent(map_next))
532                         return 0;
533         }
534 #ifdef MAPINFO
535         if(MapInfo_CheckMap(argv(position)))
536 #else
537         filename = Map_Filename(position);
538         if(TryFile(filename))
539 #endif
540         {
541                 if(pass == 2)
542                         return 1;
543                 if(MapHasRightSize(argv(position)))
544                         return 1;
545                 return 0;
546         }
547         else
548                 dprint( "Couldn't find '", filename, "'..\n" );
549
550         return 0;
551 }
552
553 void(string nextmapname) Map_Goto_SetStr =
554 {
555         if(getmapname_stored != "")
556                 strunzone(getmapname_stored);
557         if(nextmapname == "")
558                 getmapname_stored = "";
559         else
560                 getmapname_stored = strzone(nextmapname);
561 }
562
563 void(float position) Map_Goto_SetFloat =
564 {
565         cvar_set("g_maplist_index", ftos(position));
566         Map_Goto_SetStr(argv(position));
567 }
568
569 void() GameResetCfg =
570 {
571 #ifdef MAPINFO
572         // settings persist, except...
573         if(cvar("g_campaign"))
574                 localcmd("\nexec mutator_reset.cfg\n");
575         localcmd("\nsettemp_restore\n");
576 #else
577         // if an exit cfg is defined by exiting map, exec it.
578         string exit_cfg;
579         exit_cfg = cvar_string("exit_cfg");
580         if(exit_cfg != "")
581                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
582
583         localcmd("exec game_reset.cfg\n");
584 #endif
585
586         Ban_SaveBans();
587 };
588
589 void() Map_Goto =
590 {
591         Map_MarkAsRecent(getmapname_stored);
592         GameResetCfg();
593 #ifdef MAPINFO
594         MapInfo_LoadMap(getmapname_stored);
595 #else
596         localcmd(strcat("exec \"maps/", getmapname_stored ,".mapcfg\"\n"));
597 #endif
598 }
599
600 // return codes of map selectors:
601 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
602 //   -2 = permanent failure
603 float() MaplistMethod_Iterate = // usual method
604 {
605         float pass, i;
606
607         for(pass = 1; pass <= 2; ++pass)
608         {
609                 for(i = 1; i < Map_Count; ++i)
610                 {
611                         float mapindex;
612                         mapindex = math_mod(i + Map_Current, Map_Count);
613                         if(Map_Check(mapindex, pass))
614                                 return mapindex;
615                 }
616         }
617         return -1;
618 }
619
620 float() MaplistMethod_Repeat = // fallback method
621 {
622         if(Map_Check(Map_Current, 2))
623                 return Map_Current;
624         return -2;
625 }
626
627 float() MaplistMethod_Random = // random map selection
628 {
629         float i, imax;
630
631         imax = 42;
632
633         for(i = 0; i <= imax; ++i)
634         {
635                 float mapindex;
636                 mapindex = math_mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
637                 if(Map_Check(mapindex, 1))
638                         return mapindex;
639         }
640         return -1;
641 }
642
643 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
644 // the exponent sets a bias on the map selection:
645 // the higher the exponent, the less likely "shortly repeated" same maps are
646 {
647         float i, j, imax, insertpos;
648
649         imax = 42;
650
651         if(Map_Count <= 1)
652                 return 0; // only one map, then always play this one
653
654         for(i = 0; i <= imax; ++i)
655         {
656                 string newlist;
657
658                 // now reinsert this at another position
659                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
660                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
661                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
662                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
663
664                 // insert the current map there
665                 newlist = "";
666 #ifdef MAPINFO
667                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
668                         newlist = strcat(newlist, " ", argv(j));
669                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
670                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
671                         newlist = strcat(newlist, " ", argv(j));
672                 newlist = substring(newlist, 1, strlen(newlist) - 1);
673 #else
674                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
675                         newlist = strcat(newlist, "'", argv(j), "'");
676                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
677                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
678                         newlist = strcat(newlist, "'", argv(j), "'");
679 #endif
680                 cvar_set("g_maplist", newlist);
681                 Map_Count = tokenize(newlist);
682
683                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
684                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
685                 if(Map_Check(Map_Current, 1))
686                         return Map_Current;
687         }
688         return -1;
689 }
690
691 void() Maplist_Init =
692 {
693         string temp;
694         temp = cvar_string("g_maplist");
695         Map_Count = tokenize(temp);
696         if(Map_Count == 0)
697         {
698                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
699 #ifdef MAPINFO
700                 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps());
701                 localcmd("\nmenu_cmd sync\n");
702 #else
703                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
704 #endif
705                 Map_Count = tokenize(temp);
706         }
707         if(Map_Count == 0)
708                 error("empty maplist, cannot select a new map");
709         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
710
711         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
712         // this may or may not be correct, but who cares, in the worst case a map
713         // isn't chosen in the first pass that should have been
714 }
715
716 string() GetNextMap =
717 {
718         float nextMap;
719
720         Maplist_Init();
721         nextMap = -1;
722
723         if(nextMap == -1)
724                 if(cvar("g_maplist_shuffle") > 0)
725                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
726
727         if(nextMap == -1)
728                 if(cvar("g_maplist_selectrandom"))
729                         nextMap = MaplistMethod_Random();
730
731         if(nextMap == -1)
732                 nextMap = MaplistMethod_Iterate();
733
734         if(nextMap == -1)
735                 nextMap = MaplistMethod_Repeat();
736
737         if(nextMap >= 0)
738         {
739                 Map_Goto_SetFloat(nextMap);
740                 return getmapname_stored;
741         }
742
743         return "";
744 };
745
746 float() DoNextMapOverride =
747 {
748         Ban_SaveBans();
749
750         if(cvar("g_campaign"))
751         {
752                 CampaignPostIntermission();
753                 alreadychangedlevel = TRUE;
754                 return TRUE;
755         }
756         if(cvar("quit_when_empty"))
757         {
758                 if(player_count <= currentbots)
759                 {
760                         localcmd("quit\n");
761                         alreadychangedlevel = TRUE;
762                         return TRUE;
763                 }
764         }
765         if(cvar_string("quit_and_redirect") != "")
766         {
767                 redirection_target = strzone(cvar_string("quit_and_redirect"));
768                 alreadychangedlevel = TRUE;
769                 return TRUE;
770         }
771         if (cvar("samelevel")) // if samelevel is set, stay on same level
772         {
773                 // 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)
774                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
775                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
776                 localcmd("restart\n");
777                 //changelevel (mapname);
778                 alreadychangedlevel = TRUE;
779                 return TRUE;
780         }
781         if(cvar_string("nextmap") != "")
782 #ifdef MAPINFO
783                 if(MapInfo_CheckMap(cvar_string("nextmap")))
784 #else
785                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
786 #endif
787                 {
788                         Map_Goto_SetStr(cvar_string("nextmap"));
789                         Map_Goto();
790                         alreadychangedlevel = TRUE;
791                         return TRUE;
792                 }
793         if(cvar("lastlevel"))
794         {
795                 GameResetCfg();
796                 localcmd("set lastlevel 0\ntogglemenu\n");
797                 alreadychangedlevel = TRUE;
798                 return TRUE;
799         }
800         return FALSE;
801 };
802
803 void() GotoNextMap =
804 {
805         //local string nextmap;
806         //local float n, nummaps;
807         //local string s;
808         if (alreadychangedlevel)
809                 return;
810         alreadychangedlevel = TRUE;
811
812         {
813                 string nextMap;
814                 float allowReset;
815
816                 for(allowReset = 1; allowReset >= 0; --allowReset)
817                 {
818                         nextMap = GetNextMap();
819                         if(nextMap != "")
820                                 break;
821
822                         if(allowReset)
823                         {
824                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
825 #ifdef MAPINFO
826                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
827                                 localcmd("\nmenu_cmd sync\n");
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                 localcmd("\nmenu_cmd sync\n");
1880 #else
1881                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
1882 #endif
1883                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1884                         MapVote_AddVotable(GetNextMap(), FALSE);
1885         }
1886
1887         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1888
1889         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1890         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1891         if(mapvote_count < 3 || mapvote_keeptwotime <= time)
1892                 mapvote_keeptwotime = 0;
1893         mapvote_message = "Choose a map and press its key!";
1894 }
1895 float MapVote_Finished(float mappos)
1896 {
1897         string result;
1898         float i;
1899
1900         result = strcat(":vote:finished:", mapvote_maps[mappos]);
1901         result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1902         for(i = 0; i < mapvote_count; ++i)
1903                 if(i != mappos)
1904                         if(mapvote_maps[i] != "")
1905                         {
1906                                 result = strcat(result, ":", mapvote_maps[i]);
1907                                 result = strcat(result, ":", ftos(mapvote_votes[i]));
1908                         }
1909         GameLogEcho(result, FALSE);
1910         if(mapvote_maps_suggested[mappos])
1911                 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
1912
1913         FOR_EACH_REALCLIENT(other)
1914                 FixClientCvars(other);
1915
1916         Map_Goto_SetStr(mapvote_maps[mappos]);
1917         Map_Goto();
1918         alreadychangedlevel = TRUE;
1919         return TRUE;
1920 }
1921 void MapVote_CheckRules_1()
1922 {
1923         float i;
1924
1925         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1926         {
1927                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1928                 mapvote_votes[i] = 0;
1929         }
1930
1931         mapvote_voters = 0;
1932         FOR_EACH_REALCLIENT(other)
1933         {
1934                 ++mapvote_voters;
1935                 if(other.mapvote)
1936                 {
1937                         i = other.mapvote - 1;
1938                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
1939                         mapvote_votes[i] = mapvote_votes[i] + 1;
1940                 }
1941         }
1942 }
1943
1944 float MapVote_CheckRules_2()
1945 {
1946         float i;
1947         float firstPlace, secondPlace;
1948         float firstPlaceVotes, secondPlaceVotes;
1949         string result;
1950
1951         RandSel_Init();
1952         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1953                 RandSel_Add(mapvote_votes[i], i);
1954         firstPlace = randsel_value;
1955         firstPlaceVotes = randsel_priority;
1956         //dprint("First place: ", ftos(firstPlace), "\n");
1957         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
1958
1959         RandSel_Init();
1960         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1961                 if(i != firstPlace)
1962                         RandSel_Add(mapvote_votes[i], i);
1963         secondPlace = randsel_value;
1964         secondPlaceVotes = randsel_priority;
1965         //dprint("Second place: ", ftos(secondPlace), "\n");
1966         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
1967
1968         if(firstPlace == -1)
1969                 error("No first place in map vote... WTF?");
1970
1971         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters - firstPlaceVotes) < firstPlaceVotes)
1972                 return MapVote_Finished(firstPlace);
1973
1974         if(mapvote_keeptwotime)
1975                 if(time > mapvote_keeptwotime || (mapvote_voters - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
1976                 {
1977                         mapvote_message = "Now decide between the TOP TWO!";
1978                         mapvote_keeptwotime = 0;
1979                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
1980                         result = strcat(result, ":", ftos(firstPlaceVotes));
1981                         result = strcat(result, ":", mapvote_maps[secondPlace]);
1982                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
1983                         for(i = 0; i < mapvote_count; ++i)
1984                                 if(i != firstPlace)
1985                                         if(i != secondPlace)
1986                                                 if(mapvote_maps[i] != "")
1987                                                 {
1988                                                         result = strcat(result, ":", mapvote_maps[i]);
1989                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
1990                                                         strunzone(mapvote_maps[i]);
1991                                                         mapvote_maps[i] = "";
1992                                                 }
1993                         GameLogEcho(result, FALSE);
1994                 }
1995
1996         return FALSE;
1997 }
1998 void MapVote_Tick()
1999 {
2000         string msgstr;
2001         string tmp;
2002         float i;
2003         float keeptwo;
2004
2005         keeptwo = mapvote_keeptwotime;
2006         MapVote_CheckRules_1(); // count
2007         if(MapVote_CheckRules_2()) // decide
2008                 return;
2009
2010         FOR_EACH_REALCLIENT(other)
2011         {
2012                 // hide scoreboard again
2013                 if(other.health != 2342)
2014                 {
2015                         other.health = 2342;
2016                         other.impulse = 0;
2017                         if(clienttype(other) == CLIENTTYPE_REAL)
2018                         {
2019                                 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");
2020                                 msg_entity = other;
2021                                 WriteByte(MSG_ONE, SVC_FINALE);
2022                                 WriteString(MSG_ONE, "");
2023                                 /*
2024                                 for(i = 0; i < mapvote_count; ++i)
2025                                         if(mapvote_maps[i] != "")
2026                                         {
2027                                                 tmp = mapvote_maps[i];
2028                                                 sprint(other, strcat("map voting: type ^1impulse ", ftos(i+1), "^7 to vote for ", tmp, "\n"));
2029                                         }
2030                                 */
2031                         }
2032                 }
2033
2034                 // notify about keep-two
2035                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2036                         play2(other, "misc/invshot.wav");
2037
2038                 // clear possibly invalid votes
2039                 if(mapvote_maps[other.mapvote - 1] == "")
2040                         other.mapvote = 0;
2041                 // use impulses as new vote
2042                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2043                         if(mapvote_maps[other.impulse - 1] != "")
2044                                 other.mapvote = other.impulse;
2045                 other.impulse = 0;
2046         }
2047
2048         MapVote_CheckRules_1(); // just count
2049
2050         FOR_EACH_REALCLIENT(other)
2051         {
2052                 // display voting screen
2053                 msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2054                 msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2055                 msgstr = strcat(msgstr, mapvote_message);
2056                 msgstr = strcat(msgstr, "\n\n");
2057                 for(i = 0; i < mapvote_count; ++i)
2058                         if(mapvote_maps[i] == "")
2059                                 msgstr = strcat(msgstr, "\n");
2060                         else
2061                         {
2062                                 tmp = mapvote_maps[i];
2063                                 tmp = strpad(mapvote_maxlen, tmp);
2064                                 tmp = strcat(ftos(math_mod(i + 1, 10)), ": ", tmp);
2065                                 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2066                                 if(mapvote_votes[i] != 1)
2067                                         tmp = strcat(tmp, "s");
2068                                 tmp = strcat(tmp, ")");
2069                                 tmp = strpad(mapvote_maxlen + 15, tmp);
2070                                 if(other.mapvote == i + 1)
2071                                         msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2072                                 else
2073                                         msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2074                         }
2075                 i = ceil(mapvote_timeout - time);
2076                 msgstr = strcat(msgstr, "\n\n", ftos(i), " second");
2077                 if(i != 1)
2078                         msgstr = strcat(msgstr, "s");
2079                 msgstr = strcat(msgstr, " left");
2080
2081                 centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2082         }
2083 }
2084 void MapVote_Start()
2085 {
2086         if(mapvote_run)
2087                 return;
2088
2089 #ifdef MAPINFO
2090         MapInfo_Enumerate();
2091         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1))
2092 #endif
2093                 mapvote_run = TRUE;
2094 }
2095 void MapVote_Think()
2096 {
2097         if(!mapvote_run)
2098                 return;
2099
2100         if(alreadychangedlevel)
2101                 return;
2102
2103         if(time < mapvote_nextthink)
2104                 return;
2105         //dprint("tick\n");
2106
2107         mapvote_nextthink = time + 0.5;
2108
2109         if(!mapvote_initialized)
2110         {
2111                 mapvote_initialized = TRUE;
2112                 if(DoNextMapOverride())
2113                         return;
2114                 if(!cvar("g_maplist_votable") || player_count <= 0)
2115                 {
2116                         GotoNextMap();
2117                         return;
2118                 }
2119                 MapVote_Init();
2120         }
2121
2122         MapVote_Tick();
2123 };
2124
2125 string GotoMap(string m)
2126 {
2127 #ifdef MAPINFO
2128         if(!MapInfo_CheckMap(m))
2129 #else
2130         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2131 #endif
2132                 return "The map you chose is not available on this server.";
2133         cvar_set("nextmap", m);
2134         cvar_set("timelimit", "-1");
2135         if(mapvote_initialized || alreadychangedlevel)
2136         {
2137                 if(DoNextMapOverride())
2138                         return "Map switch initiated.";
2139                 else
2140                         return "Hm... no. For some reason I like THIS map more.";
2141         }
2142         else
2143                 return "Map switch will happen after scoreboard.";
2144 }
2145
2146
2147 void EndFrame()
2148 {
2149         FOR_EACH_REALCLIENT(self)
2150         {
2151                 if(self.classname == "spectator")
2152                 {
2153                         if(self.enemy.hitsound)
2154                                 play2(self, "misc/hit.wav");
2155                 }
2156                 else
2157                 {
2158                         if(self.hitsound)
2159                                 play2(self, "misc/hit.wav");
2160                 }
2161         }
2162         FOR_EACH_CLIENT(self)
2163                 self.hitsound = FALSE;
2164 }
2165
2166
2167 /*
2168  * RedirectionThink:
2169  * returns TRUE if redirecting
2170  */
2171 float redirection_timeout;
2172 float redirection_nextthink;
2173 float RedirectionThink()
2174 {
2175         float clients_found;
2176
2177         if(redirection_target == "")
2178                 return FALSE;
2179
2180         if(!redirection_timeout)
2181         {
2182                 cvar_set("sv_public", "-2");
2183                 redirection_timeout = time + 0.5; // this will only try twice... should be able to keep more clients
2184                 if(redirection_target == "self")
2185                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2186                 else
2187                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2188         }
2189
2190         if(time < redirection_nextthink)
2191                 return TRUE;
2192
2193         redirection_nextthink = time + 1;
2194
2195         clients_found = 0;
2196         FOR_EACH_REALCLIENT(self)
2197         {
2198                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2199                 if(redirection_target == "self")
2200                         stuffcmd(self, "\ndisconnect; reconnect\n");
2201                 else
2202                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2203                 ++clients_found;
2204         }
2205
2206         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2207
2208         if(time > redirection_timeout || clients_found == 0)
2209                 localcmd("\nwait; wait; wait; quit\n");
2210
2211         return TRUE;
2212 }