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