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