]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
preparations for better team auto balancing;
[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_string("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         float minTotalFrags;
904         float maxTotalFrags;
905         float score;
906         float f;
907
908         gameover = TRUE;
909
910         intermission_running = 1;
911
912 // enforce a wait time before allowing changelevel
913         if(player_count > 0)
914                 intermission_exittime = time + cvar("sv_mapchange_delay");
915         else
916                 intermission_exittime = -60;
917
918         WriteByte (MSG_ALL, SVC_CDTRACK);
919         WriteByte (MSG_ALL, 3);
920         WriteByte (MSG_ALL, 3);
921
922         //pos = FindIntermission ();
923
924         VoteReset();
925
926         DumpStats();
927
928         if(cvar("sv_eventlog"))
929                 GameLogEcho(":gameover", FALSE);
930
931         GameLogClose();
932
933         maxTotalFrags = 0;
934         for(other = world; (other = findflags(other, flags, FL_CLIENT)); )
935         {
936                 if(maxTotalFrags < other.totalfrags)
937                         maxTotalFrags = other.totalfrags;
938                 if(minTotalFrags > other.totalfrags)
939                         minTotalFrags = other.totalfrags;
940         }
941
942         for(other = world; (other = findflags(other, flags, FL_CLIENT)); )
943         {
944                 //other.nextthink = time + 0.5;
945                 other.takedamage = DAMAGE_NO;
946                 other.solid = SOLID_NOT;
947                 other.movetype = MOVETYPE_NONE;
948                 other.angles = other.v_angle;
949                 other.angles_x = other.angles_x * -1;
950                 other.autoscreenshot = time + 0.8;      // used for autoscreenshot
951
952                 self = other;
953
954                 if(other.winning)
955                         bprint(strcat(other.netname, " ^7wins.\n"));
956
957                 if(!currentbots)
958                 {
959                         score = (other.frags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
960                         f = bound(0, other.play_time / max(time, 1), 1);
961                         // store some statistics?
962                 }
963         }
964
965         if(cvar("g_campaign"))
966                 CampaignPreIntermission();
967
968         WriteByte (MSG_ALL, SVC_INTERMISSION);
969 };
970
971 /*
972 ============
973 CheckRules_Player
974
975 Exit deathmatch games upon conditions
976 ============
977 */
978 void() CheckRules_Player =
979 {
980         if (gameover)   // someone else quit the game already
981                 return;
982
983         if(self.deadflag == DEAD_NO)
984                 self.play_time += frametime;
985
986         // fixme: don't check players; instead check dom_team and ctf_team entities
987         //   (div0: and that in CheckRules_World please)
988 };
989
990 float checkrules_oneminutewarning;
991 float checkrules_leaderfrags;
992 float tdm_max_score, tdm_old_score;
993
994 float checkrules_equality;
995 float checkrules_overtimewarning;
996 float checkrules_overtimeend;
997
998 void() InitiateOvertime =
999 {
1000         if(!checkrules_overtimeend)
1001                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1002 }
1003
1004 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1005 float WINNING_YES = 1; // winner found
1006 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1007 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1008
1009 float(float fraglimitreached, float equality) GetWinningCode =
1010 {
1011         if(equality)
1012                 if(fraglimitreached)
1013                         return WINNING_STARTOVERTIME;
1014                 else
1015                         return WINNING_NEVER;
1016         else
1017                 if(fraglimitreached)
1018                         return WINNING_YES;
1019                 else
1020                         return WINNING_NO;
1021 }
1022
1023 // set the .winning flag for exactly those players with a given field value
1024 void(.float field, float value) SetWinners =
1025 {
1026         entity head;
1027         head = findchain(classname, "player");
1028         while (head)
1029         {
1030                 head.winning = (head.field == value);
1031                 head = head.chain;
1032         }
1033 }
1034
1035 // set the .winning flag for those players with a given field value
1036 void(.float field, float value) AddWinners =
1037 {
1038         entity head;
1039         head = findchain(classname, "player");
1040         while (head)
1041         {
1042                 if(head.field == value)
1043                         head.winning = 1;
1044                 head = head.chain;
1045         }
1046 }
1047
1048 // clear the .winning flags
1049 void(void) ClearWinners =
1050 {
1051         entity head;
1052         head = findchain(classname, "player");
1053         while (head)
1054         {
1055                 head.winning = 0;
1056                 head = head.chain;
1057         }
1058 }
1059
1060 float() LMS_NewPlayerLives =
1061 {
1062         float fl;
1063         fl = cvar("fraglimit");
1064         if(fl == 0)
1065                 fl = 999;
1066
1067         // first player has left the game for dying too much? Nobody else can get in.
1068         if(lms_lowest_lives < 1)
1069                 return FALSE;
1070
1071         if(!cvar("g_lms_join_anytime"))
1072                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1073                         return FALSE;
1074
1075         return bound(1, lms_lowest_lives, fl);
1076 }
1077
1078 // LMS winning condition: game terminates if and only if there's at most one
1079 // one player who's living lives. Top two scores being equal cancels the time
1080 // limit.
1081 float() WinningCondition_LMS =
1082 {
1083         entity head;
1084         float have_player;
1085         float have_players;
1086         float l;
1087
1088         have_player = FALSE;
1089         have_players = FALSE;
1090         l = LMS_NewPlayerLives();
1091
1092         head = find(world, classname, "player");
1093         if(head)
1094                 have_player = TRUE;
1095         head = find(head, classname, "player");
1096         if(head)
1097                 have_players = TRUE;
1098
1099         if(have_player)
1100         {
1101                 // we have at least one player
1102                 if(have_players)
1103                 {
1104                         // two or more active players - continue with the game
1105                 }
1106                 else
1107                 {
1108                         // exactly one player?
1109                         if(l)
1110                         {
1111                                 // but no game has taken place yet
1112                         }
1113                         else
1114                         {
1115                                 // a winner!
1116                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1117                                 dprint("Have a winner, ending game.\n");
1118                                 return WINNING_YES;
1119                         }
1120                 }
1121         }
1122         else
1123         {
1124                 // nobody is playing at all...
1125                 if(l)
1126                 {
1127                         // wait for players...
1128                 }
1129                 else
1130                 {
1131                         // SNAFU (maybe a draw game?)
1132                         ClearWinners();
1133                         dprint("No players, ending game.\n");
1134                         return WINNING_YES;
1135                 }
1136         }
1137
1138         // When we get here, we have at least two players who are actually LIVING,
1139         // or one player who is still waiting for a victim to join the server. Now
1140         // check if the top two players have equal score.
1141
1142         checkrules_leaderfrags = 0;
1143         head = findchain(classname, "player");
1144         checkrules_equality = FALSE;
1145         while (head)
1146         {
1147                 if(head.frags > checkrules_leaderfrags)
1148                 {
1149                         checkrules_leaderfrags = head.frags;
1150                         checkrules_equality = FALSE;
1151                 }
1152                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1153                         checkrules_equality = TRUE;
1154                 head = head.chain;
1155         }
1156
1157         SetWinners(frags, checkrules_leaderfrags);
1158
1159         // The top two players have the same amount of lives? No timelimit then,
1160         // enter overtime...
1161
1162         if(checkrules_equality)
1163                 return WINNING_NEVER;
1164
1165         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1166         return WINNING_NO;
1167 }
1168
1169 // DM winning condition: game terminates if a player reached the fraglimit,
1170 // unless the first two players have the same score. The latter case also
1171 // breaks the time limit.
1172 float(float fraglimit) WinningCondition_MaxIndividualScore =
1173 {
1174         float checkrules_oldleaderfrags;
1175         entity head;
1176
1177         checkrules_oldleaderfrags = checkrules_leaderfrags;
1178         checkrules_leaderfrags = 0;
1179         head = findchain(classname, "player");
1180         checkrules_equality = FALSE;
1181         while (head)
1182         {
1183                 if(head.frags > checkrules_leaderfrags)
1184                 {
1185                         checkrules_leaderfrags = head.frags;
1186                         checkrules_equality = FALSE;
1187                 }
1188                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1189                         checkrules_equality = TRUE;
1190                 head = head.chain;
1191         }
1192
1193         if(checkrules_leaderfrags > 0)
1194                 SetWinners(frags, checkrules_leaderfrags);
1195         else
1196                 ClearWinners();
1197
1198         if (!cvar("g_runematch"))
1199                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1200                 {
1201                         if (checkrules_leaderfrags == fraglimit - 1)
1202                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1203                         else if (checkrules_leaderfrags == fraglimit - 2)
1204                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1205                         else if (checkrules_leaderfrags == fraglimit - 3)
1206                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1207                 }
1208
1209         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1210 }
1211
1212 float(float fraglimit) WinningConditionBase_Teamplay =
1213 {
1214         tdm_old_score = tdm_max_score;
1215         tdm_max_score = max(team1_score, team2_score, team3_score, team4_score);
1216
1217         checkrules_equality =
1218         (
1219                 (tdm_max_score > 0)
1220                 &&
1221                 (
1222                           (team1_score == tdm_max_score)
1223                         + (team2_score == tdm_max_score)
1224                         + (team3_score == tdm_max_score)
1225                         + (team4_score == tdm_max_score)
1226                         >= 2));
1227
1228         ClearWinners();
1229         if(tdm_max_score > 0)
1230         {
1231                 if(team1_score == tdm_max_score)
1232                         AddWinners(team, COLOR_TEAM1);
1233                 if(team2_score == tdm_max_score)
1234                         AddWinners(team, COLOR_TEAM2);
1235                 if(team3_score == tdm_max_score)
1236                         AddWinners(team, COLOR_TEAM3);
1237                 if(team4_score == tdm_max_score)
1238                         AddWinners(team, COLOR_TEAM4);
1239         }
1240
1241         if(!cvar("g_runematch") && !cvar("g_domination"))
1242                 if(tdm_max_score != tdm_old_score)
1243                 {
1244                         if(tdm_max_score == fraglimit - 1)
1245                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1246                         else if(tdm_max_score == fraglimit - 2)
1247                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1248                         else if(tdm_max_score == fraglimit - 3)
1249                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1250                 }
1251
1252         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1253 }
1254
1255 // TDM winning condition: game terminates if a team's score sum reached the
1256 // fraglimit, unless the first two teams have the same total score. The latter
1257 // case also breaks the time limit.
1258 float(float fraglimit) WinningCondition_MaxTeamSum =
1259 {
1260         entity head;
1261
1262         team1_score = team2_score = team3_score = team4_score = 0;
1263
1264         head = findchain(classname, "player");
1265         while (head)
1266         {
1267                 if(head.team == COLOR_TEAM1)
1268                         team1_score += head.frags;
1269                 else if(head.team == COLOR_TEAM2)
1270                         team2_score += head.frags;
1271                 else if(head.team == COLOR_TEAM3)
1272                         team3_score += head.frags;
1273                 else if(head.team == COLOR_TEAM4)
1274                         team4_score += head.frags;
1275                 head = head.chain;
1276         }
1277
1278         return WinningConditionBase_Teamplay(fraglimit);
1279 }
1280
1281 // DOM/CTF winning condition: game terminates if the max of a team's players'
1282 // score reached the fraglimit, unless the first two teams have the same
1283 // maximum score. The latter case also breaks the time limit.
1284 float(float fraglimit) WinningCondition_MaxTeamMax =
1285 {
1286         entity head;
1287
1288         team1_score = team2_score = team3_score = team4_score = 0;
1289
1290         head = findchain(classname, "player");
1291         while (head)
1292         {
1293                 if(head.team == COLOR_TEAM1)
1294                 {
1295                         if(head.frags > team1_score)
1296                                 team1_score = head.frags;
1297                 }
1298                 else if(head.team == COLOR_TEAM2)
1299                 {
1300                         if(head.frags > team2_score)
1301                                 team2_score = head.frags;
1302                 }
1303                 else if(head.team == COLOR_TEAM3)
1304                 {
1305                         if(head.frags > team3_score)
1306                                 team3_score = head.frags;
1307                 }
1308                 else if(head.team == COLOR_TEAM4)
1309                 {
1310                         if(head.frags > team4_score)
1311                                 team4_score = head.frags;
1312                 }
1313                 head = head.chain;
1314         }
1315
1316         return WinningConditionBase_Teamplay(fraglimit);
1317 }
1318
1319 void PrintScoreboardFor(string name, string colorcode, float whichteam)
1320 {
1321         entity head;
1322         float v;
1323         float teamvalue;
1324         float fragtotal;
1325         string s;
1326         float found;
1327         found = FALSE;
1328         head = find(world, classname, "player");
1329         teamvalue = 0;
1330         while(head)
1331         {
1332                 if(!whichteam || head.team == whichteam)
1333                 {
1334                         if(name != "")
1335                                 if(!found)
1336                                         ServerConsoleEcho(strcat(" ", colorcode, name, ":"), FALSE);
1337                         found = TRUE;
1338                         fragtotal = fragtotal + head.frags;
1339                         s = ftos(head.frags);
1340                         s = strcat(s, "/", ftos(head.deaths));
1341                         s = strcat(s, " @ ", ftos(head.ping));
1342                         if(clienttype(head) == CLIENTTYPE_BOT)
1343                                 s = strcat(s, "botms");
1344                         else
1345                                 s = strcat(s, "ms");
1346                         v = PlayerValue(head);
1347                         teamvalue += v;
1348                         s = strcat(s, " / ", ftos(v));
1349                         ServerConsoleEcho(strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"), TRUE);
1350                 }
1351                 head = find(head, classname, "player");
1352         }
1353         if(whichteam && found)
1354         {
1355                 s = ftos(fragtotal);
1356                 s = strcat(s, " / ", ftos(teamvalue));
1357                 ServerConsoleEcho(strcat(colorcode, "  (total: ", s, ")"), FALSE);
1358         }
1359 }
1360
1361 void PrintScoreboard()
1362 {
1363         ServerConsoleEcho("Scoreboard:", FALSE);
1364         if(teams_matter)
1365         {
1366                 PrintScoreboardFor("Red", "^1", COLOR_TEAM1);
1367                 PrintScoreboardFor("Blue", "^4", COLOR_TEAM2);
1368                 PrintScoreboardFor("Pink", "^6", COLOR_TEAM3);
1369                 PrintScoreboardFor("Yellow", "^3", COLOR_TEAM4);
1370         }
1371         else
1372         {
1373                 PrintScoreboardFor("", "^7", 0);
1374         }
1375         ServerConsoleEcho(".", FALSE);
1376 }
1377
1378 void RemoveFromMaplist(string m)
1379 {
1380         string result;
1381         float litems;
1382         float i;
1383         float found;
1384
1385         litems = tokenize(cvar_string("g_maplist"));
1386         found = 0;
1387         result = "";
1388         for(i = 0; i < litems; ++i)
1389         {
1390                 m = strcat(m);
1391                 result = strcat(result);
1392                 if(argv(i) == m)
1393                         found += 1;
1394                 else
1395                         result = strcat(result, "'", argv(i), "'");
1396         }
1397         if(found)
1398                 cvar_set("g_maplist", result);
1399         ServerConsoleEcho(strcat("Removed ", ftos(found), " items."), FALSE);
1400 }
1401
1402 void AddToMaplist(string m)
1403 {
1404         string result;
1405         float found;
1406         float litems;
1407         float i;
1408         float ipos;
1409         float inserted;
1410
1411         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1412         {
1413                 ServerConsoleEcho("Map not found.", FALSE);
1414                 return;
1415         }
1416
1417         litems = tokenize(cvar_string("g_maplist"));
1418         if(cvar("g_maplist_shuffle"))
1419                 ipos = ceil(random() * (litems + 1)) - 1;
1420         else
1421                 ipos = litems;
1422         found = 0;
1423         inserted = 0;
1424         for(i = 0; i < litems; ++i)
1425         {
1426                 m = strcat(m);
1427                 if(i == ipos)
1428                 {
1429                         result = strcat(result, "'", m, "'");
1430                         inserted = 1;
1431                 }
1432                 result = strcat(result, "'", argv(i), "'");
1433                 if(argv(i) == m)
1434                         found += 1;
1435         }
1436         if(!inserted)
1437                 result = strcat(result, "'", m, "'");
1438         if(!found)
1439         {
1440                 cvar_set("g_maplist", result);
1441                 ServerConsoleEcho("Map added.", FALSE);
1442         }
1443         else
1444                 ServerConsoleEcho("Map already in list.", FALSE);
1445 }
1446
1447 void ShuffleMaplist()
1448 {
1449         string result;
1450         float start;
1451         float litems;
1452         float selected;
1453         float i;
1454
1455         result = cvar_string("g_maplist");
1456         litems = tokenize(result);
1457
1458         for(start = 0; start < litems - 1; ++start)
1459         {
1460                 result = "";
1461
1462                 // select a random item
1463                 selected = ceil(random() * (litems - start) + start) - 1;
1464
1465                 // shift this item to the place start
1466                 for(i = 0; i < start; ++i)
1467                         result = strcat(result, "'", argv(i), "'");
1468                 result = strcat(result, "'", argv(selected), "'");
1469                 for(i = start; i < litems; ++i)
1470                         if(i != selected)
1471                                 result = strcat(result, "'", argv(i), "'");
1472
1473                 litems = tokenize(result);
1474
1475                 //dprint(result, "\n");
1476         }
1477
1478         cvar_set("g_maplist", result);
1479 }
1480
1481 void() HandleMaplistShuffleCommands =
1482 {
1483         // automatically shuffle when setting g_maplist_shuffle
1484         if(cvar_string("_g_maplist_add") != "")
1485         {
1486                 AddToMaplist(cvar_string("_g_maplist_add"));
1487                 cvar_set("_g_maplist_add", "");
1488         }
1489         if(cvar_string("_g_maplist_remove") != "")
1490         {
1491                 RemoveFromMaplist(cvar_string("_g_maplist_remove"));
1492                 cvar_set("_g_maplist_remove", "");
1493         }
1494         if(cvar("_g_maplist_shufflenow") || (cvar("g_maplist_shuffle") && !cvar("_g_maplist_have_shuffled")))
1495         {
1496                 ShuffleMaplist();
1497                 cvar_set("_g_maplist_shufflenow", "0");
1498                 cvar_set("_g_maplist_have_shuffled", "1");
1499                 ServerConsoleEcho("Shuffled map list.", FALSE);
1500         }
1501         if(cvar("_g_maplist_have_shuffled"))
1502                 if(!cvar("g_maplist_shuffle"))
1503                         cvar_set("_g_maplist_have_shuffled", "0");
1504 }
1505
1506 /*
1507 ============
1508 CheckRules_World
1509
1510 Exit deathmatch games upon conditions
1511 ============
1512 */
1513 void() CheckRules_World =
1514 {
1515         local float status;
1516         local float timelimit;
1517         local float fraglimit;
1518
1519         VoteThink();
1520
1521         SetDefaultAlpha();
1522
1523         if (intermission_running)
1524                 if (time >= intermission_exittime + 60)
1525                 {
1526                         GotoNextMap();
1527                         return;
1528                 }
1529
1530         if (gameover)   // someone else quit the game already
1531                 return;
1532
1533         DumpStats();
1534
1535         if(cvar("_scoreboard"))
1536         {
1537                 cvar_set("_scoreboard", "0");
1538                 PrintScoreboard();
1539         }
1540
1541         HandleMaplistShuffleCommands();
1542
1543         timelimit = cvar("timelimit") * 60;
1544         fraglimit = cvar("fraglimit");
1545
1546         if (timelimit && time >= timelimit)
1547                 InitiateOvertime();
1548
1549         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1550         {
1551                 NextLevel();
1552                 return;
1553         }
1554
1555         if(!checkrules_overtimewarning && checkrules_overtimeend)
1556         {
1557                 checkrules_overtimewarning = TRUE;
1558                 //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1559                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1560         }
1561
1562         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1563         {
1564                 checkrules_oneminutewarning = TRUE;
1565                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1566         }
1567
1568         status = WINNING_NO;
1569         if(cvar("g_lms"))
1570         {
1571                 status = WinningCondition_LMS();
1572         }
1573         else
1574         {
1575                 if(teams_matter)
1576                 {
1577                         if(cvar("g_tdm") || cvar("g_runematch") || cvar("g_ctf") || cvar("g_domination"))
1578                                 status = WinningCondition_MaxTeamSum(fraglimit);
1579                         //else if()
1580                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1581                         else
1582                         {
1583                                 dprint("div0: How can this happen?\n");
1584                                 status = WinningCondition_MaxTeamMax(fraglimit);
1585                         }
1586                 }
1587                 else
1588                         status = WinningCondition_MaxIndividualScore(fraglimit);
1589         }
1590
1591         if(status == WINNING_STARTOVERTIME)
1592         {
1593                 status = WINNING_NEVER;
1594                 InitiateOvertime();
1595         }
1596
1597         if(status == WINNING_NEVER)
1598                 // equality cases! Nobody wins if the overtime ends in a draw.
1599                 ClearWinners();
1600
1601         if(checkrules_overtimeend)
1602                 if(status != WINNING_NEVER)
1603                         status = WINNING_YES;
1604
1605         if(status == WINNING_YES)
1606                 NextLevel();
1607 };