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