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