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