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