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