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