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