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