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