]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
simplified nextmap check (might be a bit more efficient that way ;))
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2
3 string GetMapname();
4 void GotoNextMap();
5 void HandleMaplistShuffleCommands();
6
7 void SetDefaultAlpha()
8 {
9         if(cvar("g_running_guns"))
10         {
11                 default_player_alpha = -1;
12                 default_weapon_alpha = +1;
13         }
14         else if(cvar("g_cloaked"))
15         {
16                 default_player_alpha = cvar("g_balance_cloaked_alpha");
17                 default_weapon_alpha = default_player_alpha;
18         }
19         else
20         {
21                 default_player_alpha = cvar("g_player_alpha");
22                 if(default_player_alpha <= 0)
23                         default_player_alpha = 1;
24                 default_weapon_alpha = default_player_alpha;
25         }
26 }
27
28 void fteqcc_testbugs()
29 {
30         float a, b;
31
32         if(!cvar("developer_fteqccbugs"))
33                 return;
34
35         dprint("*** fteqcc test: checking for bugs...\n");
36
37         a = 1;
38         b = 5;
39         if(sqrt(a) - sqrt(b - a) == 0)
40                 dprint("*** fteqcc test: found same-function-twice bug\n");
41         else
42                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
43
44         world.frags = -10;
45         world.enemy = world;
46         world.enemy.frags += 10;
47         if(world.frags > 0.2 || world.frags < -0.2) // don't error out if it's just roundoff errors
48                 dprint("*** fteqcc test: found += bug\n");
49         else
50                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
51         world.frags = 0;
52 }
53
54 void GotoFirstMap()
55 {
56         if(cvar("_sv_init"))
57         {
58                 cvar_set("_sv_init", "0");
59                 HandleMaplistShuffleCommands();
60                 tokenize(cvar_string("g_maplist"));
61                 if(argv(0) != GetMapname())
62                 {
63                         cvar_set("nextmap", argv(0));
64                         GotoNextMap();
65                 }
66         }
67 }
68
69 float world_already_spawned;
70 void worldspawn (void)
71 {
72         if(world_already_spawned)
73                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
74         world_already_spawned = TRUE;
75         // Precache all player models
76         // Workaround for "invisible players"
77         precache_model("models/player/carni.zym");
78         precache_model("models/player/crash.zym");
79         precache_model("models/player/grunt.zym");
80         precache_model("models/player/headhunter.zym");
81         precache_model("models/player/insurrectionist.zym");
82         precache_model("models/player/jeandarc.zym");
83         precache_model("models/player/lurk.zym");
84         precache_model("models/player/lycanthrope.zym");
85         precache_model("models/player/marine.zym");
86         precache_model("models/player/nexus.zym");
87         precache_model("models/player/pyria.zym");
88         precache_model("models/player/shock.zym");
89         precache_model("models/player/skadi.zym");
90         precache_model("models/player/specop.zym");
91         precache_model("models/player/visitant.zym");
92
93         //precache_model ("progs/beam.mdl");
94         precache_model ("models/bullet.mdl");
95         precache_model ("models/casing_bronze.mdl");
96         precache_model ("models/casing_shell.mdl");
97         precache_model ("models/casing_steel.mdl");
98         precache_model ("models/ebomb.mdl");
99         precache_model ("models/elaser.mdl");
100         precache_model ("models/flash.md3");
101         precache_model ("models/gibs/bloodyskull.md3");
102         precache_model ("models/gibs/chunk.mdl");
103         precache_model ("models/gibs/eye.md3");
104         precache_model ("models/gibs/gib1.md3");
105         //precache_model ("models/gibs/gib2.md3");
106         //precache_model ("models/gibs/gib3.md3");
107         //precache_model ("models/gibs/gib4.md3");
108         precache_model ("models/gibs/gib5.md3");
109         //precache_model ("models/gibs/gib6.md3");
110         precache_model ("models/gibs/gib1.mdl");
111         precache_model ("models/gibs/gib2.mdl");
112         precache_model ("models/gibs/gib3.mdl");
113         precache_model ("models/grenademodel.md3");
114         precache_model ("models/hagarmissile.mdl");
115         precache_model ("models/items/a_bullets.mdl");
116         precache_model ("models/items/a_cells.md3");
117         precache_model ("models/items/a_rockets.md3");
118         precache_model ("models/items/a_shells.md3");
119         precache_model ("models/items/g_a1.md3");
120         precache_model ("models/items/g_a25.md3");
121         precache_model ("models/items/g_h1.md3");
122         precache_model ("models/items/g_h25.md3");
123         precache_model ("models/items/g_h100.md3");
124         precache_model ("models/items/g_invincible.md3");
125         precache_model ("models/items/g_strength.md3");
126         precache_model ("models/laser.mdl");
127         precache_model ("models/misc/chatbubble.spr");
128         precache_model ("models/misc/teambubble.spr");
129         precache_model ("models/nexflash.md3");
130         precache_model ("models/plasma.mdl");
131         precache_model ("models/plasmatrail.mdl");
132         precache_model ("models/rocket.md3");
133         //precache_model ("models/sprites/grenexpl.spr");
134         precache_model ("models/runematch/rune.mdl");
135         precache_model ("models/runematch/curse.mdl");
136         //precache_model ("models/sprites/hagar.spr");
137         //precache_model ("models/sprites/muzzleflash.spr32");
138         //precache_model ("models/sprites/electrocombo.spr32");
139         //precache_model ("models/sprites/plasmahitwall.spr32");
140         //precache_model ("models/sprites/plasmashot.spr32");
141         //precache_model ("models/sprites/rockexpl.spr");
142         precache_model ("models/tracer.mdl");
143         precache_model ("models/uziflash.md3");
144         precache_model ("models/weapons/g_crylink.md3");
145         precache_model ("models/weapons/g_electro.md3");
146         precache_model ("models/weapons/g_gl.md3");
147         precache_model ("models/weapons/g_hagar.md3");
148         precache_model ("models/weapons/g_nex.md3");
149         precache_model ("models/weapons/g_rl.md3");
150         precache_model ("models/weapons/g_shotgun.md3");
151         precache_model ("models/weapons/g_uzi.md3");
152         precache_model ("models/weapons/v_crylink.md3");
153         precache_model ("models/weapons/v_electro.md3");
154         precache_model ("models/weapons/v_gl.md3");
155         precache_model ("models/weapons/v_hagar.md3");
156         precache_model ("models/weapons/v_laser.md3");
157         precache_model ("models/weapons/v_nex.md3");
158         precache_model ("models/weapons/v_rl.md3");
159         precache_model ("models/weapons/v_shotgun.md3");
160         precache_model ("models/weapons/v_uzi.md3");
161         precache_model ("models/weapons/w_crylink.zym");
162         precache_model ("models/weapons/w_electro.zym");
163         precache_model ("models/weapons/w_gl.zym");
164         precache_model ("models/weapons/w_hagar.zym");
165         precache_model ("models/weapons/w_laser.zym");
166         precache_model ("models/weapons/w_nex.zym");
167         precache_model ("models/weapons/w_rl.zym");
168         precache_model ("models/weapons/w_shotgun.zym");
169         precache_model ("models/weapons/w_uzi.zym");
170
171         // laser for laser-guided weapons
172         precache_model ("models/laser_dot.mdl");
173
174         precache_sound ("misc/null.wav");
175         precache_sound ("misc/armor1.wav");
176         precache_sound ("misc/armor25.wav");
177         precache_sound ("misc/armorimpact.wav");
178         precache_sound ("misc/bodyimpact1.wav");
179         precache_sound ("misc/bodyimpact2.wav");
180         precache_sound ("misc/gib.wav");
181         precache_sound ("misc/gib_splat01.wav");
182         precache_sound ("misc/gib_splat02.wav");
183         precache_sound ("misc/gib_splat03.wav");
184         precache_sound ("misc/gib_splat04.wav");
185         //precache_sound ("misc/h2ohit.wav");
186         precache_sound ("misc/hit.wav");
187         precache_sound ("misc/footstep01.wav");
188         precache_sound ("misc/footstep02.wav");
189         precache_sound ("misc/footstep03.wav");
190         precache_sound ("misc/footstep04.wav");
191         precache_sound ("misc/footstep05.wav");
192         precache_sound ("misc/footstep06.wav");
193         precache_sound ("misc/hitground1.ogg");
194         precache_sound ("misc/hitground2.ogg");
195         precache_sound ("misc/hitground3.ogg");
196         precache_sound ("misc/hitground4.ogg");
197         precache_sound ("misc/itempickup.ogg");
198         precache_sound ("misc/itemrespawn.ogg");
199         precache_sound ("misc/jumppad.ogg");
200         precache_sound ("misc/mediumhealth.ogg");
201         precache_sound ("misc/megahealth.ogg");
202         precache_sound ("misc/minihealth.ogg");
203         precache_sound ("misc/powerup.ogg");
204         precache_sound ("misc/powerup_shield.ogg");
205         precache_sound ("misc/talk.wav");
206         precache_sound ("misc/teleport.ogg");
207         precache_sound ("plats/medplat1.wav");
208         precache_sound ("plats/medplat2.wav");
209         precache_sound ("player/lava.wav");
210         precache_sound ("player/slime.wav");
211         precache_sound ("weapons/crylink_fire.ogg");
212         precache_sound ("weapons/electro_bounce.ogg");
213         precache_sound ("weapons/electro_fire.ogg");
214         precache_sound ("weapons/electro_fire2.ogg");
215         precache_sound ("weapons/electro_fly.wav");
216         precache_sound ("weapons/electro_impact.ogg");
217         precache_sound ("weapons/electro_impact_combo.ogg");
218         //precache_sound ("weapons/grenade_bounce.ogg");
219         precache_sound ("weapons/grenade_bounce1.ogg");
220         precache_sound ("weapons/grenade_bounce2.ogg");
221         precache_sound ("weapons/grenade_bounce3.ogg");
222         precache_sound ("weapons/grenade_bounce4.ogg");
223         precache_sound ("weapons/grenade_bounce5.ogg");
224         precache_sound ("weapons/grenade_bounce6.ogg");
225         precache_sound ("weapons/grenade_fire.ogg");
226         precache_sound ("weapons/grenade_impact.ogg");
227         precache_sound ("weapons/hagar_fire.ogg");
228         precache_sound ("weapons/hagexp1.ogg");
229         precache_sound ("weapons/hagexp2.ogg");
230         precache_sound ("weapons/hagexp3.ogg");
231         precache_sound ("weapons/hook_fire.ogg");
232         precache_sound ("weapons/hook_impact.ogg");
233         precache_sound ("weapons/lasergun_fire.ogg");
234         precache_sound ("weapons/laserimpact.ogg");
235         precache_sound ("weapons/nexfire.ogg");
236         precache_sound ("weapons/neximpact.ogg");
237         precache_sound ("weapons/ric1.ogg");
238         precache_sound ("weapons/ric2.ogg");
239         precache_sound ("weapons/ric3.ogg");
240         precache_sound ("weapons/rocket_fire.ogg");
241         precache_sound ("weapons/rocket_fly.wav");
242         precache_sound ("weapons/rocket_impact.ogg");
243         precache_sound ("weapons/rocket_det.ogg");
244         precache_sound ("weapons/shotgun_fire.ogg");
245         precache_sound ("weapons/tink1.ogg");
246         precache_sound ("weapons/uzi_fire.ogg");
247         precache_sound ("weapons/weapon_switch.ogg");
248         precache_sound ("weapons/weaponpickup.ogg");
249         precache_sound ("weapons/strength_fire.ogg");
250
251         //precache_sound ("announce/male/kill10.ogg");
252         //precache_sound ("announce/male/kill15.ogg");
253         //precache_sound ("announce/male/kill20.ogg");
254         //precache_sound ("announce/male/kill25.ogg");
255         //precache_sound ("announce/male/kill3.ogg");
256         //precache_sound ("announce/male/kill30.ogg");
257         //precache_sound ("announce/male/kill4.ogg");
258         //precache_sound ("announce/male/kill5.ogg");
259         //precache_sound ("announce/male/kill6.ogg");
260         //precache_sound ("announce/male/mapkill1.ogg");
261         //precache_sound ("announce/robotic/last_second_save.ogg");
262         //precache_sound ("announce/robotic/narrowly_averted.ogg");
263         //precache_sound ("minstagib/mockery.ogg");
264
265         // announcer sounds - male
266         precache_sound ("announcer/male/03kills.ogg");
267         precache_sound ("announcer/male/05kills.ogg");
268         precache_sound ("announcer/male/10kills.ogg");
269         precache_sound ("announcer/male/15kills.ogg");
270         precache_sound ("announcer/male/20kills.ogg");
271         precache_sound ("announcer/male/25kills.ogg");
272         precache_sound ("announcer/male/30kills.ogg");
273         precache_sound ("announcer/male/botlike.ogg");
274         precache_sound ("announcer/male/electrobitch.ogg");
275         precache_sound ("announcer/male/welcome.ogg");
276         precache_sound ("announcer/male/yoda.ogg");
277
278         // announcer sounds - robotic
279         precache_sound ("announcer/robotic/1fragleft.ogg");
280         precache_sound ("announcer/robotic/1minuteremains.ogg");
281         precache_sound ("announcer/robotic/2fragsleft.ogg");
282         precache_sound ("announcer/robotic/3fragsleft.ogg");
283         precache_sound ("announcer/robotic/lastsecond.ogg");
284         precache_sound ("announcer/robotic/narrowly.ogg");
285         precache_sound ("announcer/robotic/1.ogg");
286         precache_sound ("announcer/robotic/2.ogg");
287         precache_sound ("announcer/robotic/3.ogg");
288         precache_sound ("announcer/robotic/4.ogg");
289         precache_sound ("announcer/robotic/5.ogg");
290         precache_sound ("announcer/robotic/6.ogg");
291         precache_sound ("announcer/robotic/7.ogg");
292         precache_sound ("announcer/robotic/8.ogg");
293         precache_sound ("announcer/robotic/9.ogg");
294         precache_sound ("announcer/robotic/10.ogg");
295
296         // plays music for the level if there is any
297         if (self.noise)
298         {
299                 precache_sound (self.noise);
300                 ambientsound ('0 0 0', self.noise, 1.00, ATTN_NONE);
301         }
302
303         // 0 normal
304         lightstyle(0, "m");
305
306         // 1 FLICKER (first variety)
307         lightstyle(1, "mmnmmommommnonmmonqnmmo");
308
309         // 2 SLOW STRONG PULSE
310         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
311
312         // 3 CANDLE (first variety)
313         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
314
315         // 4 FAST STROBE
316         lightstyle(4, "mamamamamama");
317
318         // 5 GENTLE PULSE 1
319         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
320
321         // 6 FLICKER (second variety)
322         lightstyle(6, "nmonqnmomnmomomno");
323
324         // 7 CANDLE (second variety)
325         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
326
327         // 8 CANDLE (third variety)
328         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
329
330         // 9 SLOW STROBE (fourth variety)
331         lightstyle(9, "aaaaaaaazzzzzzzz");
332
333         // 10 FLUORESCENT FLICKER
334         lightstyle(10, "mmamammmmammamamaaamammma");
335
336         // 11 SLOW PULSE NOT FADE TO BLACK
337         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
338
339         // styles 32-62 are assigned by the light program for switchable lights
340
341         // 63 testing
342         lightstyle(63, "a");
343
344         registercvar("_g_maplist_shufflenow", "0");
345         registercvar("_g_maplist_have_shuffled", "0");
346
347         player_count = 0;
348         lms_lowest_lives = 0;
349         lms_next_place = 0;
350
351         GotoFirstMap();
352
353         bot_waypoints_for_items = cvar("g_waypoints_for_items");
354         if(bot_waypoints_for_items == 1)
355                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
356                         bot_waypoints_for_items = 0;
357
358         if(cvar("g_campaign"))
359                 CampaignPreInit();
360
361         InitGameplayMode();
362         //if (cvar("g_domination"))
363         //      dom_init();
364
365         local entity head;
366         head = nextent(world);
367         maxclients = 0;
368         while(head)
369         {
370                 maxclients++;
371                 head = nextent(head);
372         }
373
374         GameLogInit(); // prepare everything
375         if(cvar("sv_eventlog"))
376         {
377                 local string s;
378                 GameLogEcho(":logversion:2", FALSE);
379                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
380                 s = strcat(s, ftos(random()));
381                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
382                 s = ":gameinfo:mutators:LIST";
383                 if(cvar("g_grappling_hook"))
384                         s = strcat(s, ":grappling_hook");
385                 if(!cvar("g_use_ammunition"))
386                         s = strcat(s, ":no_use_ammunition");
387                 if(!cvar("g_pickup_items"))
388                         s = strcat(s, ":no_pickup_items");
389                 if(cvar("g_instagib"))
390                         s = strcat(s, ":instagib");
391                 if(cvar("g_rocketarena"))
392                         s = strcat(s, ":rockerarena");
393                 if(cvar("g_nixnex"))
394                         s = strcat(s, ":nixnex");
395                 if(cvar("g_vampire"))
396                         s = strcat(s, ":vampire");
397                 if(cvar("g_laserguided_missile"))
398                         s = strcat(s, ":laserguided_missile");
399                 if(cvar("g_norecoil"))
400                         s = strcat(s, ":norecoil");
401                 if(cvar("g_midair"))
402                         s = strcat(s, ":midair");
403                 if(cvar("g_minstagib"))
404                         s = strcat(s, ":minstagib");
405                 GameLogEcho(s, FALSE);
406                 GameLogEcho(":gameinfo:end", FALSE);
407         }
408
409         cvar_set("nextmap", "");
410
411         SetDefaultAlpha();
412
413         if(cvar("g_campaign"))
414                 CampaignPostInit();
415
416         fteqcc_testbugs();
417 }
418
419 void light (void)
420 {
421         //makestatic (self); // Who the f___ did that?
422         remove(self);
423 }
424
425 float( string pFilename ) TryFile =
426 {
427         local float lHandle;
428         dprint("TryFile(\"", pFilename, "\")\n");
429         lHandle = fopen( pFilename, FILE_READ );
430         if( lHandle != -1 ) {
431                 fclose( lHandle );
432                 return TRUE;
433         } else {
434                 return FALSE;
435         }
436 };
437
438 string GetGametype()
439 {
440         if (game == GAME_DEATHMATCH)
441                 return "dm";
442         else if (game == GAME_TEAM_DEATHMATCH)
443                 return "tdm";
444         else if (game == GAME_DOMINATION)
445                 return "dom";
446         else if (game == GAME_CTF)
447                 return "ctf";
448         else if (game == GAME_RUNEMATCH)
449                 return "rune";
450         else if (game == GAME_LMS)
451                 return "lms";
452         return "dm";
453 }
454
455 string GetMapname()
456 {
457         return strcat(GetGametype(), "_", mapname);
458 }
459
460 float Map_Count, Map_Current;
461 string Map_Current_Name;
462
463 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
464 float GetMaplistPosition()
465 {
466         float pos, idx;
467         string map;
468
469         map = GetMapname();
470         idx = cvar("g_maplist_index");
471
472         if(idx >= 0)
473                 if(idx < Map_Count)
474                         if(map == argv(idx))
475                                 return idx;
476
477         for(pos = 0; pos < Map_Count; ++pos)
478                 if(map == argv(pos))
479                         return pos;
480
481         // resume normal maplist rotation if current map is not in g_maplist
482         return idx;
483 }
484
485 float MapHasRightSize(string map)
486 {
487         // open map size restriction file
488         float fh;
489         dprint("opensize "); dprint(map);
490         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
491         if(fh >= 0)
492         {
493                 float mapmin, mapmax;
494                 dprint(": ok, ");
495                 mapmin = stof(fgets(fh));
496                 mapmax = stof(fgets(fh));
497                 fclose(fh);
498                 if(player_count < mapmin)
499                 {
500                         dprint("not enough\n");
501                         return FALSE;
502                 }
503                 if(player_count > mapmax)
504                 {
505                         dprint("too many\n");
506                         return FALSE;
507                 }
508                 dprint("right size\n");
509                 return TRUE;
510         }
511         dprint(": not found\n");
512         return TRUE;
513 }
514
515 string Map_Filename(float position)
516 {
517         return strcat("maps/", argv(position), ".mapcfg");
518 }
519
520 float(float position, float pass) Map_Check =
521 {
522         string filename;
523         string map_next;
524         map_next = argv(position);
525         if(pass <= 1)
526                 if(map_next == Map_Current_Name) // same map again in first pass?
527                         return 0;
528         filename = Map_Filename(position);
529         if(TryFile(filename))
530         {
531                 if(pass == 2)
532                         return 1;
533                 if(MapHasRightSize(argv(position)))
534                         return 1;
535                 return 0;
536         }
537         else
538                 dprint( "Couldn't find '", filename, "'..\n" );
539
540         return 0;
541 }
542
543 void(float position) Map_Goto =
544 {
545         cvar_set("g_maplist_index", ftos(position));
546         localcmd(strcat("exec \"", Map_Filename(position) ,"\"\n"));
547 }
548
549 // return codes of map selectors:
550 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
551 //   -2 = permanent failure
552 float() MaplistMethod_Iterate = // usual method
553 {
554         float pass, i;
555
556         for(pass = 1; pass <= 2; ++pass)
557         {
558                 for(i = 1; i < Map_Count; ++i)
559                 {
560                         float mapindex;
561                         mapindex = math_mod(i + Map_Current, Map_Count);
562                         if(Map_Check(mapindex, pass))
563                                 return mapindex;
564                 }
565         }
566         return -1;
567 }
568
569 float() MaplistMethod_Repeat = // fallback method
570 {
571         if(Map_Check(Map_Current, 2))
572                 return Map_Current;
573         return -2;
574 }
575
576 float() MaplistMethod_Random = // random map selection
577 {
578         float i, imax;
579
580         imax = 42;
581
582         for(i = 0; i <= imax; ++i)
583         {
584                 float mapindex;
585                 mapindex = math_mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
586                 if(Map_Check(mapindex, 1))
587                         return mapindex;
588         }
589         return -1;
590 }
591
592 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
593 // the exponent sets a bias on the map selection:
594 // the higher the exponent, the 
595 {
596         float i, j, imax, insertpos;
597
598         imax = 42;
599
600         if(Map_Count <= 1)
601                 return 0; // only one map, then always play this one
602
603         for(i = 0; i <= imax; ++i)
604         {
605                 string newlist;
606
607                 // now reinsert this at another position
608                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
609                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
610                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
611                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
612
613                 // insert the current map there
614                 newlist = "";
615                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
616                         newlist = strcat(newlist, "'", argv(j), "'");
617                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
618                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
619                         newlist = strcat(newlist, "'", argv(j), "'");
620                 cvar_set("g_maplist", newlist);
621                 Map_Count = tokenize(newlist);
622
623                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
624                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
625                 if(Map_Check(Map_Current, 1))
626                         return Map_Current;
627         }
628         return -1;
629 }
630
631 void() Maplist_Init =
632 {
633         string temp;
634         temp = cvar_string("g_maplist");
635         Map_Count = tokenize(temp);
636         if(Map_Count == 0)
637         {
638                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
639                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
640                 Map_Count = tokenize(temp);
641         }
642         if(Map_Count == 0)
643                 error("empty maplist, cannot select a new map");
644         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
645
646         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
647         // this may or may not be correct, but who cares, in the worst case a map
648         // isn't chosen in the first pass that should have been
649 }
650
651 void() GotoNextMap =
652 {
653         //local string nextmap;
654         //local float n, nummaps;
655         //local string s;
656         string exit_cfg;
657         if (alreadychangedlevel)
658                 return;
659         alreadychangedlevel = TRUE;
660
661         if(cvar("g_campaign"))
662         {
663                 CampaignPostIntermission();
664                 return;
665         }
666
667         if(cvar("quit_when_empty"))
668         {
669                 if(player_count <= currentbots)
670                 {
671                         localcmd("quit\n");
672                         return;
673                 }
674         }
675
676         if (cvar("samelevel")) // if samelevel is set, stay on same level
677         {
678                 // 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)
679                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
680                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
681                 localcmd("restart\n");
682                 //changelevel (mapname);
683                 return;
684         }
685
686         // if an exit cfg is defined by exiting map, exec it.
687         exit_cfg = cvar_string("exit_cfg");
688         if(exit_cfg != "")
689                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
690
691         localcmd("exec game_reset.cfg\n");
692
693
694         if (cvar("lastlevel"))
695         {
696                 localcmd(strcat("set lastlevel 0\n"));
697                 localcmd(strcat("togglemenu\n"));
698         }
699         else
700         {
701                 float nextMap;
702                 float allowReset;
703
704                 // cvar "nextmap" always gets priority
705                 if(cvar("nextmap"))
706                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
707                 {
708                         localcmd(strcat("exec \"maps/", cvar_string("nextmap"), ".mapcfg\"\n"));
709                         return;
710                 }
711
712                 for(allowReset = 1; allowReset >= 0; --allowReset)
713                 {
714                         Maplist_Init();
715                         nextMap = -1;
716
717                         if(nextMap == -1)
718                                 if(cvar("g_maplist_shuffle") > 0)
719                                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
720
721                         if(nextMap == -1)
722                                 if(cvar("g_maplist_selectrandom"))
723                                         nextMap = MaplistMethod_Random();
724
725                         if(nextMap == -1)
726                                 nextMap = MaplistMethod_Iterate();
727
728                         if(nextMap == -1)
729                                 nextMap = MaplistMethod_Repeat();
730
731                         if(nextMap >= 0)
732                         {
733                                 Map_Goto(nextMap);
734                                 break;
735                         }
736                         else // PERMANENT FAILURE
737                         {
738                                 if(allowReset)
739                                 {
740                                         bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
741                                         cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
742                                 }
743                                 else
744                                 {
745                                         error("Everything is broken - not even the default map list works. Please report this to the developers.");
746                                 }
747                         }
748                 }
749         }
750 };
751
752
753 /*
754 ============
755 IntermissionThink
756
757 When the player presses attack or jump, change to the next level
758 ============
759 */
760 .float autoscreenshot;
761 void() IntermissionThink =
762 {
763         if(cvar("sv_autoscreenshot"))
764         if(self.autoscreenshot)
765         if(time > self.autoscreenshot)
766         {
767                 self.autoscreenshot = FALSE;
768                 if(clienttype(self) == CLIENTTYPE_REAL)
769                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
770                 return;
771         }
772
773         if (time < intermission_exittime)
774                 return;
775
776         if (time < intermission_exittime + 10 && !self.button0 && !self.button2 && !self.button3 && !self.button6 && !self.buttonuse)
777                 return;
778
779         GotoNextMap ();
780 };
781
782 /*
783 ============
784 FindIntermission
785
786 Returns the entity to view from
787 ============
788 */
789 /*
790 entity() FindIntermission =
791 {
792         local   entity spot;
793         local   float cyc;
794
795 // look for info_intermission first
796         spot = find (world, classname, "info_intermission");
797         if (spot)
798         {       // pick a random one
799                 cyc = random() * 4;
800                 while (cyc > 1)
801                 {
802                         spot = find (spot, classname, "info_intermission");
803                         if (!spot)
804                                 spot = find (spot, classname, "info_intermission");
805                         cyc = cyc - 1;
806                 }
807                 return spot;
808         }
809
810 // then look for the start position
811         spot = find (world, classname, "info_player_start");
812         if (spot)
813                 return spot;
814
815 // testinfo_player_start is only found in regioned levels
816         spot = find (world, classname, "testplayerstart");
817         if (spot)
818                 return spot;
819
820 // then look for the start position
821         spot = find (world, classname, "info_player_deathmatch");
822         if (spot)
823                 return spot;
824
825         //objerror ("FindIntermission: no spot");
826         return world;
827 };
828 */
829
830 /*
831 ===============================================================================
832
833 RULES
834
835 ===============================================================================
836 */
837
838 void() DumpStats =
839 {
840         local float file;
841         local string s;
842
843         if(cvar("_printstats"))
844                 cvar_set("_printstats", "0");
845         else if(!gameover)
846                 return;
847
848         if(gameover)
849                 s = ":scores:";
850         else
851                 s = ":status:";
852
853         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
854
855         if(cvar("sv_eventlog") && gameover)
856                 GameLogEcho(s, FALSE);
857         else if(cvar("sv_logscores_console"))
858                 ServerConsoleEcho(s, FALSE);
859         if(cvar("sv_logscores_file"))
860         {
861                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
862                 fputs(file, strcat(s, "\n"));
863         }
864
865         other = findchainflags(flags, FL_CLIENT);
866         while (other)
867         {
868                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
869                 {
870                         s = strcat(":player:", ftos(other.frags), ":");
871                         s = strcat(s, ftos(other.deaths), ":");
872                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
873                         s = strcat(s, ftos(other.team), ":");
874
875                         if(cvar("sv_logscores_file"))
876                                 fputs(file, strcat(s, other.netname, "\n"));
877                         if(cvar("sv_eventlog") && gameover)
878                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
879                         else if(cvar("sv_logscores_console"))
880                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
881                 }
882                 other = other.chain;
883         }
884
885         if(cvar("sv_eventlog") && gameover)
886                 GameLogEcho(":end", FALSE);
887         else if(cvar("sv_logscores_console"))
888                 ServerConsoleEcho(":end", FALSE);
889         if(cvar("sv_logscores_file"))
890         {
891                 fputs(file, ":end\n");
892                 fclose(file);
893         }
894 }
895
896
897 /*
898 go to the next level for deathmatch
899 only called if a time or frag limit has expired
900 */
901 void() NextLevel =
902 {
903         gameover = TRUE;
904
905         intermission_running = 1;
906
907 // enforce a wait time before allowing changelevel
908         if(player_count > 0)
909                 intermission_exittime = time + cvar("sv_mapchange_delay");
910         else
911                 intermission_exittime = -60;
912
913         WriteByte (MSG_ALL, SVC_CDTRACK);
914         WriteByte (MSG_ALL, 3);
915         WriteByte (MSG_ALL, 3);
916
917         //pos = FindIntermission ();
918
919         VoteReset();
920
921         DumpStats();
922
923         if(cvar("sv_eventlog"))
924                 GameLogEcho(":gameover", FALSE);
925
926         GameLogClose();
927
928         other = findchainflags(flags, FL_CLIENT);
929         while (other != world)
930         {
931                 //other.nextthink = time + 0.5;
932                 other.takedamage = DAMAGE_NO;
933                 other.solid = SOLID_NOT;
934                 other.movetype = MOVETYPE_NONE;
935                 other.angles = other.v_angle;
936                 other.angles_x = other.angles_x * -1;
937                 other.autoscreenshot = time + 0.8;      // used for autoscreenshot
938
939                 self = other;
940
941                 if(other.winning)
942                         bprint(strcat(other.netname, " ^7wins.\n"));
943
944                 /*
945                 if (pos != world);
946                 {
947                         other.modelindex = 0;
948                         other.weaponentity = world; // remove weapon model
949                         other.view_ofs = '0 0 0';
950                         other.angles = other.v_angle = pos.mangle;
951                         if (!other.angles)
952                         {
953                                 other.angles = other.v_angle = pos.angles;
954                                 other.v_angle_x = other.v_angle_x * -1;
955                         }
956                         other.fixangle = TRUE;          // turn this way immediately
957                         setorigin (other, pos.origin);
958                 }
959                 */
960                 other = other.chain;
961         }
962
963         if(cvar("g_campaign"))
964                 CampaignPreIntermission();
965
966         WriteByte (MSG_ALL, SVC_INTERMISSION);
967 };
968
969 /*
970 ============
971 CheckRules_Player
972
973 Exit deathmatch games upon conditions
974 ============
975 */
976 void() CheckRules_Player =
977 {
978         if (gameover)   // someone else quit the game already
979                 return;
980
981         // fixme: don't check players; instead check dom_team and ctf_team entities
982         //   (div0: and that in CheckRules_World please)
983 };
984
985 float checkrules_oneminutewarning;
986 float checkrules_leaderfrags;
987 float tdm_max_score, tdm_old_score;
988
989 float checkrules_equality;
990 float checkrules_overtimewarning;
991 float checkrules_overtimeend;
992
993 void() InitiateOvertime =
994 {
995         if(!checkrules_overtimeend)
996                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
997 }
998
999 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1000 float WINNING_YES = 1; // winner found
1001 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1002 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1003
1004 float(float fraglimitreached, float equality) GetWinningCode =
1005 {
1006         if(equality)
1007                 if(fraglimitreached)
1008                         return WINNING_STARTOVERTIME;
1009                 else
1010                         return WINNING_NEVER;
1011         else
1012                 if(fraglimitreached)
1013                         return WINNING_YES;
1014                 else
1015                         return WINNING_NO;
1016 }
1017
1018 // set the .winning flag for exactly those players with a given field value
1019 void(.float field, float value) SetWinners =
1020 {
1021         entity head;
1022         head = findchain(classname, "player");
1023         while (head)
1024         {
1025                 head.winning = (head.field == value);
1026                 head = head.chain;
1027         }
1028 }
1029
1030 // set the .winning flag for those players with a given field value
1031 void(.float field, float value) AddWinners =
1032 {
1033         entity head;
1034         head = findchain(classname, "player");
1035         while (head)
1036         {
1037                 if(head.field == value)
1038                         head.winning = 1;
1039                 head = head.chain;
1040         }
1041 }
1042
1043 // clear the .winning flags
1044 void(void) ClearWinners =
1045 {
1046         entity head;
1047         head = findchain(classname, "player");
1048         while (head)
1049         {
1050                 head.winning = 0;
1051                 head = head.chain;
1052         }
1053 }
1054
1055 float() LMS_NewPlayerLives =
1056 {
1057         float fl;
1058         fl = cvar("fraglimit");
1059         if(fl == 0)
1060                 fl = 999;
1061
1062         // first player has left the game for dying too much? Nobody else can get in.
1063         if(lms_lowest_lives < 1)
1064                 return FALSE;
1065
1066         if(!cvar("g_lms_join_anytime"))
1067                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1068                         return FALSE;
1069
1070         return bound(1, lms_lowest_lives, fl);
1071 }
1072
1073 // LMS winning condition: game terminates if and only if there's at most one
1074 // one player who's living lives. Top two scores being equal cancels the time
1075 // limit.
1076 float() WinningCondition_LMS =
1077 {
1078         entity head;
1079         float have_player;
1080         float have_players;
1081         float l;
1082
1083         have_player = FALSE;
1084         have_players = FALSE;
1085         l = LMS_NewPlayerLives();
1086
1087         head = find(world, classname, "player");
1088         if(head)
1089                 have_player = TRUE;
1090         head = find(head, classname, "player");
1091         if(head)
1092                 have_players = TRUE;
1093
1094         if(have_player)
1095         {
1096                 // we have at least one player
1097                 if(have_players)
1098                 {
1099                         // two or more active players - continue with the game
1100                 }
1101                 else
1102                 {
1103                         // exactly one player?
1104                         if(l)
1105                         {
1106                                 // but no game has taken place yet
1107                         }
1108                         else
1109                         {
1110                                 // a winner!
1111                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1112                                 dprint("Have a winner, ending game.\n");
1113                                 return WINNING_YES;
1114                         }
1115                 }
1116         }
1117         else
1118         {
1119                 // nobody is playing at all...
1120                 if(l)
1121                 {
1122                         // wait for players...
1123                 }
1124                 else
1125                 {
1126                         // SNAFU (maybe a draw game?)
1127                         ClearWinners();
1128                         dprint("No players, ending game.\n");
1129                         return WINNING_YES;
1130                 }
1131         }
1132
1133         // When we get here, we have at least two players who are actually LIVING,
1134         // or one player who is still waiting for a victim to join the server. Now
1135         // check if the top two players have equal score.
1136
1137         checkrules_leaderfrags = 0;
1138         head = findchain(classname, "player");
1139         checkrules_equality = FALSE;
1140         while (head)
1141         {
1142                 if(head.frags > checkrules_leaderfrags)
1143                 {
1144                         checkrules_leaderfrags = head.frags;
1145                         checkrules_equality = FALSE;
1146                 }
1147                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1148                         checkrules_equality = TRUE;
1149                 head = head.chain;
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         head = findchain(classname, "player");
1175         checkrules_equality = FALSE;
1176         while (head)
1177         {
1178                 if(head.frags > checkrules_leaderfrags)
1179                 {
1180                         checkrules_leaderfrags = head.frags;
1181                         checkrules_equality = FALSE;
1182                 }
1183                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1184                         checkrules_equality = TRUE;
1185                 head = head.chain;
1186         }
1187
1188         if(checkrules_leaderfrags > 0)
1189                 SetWinners(frags, checkrules_leaderfrags);
1190         else
1191                 ClearWinners();
1192
1193         if (!cvar("g_runematch"))
1194                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1195                 {
1196                         if (checkrules_leaderfrags == fraglimit - 1)
1197                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1198                         else if (checkrules_leaderfrags == fraglimit - 2)
1199                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1200                         else if (checkrules_leaderfrags == fraglimit - 3)
1201                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1202                 }
1203
1204         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1205 }
1206
1207 float(float fraglimit) WinningConditionBase_Teamplay =
1208 {
1209         tdm_old_score = tdm_max_score;
1210         tdm_max_score = max(team1_score, team2_score, team3_score, team4_score);
1211
1212         checkrules_equality =
1213         (
1214                 (tdm_max_score > 0)
1215                 &&
1216                 (
1217                           (team1_score == tdm_max_score)
1218                         + (team2_score == tdm_max_score)
1219                         + (team3_score == tdm_max_score)
1220                         + (team4_score == tdm_max_score)
1221                         >= 2));
1222
1223         ClearWinners();
1224         if(tdm_max_score > 0)
1225         {
1226                 if(team1_score == tdm_max_score)
1227                         AddWinners(team, COLOR_TEAM1);
1228                 if(team2_score == tdm_max_score)
1229                         AddWinners(team, COLOR_TEAM2);
1230                 if(team3_score == tdm_max_score)
1231                         AddWinners(team, COLOR_TEAM3);
1232                 if(team4_score == tdm_max_score)
1233                         AddWinners(team, COLOR_TEAM4);
1234         }
1235
1236         if(!cvar("g_runematch") && !cvar("g_domination"))
1237                 if(tdm_max_score != tdm_old_score)
1238                 {
1239                         if(tdm_max_score == fraglimit - 1)
1240                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1241                         else if(tdm_max_score == fraglimit - 2)
1242                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1243                         else if(tdm_max_score == fraglimit - 3)
1244                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1245                 }
1246
1247         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1248 }
1249
1250 // TDM winning condition: game terminates if a team's score sum reached the
1251 // fraglimit, unless the first two teams have the same total score. The latter
1252 // case also breaks the time limit.
1253 float(float fraglimit) WinningCondition_MaxTeamSum =
1254 {
1255         entity head;
1256
1257         team1_score = team2_score = team3_score = team4_score = 0;
1258
1259         head = findchain(classname, "player");
1260         while (head)
1261         {
1262                 if(head.team == COLOR_TEAM1)
1263                         team1_score += head.frags;
1264                 else if(head.team == COLOR_TEAM2)
1265                         team2_score += head.frags;
1266                 else if(head.team == COLOR_TEAM3)
1267                         team3_score += head.frags;
1268                 else if(head.team == COLOR_TEAM4)
1269                         team4_score += head.frags;
1270                 head = head.chain;
1271         }
1272
1273         return WinningConditionBase_Teamplay(fraglimit);
1274 }
1275
1276 // DOM/CTF winning condition: game terminates if the max of a team's players'
1277 // score reached the fraglimit, unless the first two teams have the same
1278 // maximum score. The latter case also breaks the time limit.
1279 float(float fraglimit) WinningCondition_MaxTeamMax =
1280 {
1281         entity head;
1282
1283         team1_score = team2_score = team3_score = team4_score = 0;
1284
1285         head = findchain(classname, "player");
1286         while (head)
1287         {
1288                 if(head.team == COLOR_TEAM1)
1289                 {
1290                         if(head.frags > team1_score)
1291                                 team1_score = head.frags;
1292                 }
1293                 else if(head.team == COLOR_TEAM2)
1294                 {
1295                         if(head.frags > team2_score)
1296                                 team2_score = head.frags;
1297                 }
1298                 else if(head.team == COLOR_TEAM3)
1299                 {
1300                         if(head.frags > team3_score)
1301                                 team3_score = head.frags;
1302                 }
1303                 else if(head.team == COLOR_TEAM4)
1304                 {
1305                         if(head.frags > team4_score)
1306                                 team4_score = head.frags;
1307                 }
1308                 head = head.chain;
1309         }
1310
1311         return WinningConditionBase_Teamplay(fraglimit);
1312 }
1313
1314 void PrintScoreboardFor(string name, string colorcode, float whichteam)
1315 {
1316         entity head;
1317         float fragtotal;
1318         string s;
1319         float found;
1320         found = FALSE;
1321         head = find(world, classname, "player");
1322         while(head)
1323         {
1324                 if(!whichteam || head.team == whichteam)
1325                 {
1326                         if(name != "")
1327                                 if(!found)
1328                                         ServerConsoleEcho(strcat(" ", colorcode, name, ":"), FALSE);
1329                         found = TRUE;
1330                         fragtotal = fragtotal + head.frags;
1331                         s = ftos(head.frags);
1332                         s = strcat(s, "/", ftos(head.deaths));
1333                         s = strcat(s, " @ ", ftos(head.ping));
1334                         if(clienttype(head) == CLIENTTYPE_BOT)
1335                                 s = strcat(s, "botms");
1336                         else
1337                                 s = strcat(s, "ms");
1338                         ServerConsoleEcho(strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"), TRUE);
1339                 }
1340                 head = find(head, classname, "player");
1341         }
1342         if(whichteam && found)
1343                 ServerConsoleEcho(strcat(colorcode, "  (total: ", ftos(fragtotal), ")"), FALSE);
1344 }
1345
1346 void PrintScoreboard()
1347 {
1348         ServerConsoleEcho("Scoreboard:", FALSE);
1349         if(teams_matter)
1350         {
1351                 PrintScoreboardFor("Red", "^1", COLOR_TEAM1);
1352                 PrintScoreboardFor("Blue", "^4", COLOR_TEAM2);
1353                 PrintScoreboardFor("Pink", "^6", COLOR_TEAM3);
1354                 PrintScoreboardFor("Yellow", "^3", COLOR_TEAM4);
1355         }
1356         else
1357         {
1358                 PrintScoreboardFor("", "^7", 0);
1359         }
1360         ServerConsoleEcho(".", FALSE);
1361 }
1362
1363 void RemoveFromMaplist(string m)
1364 {
1365         string result;
1366         float litems;
1367         float i;
1368         float found;
1369
1370         litems = tokenize(cvar_string("g_maplist"));
1371         found = 0;
1372         result = "";
1373         for(i = 0; i < litems; ++i)
1374         {
1375                 m = strcat(m);
1376                 result = strcat(result);
1377                 if(argv(i) == m)
1378                         found += 1;
1379                 else
1380                         result = strcat(result, "'", argv(i), "'");
1381         }
1382         if(found)
1383                 cvar_set("g_maplist", result);
1384         ServerConsoleEcho(strcat("Removed ", ftos(found), " items."), FALSE);
1385 }
1386
1387 void AddToMaplist(string m)
1388 {
1389         string result;
1390         float found;
1391         float litems;
1392         float i;
1393         float ipos;
1394         float inserted;
1395
1396         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1397         {
1398                 ServerConsoleEcho("Map not found.", FALSE);
1399                 return;
1400         }
1401
1402         litems = tokenize(cvar_string("g_maplist"));
1403         if(cvar("g_maplist_shuffle"))
1404                 ipos = ceil(random() * (litems + 1)) - 1;
1405         else
1406                 ipos = litems;
1407         found = 0;
1408         inserted = 0;
1409         for(i = 0; i < litems; ++i)
1410         {
1411                 m = strcat(m);
1412                 if(i == ipos)
1413                 {
1414                         result = strcat(result, "'", m, "'");
1415                         inserted = 1;
1416                 }
1417                 result = strcat(result, "'", argv(i), "'");
1418                 if(argv(i) == m)
1419                         found += 1;
1420         }
1421         if(!inserted)
1422                 result = strcat(result, "'", m, "'");
1423         if(!found)
1424         {
1425                 cvar_set("g_maplist", result);
1426                 ServerConsoleEcho("Map added.", FALSE);
1427         }
1428         else
1429                 ServerConsoleEcho("Map already in list.", FALSE);
1430 }
1431
1432 void ShuffleMaplist()
1433 {
1434         string result;
1435         float start;
1436         float litems;
1437         float selected;
1438         float i;
1439
1440         result = cvar_string("g_maplist");
1441         litems = tokenize(result);
1442
1443         for(start = 0; start < litems - 1; ++start)
1444         {
1445                 result = "";
1446
1447                 // select a random item
1448                 selected = ceil(random() * (litems - start) + start) - 1;
1449
1450                 // shift this item to the place start
1451                 for(i = 0; i < start; ++i)
1452                         result = strcat(result, "'", argv(i), "'");
1453                 result = strcat(result, "'", argv(selected), "'");
1454                 for(i = start; i < litems; ++i)
1455                         if(i != selected)
1456                                 result = strcat(result, "'", argv(i), "'");
1457
1458                 litems = tokenize(result);
1459
1460                 //dprint(result, "\n");
1461         }
1462
1463         cvar_set("g_maplist", result);
1464 }
1465
1466 void() HandleMaplistShuffleCommands =
1467 {
1468         // automatically shuffle when setting g_maplist_shuffle
1469         if(cvar_string("_g_maplist_add") != "")
1470         {
1471                 AddToMaplist(cvar_string("_g_maplist_add"));
1472                 cvar_set("_g_maplist_add", "");
1473         }
1474         if(cvar_string("_g_maplist_remove") != "")
1475         {
1476                 RemoveFromMaplist(cvar_string("_g_maplist_remove"));
1477                 cvar_set("_g_maplist_remove", "");
1478         }
1479         if(cvar("_g_maplist_shufflenow") || (cvar("g_maplist_shuffle") && !cvar("_g_maplist_have_shuffled")))
1480         {
1481                 ShuffleMaplist();
1482                 cvar_set("_g_maplist_shufflenow", "0");
1483                 cvar_set("_g_maplist_have_shuffled", "1");
1484                 ServerConsoleEcho("Shuffled map list.", FALSE);
1485         }
1486         if(cvar("_g_maplist_have_shuffled"))
1487                 if(!cvar("g_maplist_shuffle"))
1488                         cvar_set("_g_maplist_have_shuffled", "0");
1489 }
1490
1491 /*
1492 ============
1493 CheckRules_World
1494
1495 Exit deathmatch games upon conditions
1496 ============
1497 */
1498 void() CheckRules_World =
1499 {
1500         local float status;
1501         local float timelimit;
1502         local float fraglimit;
1503
1504         VoteThink();
1505
1506         SetDefaultAlpha();
1507
1508         if (intermission_running)
1509                 if (time >= intermission_exittime + 60)
1510                 {
1511                         GotoNextMap();
1512                         return;
1513                 }
1514
1515         if (gameover)   // someone else quit the game already
1516                 return;
1517
1518         DumpStats();
1519
1520         if(cvar("_scoreboard"))
1521         {
1522                 cvar_set("_scoreboard", "0");
1523                 PrintScoreboard();
1524         }
1525
1526         HandleMaplistShuffleCommands();
1527
1528         timelimit = cvar("timelimit") * 60;
1529         fraglimit = cvar("fraglimit");
1530
1531         if (timelimit && time >= timelimit)
1532                 InitiateOvertime();
1533
1534         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1535         {
1536                 NextLevel();
1537                 return;
1538         }
1539
1540         if(!checkrules_overtimewarning && checkrules_overtimeend)
1541         {
1542                 checkrules_overtimewarning = TRUE;
1543                 //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1544                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1545         }
1546
1547         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1548         {
1549                 checkrules_oneminutewarning = TRUE;
1550                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1551         }
1552
1553         status = WINNING_NO;
1554         if(cvar("g_lms"))
1555         {
1556                 status = WinningCondition_LMS();
1557         }
1558         else
1559         {
1560                 if(teams_matter)
1561                 {
1562                         if(cvar("g_tdm") || cvar("g_runematch") || cvar("g_ctf") || cvar("g_domination"))
1563                                 status = WinningCondition_MaxTeamSum(fraglimit);
1564                         //else if()
1565                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1566                         else
1567                         {
1568                                 dprint("div0: How can this happen?\n");
1569                                 status = WinningCondition_MaxTeamMax(fraglimit);
1570                         }
1571                 }
1572                 else
1573                         status = WinningCondition_MaxIndividualScore(fraglimit);
1574         }
1575
1576         if(status == WINNING_STARTOVERTIME)
1577         {
1578                 status = WINNING_NEVER;
1579                 InitiateOvertime();
1580         }
1581
1582         if(status == WINNING_NEVER)
1583                 // equality cases! Nobody wins if the overtime ends in a draw.
1584                 ClearWinners();
1585
1586         if(checkrules_overtimeend)
1587                 if(status != WINNING_NEVER)
1588                         status = WINNING_YES;
1589
1590         if(status == WINNING_YES)
1591                 NextLevel();
1592 };