]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Merge branch 'master' into terencehill/itemstime
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #define LATENCY_THINKRATE 10
2 .float latency_sum;
3 .float latency_cnt;
4 .float latency_time;
5 entity pingplreport;
6 void PingPLReport_Think()
7 {
8         float delta;
9         entity e;
10
11         delta = 3 / maxclients;
12         if(delta < sys_frametime)
13                 delta = 0;
14         self.nextthink = time + delta;
15
16         e = edict_num(self.cnt + 1);
17         if(clienttype(e) == CLIENTTYPE_REAL)
18         {
19                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
20                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
21                 WriteByte(MSG_BROADCAST, self.cnt);
22                 WriteShort(MSG_BROADCAST, max(1, e.ping));
23                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
24                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
25
26                 // record latency times for clients throughout the match so we can report it to playerstats
27                 if(time > (e.latency_time + LATENCY_THINKRATE))
28                 {
29                         e.latency_sum += e.ping;
30                         e.latency_cnt += 1;
31                         e.latency_time = time;
32                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
33                 }
34         }
35         else
36         {
37                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
38                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
39                 WriteByte(MSG_BROADCAST, self.cnt);
40                 WriteShort(MSG_BROADCAST, 0);
41                 WriteByte(MSG_BROADCAST, 0);
42                 WriteByte(MSG_BROADCAST, 0);
43         }
44         self.cnt = mod(self.cnt + 1, maxclients);
45 }
46 void PingPLReport_Spawn()
47 {
48         pingplreport = spawn();
49         pingplreport.classname = "pingplreport";
50         pingplreport.think = PingPLReport_Think;
51         pingplreport.nextthink = time;
52 }
53
54 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
55 string redirection_target;
56 float world_initialized;
57
58 string GetMapname();
59 string GetGametype();
60 void GotoNextMap(float reinit);
61 void ShuffleMaplist();
62 float(float reinit) DoNextMapOverride;
63
64 void SetDefaultAlpha()
65 {
66         if(autocvar_g_running_guns)
67         {
68                 default_player_alpha = -1;
69                 default_weapon_alpha = +1;
70         }
71         else if(g_cloaked)
72         {
73                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
74                 default_weapon_alpha = default_player_alpha;
75         }
76         else
77         {
78                 default_player_alpha = autocvar_g_player_alpha;
79                 if(default_player_alpha == 0)
80                         default_player_alpha = 1;
81                 default_weapon_alpha = default_player_alpha;
82         }
83 }
84
85 void fteqcc_testbugs()
86 {
87         float a, b;
88
89         if(!autocvar_developer_fteqccbugs)
90                 return;
91
92         dprint("*** fteqcc test: checking for bugs...\n");
93
94         a = 1;
95         b = 5;
96         if(sqrt(a) - sqrt(b - a) == 0)
97                 dprint("*** fteqcc test: found same-function-twice bug\n");
98         else
99                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
100
101         world.cnt = -10;
102         world.enemy = world;
103         world.enemy.cnt += 10;
104         if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
105                 dprint("*** fteqcc test: found += bug\n");
106         else
107                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
108         world.cnt = 0;
109 }
110
111 void GotoFirstMap()
112 {
113         float n;
114         if(autocvar__sv_init)
115         {
116                 // cvar_set("_sv_init", "0");
117                 // we do NOT set this to 0 any more, so someone "accidentally" changing
118                 // to this "init" map on a dedicated server will cause no permanent
119                 // harm
120                 if(autocvar_g_maplist_shuffle)
121                         ShuffleMaplist();
122                 n = tokenizebyseparator(autocvar_g_maplist, " ");
123                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
124
125                 MapInfo_Enumerate();
126                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
127
128                 if(!DoNextMapOverride(1))
129                         GotoNextMap(1);
130
131                 return;
132         }
133
134         if(time < 5)
135         {
136                 self.nextthink = time;
137         }
138         else
139         {
140                 self.nextthink = time + 1;
141                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
142         }
143 }
144
145 void cvar_changes_init()
146 {
147         float h;
148         string k, v, d;
149         float n, i, adding, pureadding;
150
151         if(cvar_changes)
152                 strunzone(cvar_changes);
153         cvar_changes = string_null;
154         if(cvar_purechanges)
155                 strunzone(cvar_purechanges);
156         cvar_purechanges = string_null;
157         cvar_purechanges_count = 0;
158
159         h = buf_create();
160         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
161         n = buf_getsize(h);
162
163         adding = TRUE;
164         pureadding = TRUE;
165
166         for(i = 0; i < n; ++i)
167         {
168                 k = bufstr_get(h, i);
169
170 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
171 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
172 #define BADCVAR(p) if(k == p) continue
173
174                 // general excludes and namespaces for server admin used cvars
175                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
176
177                 // internal
178                 BADPREFIX("csqc_");
179                 BADPREFIX("cvar_check_");
180                 BADCVAR("gamecfg");
181                 BADCVAR("g_configversion");
182                 BADCVAR("g_maplist_index");
183                 BADCVAR("halflifebsp");
184                 BADPREFIX("sv_world");
185
186                 // client
187                 BADPREFIX("chase_");
188                 BADPREFIX("cl_");
189                 BADPREFIX("con_");
190                 BADPREFIX("scoreboard_");
191                 BADPREFIX("g_campaign");
192                 BADPREFIX("g_waypointsprite_");
193                 BADPREFIX("gl_");
194                 BADPREFIX("joy");
195                 BADPREFIX("hud_");
196                 BADPREFIX("m_");
197                 BADPREFIX("menu_");
198                 BADPREFIX("net_slist_");
199                 BADPREFIX("r_");
200                 BADPREFIX("sbar_");
201                 BADPREFIX("scr_");
202                 BADPREFIX("snd_");
203                 BADPREFIX("show");
204                 BADPREFIX("sensitivity");
205                 BADPREFIX("userbind");
206                 BADPREFIX("v_");
207                 BADPREFIX("vid_");
208                 BADPREFIX("crosshair");
209                 BADCVAR("mod_q3bsp_lightmapmergepower");
210                 BADCVAR("mod_q3bsp_nolightmaps");
211                 BADCVAR("fov");
212                 BADCVAR("mastervolume");
213                 BADCVAR("volume");
214                 BADCVAR("bgmvolume");
215
216                 // private
217                 BADCVAR("developer");
218                 BADCVAR("log_dest_udp");
219                 BADCVAR("log_file");
220                 BADCVAR("net_address");
221                 BADCVAR("net_address_ipv6");
222                 BADCVAR("port");
223                 BADCVAR("savedgamecfg");
224                 BADCVAR("serverconfig");
225                 BADCVAR("sv_autoscreenshot");
226                 BADCVAR("sv_heartbeatperiod");
227                 BADCVAR("sv_vote_master_password");
228                 BADCVAR("sys_colortranslation");
229                 BADCVAR("sys_specialcharactertranslation");
230                 BADCVAR("timeformat");
231                 BADCVAR("timestamps");
232                 BADPREFIX("developer_");
233                 BADPREFIX("g_ban_");
234                 BADPREFIX("g_banned_list");
235                 BADPREFIX("g_chat_flood_");
236                 BADPREFIX("g_ghost_items");
237                 BADPREFIX("g_playerstats_");
238                 BADPREFIX("g_respawn_ghosts");
239                 BADPREFIX("g_voice_flood_");
240                 BADPREFIX("rcon_");
241                 BADPREFIX("sv_allowdownloads");
242                 BADPREFIX("sv_autodemo");
243                 BADPREFIX("sv_curl_");
244                 BADPREFIX("sv_eventlog");
245                 BADPREFIX("sv_logscores_");
246                 BADPREFIX("sv_master");
247                 BADPREFIX("sv_weaponstats_");
248                 BADPREFIX("sv_waypointsprite_");
249                 BADCVAR("rescan_pending");
250
251                 // these can contain player IDs, so better hide
252                 BADPREFIX("g_forced_team_");
253
254                 // mapinfo
255                 BADCVAR("fraglimit");
256                 BADCVAR("g_arena");
257                 BADCVAR("g_assault");
258                 BADCVAR("g_ca");
259                 BADCVAR("g_ctf");
260                 BADCVAR("g_cts");
261                 BADCVAR("g_dm");
262                 BADCVAR("g_domination");
263                 BADCVAR("g_domination_default_teams");
264                 BADCVAR("g_freezetag");
265                 BADCVAR("g_keepaway");
266                 BADCVAR("g_keyhunt");
267                 BADCVAR("g_keyhunt_teams");
268                 BADCVAR("g_keyhunt_teams");
269                 BADCVAR("g_lms");
270                 BADCVAR("g_nexball");
271                 BADCVAR("g_onslaught");
272                 BADCVAR("g_race");
273                 BADCVAR("g_race_qualifying_timelimit");
274                 BADCVAR("g_runematch");
275                 BADCVAR("g_tdm");
276                 BADCVAR("g_tdm_teams");
277                 BADCVAR("leadlimit");
278                 BADCVAR("nextmap");
279                 BADCVAR("teamplay");
280                 BADCVAR("timelimit");
281
282                 // long
283                 BADCVAR("hostname");
284                 BADCVAR("g_maplist");
285                 BADCVAR("g_maplist_mostrecent");
286                 BADCVAR("sv_motd");
287
288                 v = cvar_string(k);
289                 d = cvar_defstring(k);
290                 if(v == d)
291                         continue;
292
293                 if(adding)
294                 {
295                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
296                         if(strlen(cvar_changes) > 16384)
297                         {
298                                 cvar_changes = "// too many settings have been changed to show them here\n";
299                                 adding = 0;
300                         }
301                 }
302
303                 // now check if the changes are actually gameplay relevant
304
305                 // does nothing visible
306                 BADCVAR("captureleadlimit_override");
307                 BADCVAR("g_arena_point_leadlimit");
308                 BADCVAR("g_balance_kill_delay");
309                 BADCVAR("g_ca_point_leadlimit");
310                 BADCVAR("g_ctf_captimerecord_always");
311                 BADCVAR("g_ctf_flag_glowtrails");
312                 BADCVAR("g_ctf_flag_pickup_verbosename");
313                 BADCVAR("g_domination_point_leadlimit");
314                 BADCVAR("g_forced_respawn");
315                 BADCVAR("g_keyhunt_point_leadlimit");
316                 BADPREFIX("g_mod_");
317                 BADCVAR("g_nexball_goalleadlimit");
318                 BADCVAR("g_runematch_point_leadlimit");
319                 BADCVAR("leadlimit_and_fraglimit");
320                 BADCVAR("leadlimit_override");
321                 BADCVAR("pausable");
322                 BADCVAR("sv_allow_fullbright");
323                 BADCVAR("sv_checkforpacketsduringsleep");
324                 BADCVAR("sv_fraginfo");
325                 BADCVAR("sv_timeout");
326                 BADPREFIX("sv_timeout_");
327                 BADCVAR("welcome_message_time");
328                 BADPREFIX("crypto_");
329                 BADPREFIX("g_chat_");
330                 BADPREFIX("g_ctf_captimerecord_");
331                 BADPREFIX("g_maplist_votable_");
332                 BADPREFIX("net_");
333                 BADPREFIX("prvm_");
334                 BADPREFIX("skill_");
335                 BADPREFIX("sv_cullentities_");
336                 BADPREFIX("sv_fraginfo_");
337                 BADPREFIX("sv_maxidle_");
338                 BADPREFIX("sv_vote_");
339                 BADPREFIX("timelimit_");
340                 BADCVAR("gameversion");
341                 BADPREFIX("gameversion_");
342                 BADCVAR("sv_namechangetimer");
343
344                 // allowed changes to server admins (please sync this to server.cfg)
345                 // vi commands:
346                 //   :/"impure"/,$d
347                 //   :g!,^\/\/[^ /],d
348                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
349                 //   :%!sort
350                 // yes, this does contain some redundant stuff, don't really care
351                 BADCVAR("bot_config_file");
352                 BADCVAR("bot_number");
353                 BADCVAR("bot_prefix");
354                 BADCVAR("bot_suffix");
355                 BADCVAR("capturelimit_override");
356                 BADCVAR("fraglimit_override");
357                 BADCVAR("gametype");
358                 BADCVAR("g_antilag");
359                 BADCVAR("g_balance_teams");
360                 BADCVAR("g_balance_teams_prevent_imbalance");
361                 BADCVAR("g_balance_teams_scorefactor");
362                 BADCVAR("g_ban_sync_trusted_servers");
363                 BADCVAR("g_ban_sync_uri");
364                 BADCVAR("g_ctf_ignore_frags");
365                 BADCVAR("g_domination_point_limit");
366                 BADCVAR("g_friendlyfire");
367                 BADCVAR("g_fullbrightitems");
368                 BADCVAR("g_fullbrightplayers");
369                 BADCVAR("g_keyhunt_point_limit");
370                 BADCVAR("g_keyhunt_teams_override");
371                 BADCVAR("g_lms_lives_override");
372                 BADCVAR("g_maplist");
373                 BADCVAR("g_maplist_check_waypoints");
374                 BADCVAR("g_maplist_mostrecent_count");
375                 BADCVAR("g_maplist_shuffle");
376                 BADCVAR("g_maplist_votable");
377                 BADCVAR("g_maplist_votable_abstain");
378                 BADCVAR("g_maplist_votable_nodetail");
379                 BADCVAR("g_maplist_votable_suggestions");
380                 BADCVAR("g_maxplayers");
381                 BADCVAR("g_mirrordamage");
382                 BADCVAR("g_nexball_goallimit");
383                 BADCVAR("g_powerups");
384                 BADCVAR("g_runematch_point_limit");
385                 BADCVAR("g_start_delay");
386                 BADCVAR("g_warmup");
387                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
388                 BADCVAR("hostname");
389                 BADCVAR("log_file");
390                 BADCVAR("maxplayers");
391                 BADCVAR("minplayers");
392                 BADCVAR("net_address");
393                 BADCVAR("port");
394                 BADCVAR("rcon_password");
395                 BADCVAR("rcon_restricted_commands");
396                 BADCVAR("rcon_restricted_password");
397                 BADCVAR("skill");
398                 BADCVAR("sv_adminnick");
399                 BADCVAR("sv_autoscreenshot");
400                 BADCVAR("sv_autotaunt");
401                 BADCVAR("sv_curl_defaulturl");
402                 BADCVAR("sv_defaultcharacter");
403                 BADCVAR("sv_defaultplayercolors");
404                 BADCVAR("sv_defaultplayermodel");
405                 BADCVAR("sv_defaultplayerskin");
406                 BADCVAR("sv_maxidle");
407                 BADCVAR("sv_maxrate");
408                 BADCVAR("sv_motd");
409                 BADCVAR("sv_public");
410                 BADCVAR("sv_ready_restart");
411                 BADCVAR("sv_status_privacy");
412                 BADCVAR("sv_taunt");
413                 BADCVAR("sv_vote_call");
414                 BADCVAR("sv_vote_commands");
415                 BADCVAR("sv_vote_majority_factor");
416                 BADCVAR("sv_vote_master");
417                 BADCVAR("sv_vote_master_commands");
418                 BADCVAR("sv_vote_master_password");
419                 BADCVAR("sv_vote_simple_majority_factor");
420                 BADCVAR("sys_ticrate");
421                 BADCVAR("teamplay_mode");
422                 BADCVAR("timelimit_override");
423                 BADCVAR("g_spawnshieldtime");
424                 BADPREFIX("g_warmup_");
425                 BADPREFIX("sv_ready_restart_");
426
427                 // mutators that announce themselves properly to the server browser
428                 BADCVAR("g_minstagib");
429                 BADCVAR("g_new_toys");
430                 BADCVAR("g_nix");
431
432                 if(autocvar_g_minstagib)
433                 {
434                         BADCVAR("g_grappling_hook");
435                         BADCVAR("g_jetpack");
436                 }
437 #undef BADPREFIX
438 #undef BADCVAR
439
440                 if(pureadding)
441                 {
442                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
443                         if(strlen(cvar_purechanges) > 16384)
444                         {
445                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
446                                 pureadding = 0;
447                         }
448                 }
449                 ++cvar_purechanges_count;
450                 // WARNING: this variable is used for the server list
451                 // NEVER dare to skip this code!
452                 // Hacks to intentionally appearing as "pure server" even though you DO have
453                 // modified settings may be punished by removal from the server list.
454                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
455                 // though.
456         }
457         buf_del(h);
458         if(cvar_changes == "")
459                 cvar_changes = "// this server runs at default server settings\n";
460         else
461                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
462         cvar_changes = strzone(cvar_changes);
463         if(cvar_purechanges == "")
464                 cvar_purechanges = "// this server runs at default gameplay settings\n";
465         else
466                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
467         cvar_purechanges = strzone(cvar_purechanges);
468 }
469
470 void detect_maptype()
471 {
472 #if 0
473         vector o, v;
474         float i;
475
476         for(;;)
477         {
478                 o = world.mins;
479                 o_x += random() * (world.maxs_x - world.mins_x);
480                 o_y += random() * (world.maxs_y - world.mins_y);
481                 o_z += random() * (world.maxs_z - world.mins_z);
482
483                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
484                 if(trace_fraction == 1)
485                         continue;
486
487                 v = trace_endpos;
488
489                 for(i = 0; i < 64; i += 4)
490                 {
491                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
492         if(trace_fraction == 1)
493                 continue;
494                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
495                 }
496
497                 break;
498         }
499 #endif
500 }
501
502 entity randomseed;
503 float RandomSeed_Send(entity to, float sf)
504 {
505         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
506         WriteShort(MSG_ENTITY, self.cnt);
507         return TRUE;
508 }
509 void RandomSeed_Think()
510 {
511         self.cnt = bound(0, floor(random() * 65536), 65535);
512         self.nextthink = time + 5;
513
514         self.SendFlags |= 1;
515 }
516 void RandomSeed_Spawn()
517 {
518         randomseed = spawn();
519         randomseed.think = RandomSeed_Think;
520         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
521
522         entity oldself;
523         oldself = self;
524         self = randomseed;
525         self.think(); // sets random seed and nextthink
526         self = oldself;
527 }
528
529 void spawnfunc___init_dedicated_server(void)
530 {
531         // handler for _init/_init map (only for dedicated server initialization)
532
533         world_initialized = -1; // don't complain
534         cvar = cvar_normal;
535         cvar_string = cvar_string_normal;
536         cvar_set = cvar_set_normal;
537
538         remove = remove_unsafely;
539
540         entity e;
541         e = spawn();
542         e.think = GotoFirstMap;
543         e.nextthink = time; // this is usually 1 at this point
544
545         e = spawn();
546         e.classname = "info_player_deathmatch"; // safeguard against player joining
547
548         self.classname = "worldspawn"; // safeguard against various stuff ;)
549
550         // needs to be done so early because of the constants they create
551         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
552         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
553         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
554         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
555
556         MapInfo_Enumerate();
557         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
558 }
559
560 void Map_MarkAsRecent(string m);
561 float world_already_spawned;
562 void Nagger_Init();
563 void Item_ItemsTime_Init();
564 void ClientInit_Spawn();
565 void WeaponStats_Init();
566 void WeaponStats_Shutdown();
567 void spawnfunc_worldspawn (void)
568 {
569         float fd, l, i, j, n;
570         string s, col;
571
572         cvar = cvar_normal;
573         cvar_string = cvar_string_normal;
574         cvar_set = cvar_set_normal;
575
576         if(world_already_spawned)
577                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
578         world_already_spawned = TRUE;
579
580         remove = remove_safely; // during spawning, watch what you remove!
581
582         check_unacceptable_compiler_bugs();
583
584         cvar_changes_init(); // do this very early now so it REALLY matches the server config
585
586         compressShortVector_init();
587
588         allowed_to_spawn = TRUE;
589
590         entity head;
591         head = nextent(world);
592         maxclients = 0;
593         while(head)
594         {
595                 ++maxclients;
596                 head = nextent(head);
597         }
598
599         server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? TRUE : FALSE);
600
601         // needs to be done so early because of the constants they create
602         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
603         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
604         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
605         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
606
607         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
608
609         TemporaryDB = db_create();
610
611         // 0 normal
612         lightstyle(0, "m");
613
614         // 1 FLICKER (first variety)
615         lightstyle(1, "mmnmmommommnonmmonqnmmo");
616
617         // 2 SLOW STRONG PULSE
618         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
619
620         // 3 CANDLE (first variety)
621         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
622
623         // 4 FAST STROBE
624         lightstyle(4, "mamamamamama");
625
626         // 5 GENTLE PULSE 1
627         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
628
629         // 6 FLICKER (second variety)
630         lightstyle(6, "nmonqnmomnmomomno");
631
632         // 7 CANDLE (second variety)
633         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
634
635         // 8 CANDLE (third variety)
636         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
637
638         // 9 SLOW STROBE (fourth variety)
639         lightstyle(9, "aaaaaaaazzzzzzzz");
640
641         // 10 FLUORESCENT FLICKER
642         lightstyle(10, "mmamammmmammamamaaamammma");
643
644         // 11 SLOW PULSE NOT FADE TO BLACK
645         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
646
647         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
648
649         // 63 testing
650         lightstyle(63, "a");
651
652         if(autocvar_g_campaign)
653                 CampaignPreInit();
654
655         Map_MarkAsRecent(mapname);
656
657         PlayerStats_Init(); // we need this to be initiated before InitGameplayMode
658
659         precache_model ("null"); // we need this one before InitGameplayMode
660         InitGameplayMode();
661         readlevelcvars();
662         GrappleHookInit();
663         ElectroInit();
664         LaserInit();
665
666         player_count = 0;
667         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
668         if(bot_waypoints_for_items == 1)
669                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
670                         bot_waypoints_for_items = 0;
671
672         precache();
673
674         WaypointSprite_Init();
675
676         GameLogInit(); // prepare everything
677         // NOTE for matchid:
678         // changing the logic generating it is okay. But:
679         // it HAS to stay <= 64 chars
680         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
681         if(autocvar_sv_eventlog)
682         {
683                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
684                 matchid = strzone(s);
685
686                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
687                 s = ":gameinfo:mutators:LIST";
688
689                 ret_string = s;
690                 MUTATOR_CALLHOOK(BuildMutatorsString);
691                 s = ret_string;
692
693                 // simple, probably not good in the mutator system
694                 if(autocvar_g_grappling_hook)
695                         s = strcat(s, ":grappling_hook");
696
697                 // initialiation stuff, not good in the mutator system
698                 if(!autocvar_g_use_ammunition)
699                         s = strcat(s, ":no_use_ammunition");
700
701                 // initialiation stuff, not good in the mutator system
702                 if(autocvar_g_pickup_items == 0)
703                         s = strcat(s, ":no_pickup_items");
704                 if(autocvar_g_pickup_items > 0)
705                         s = strcat(s, ":pickup_items");
706
707                 // initialiation stuff, not good in the mutator system
708                 if(autocvar_g_weaponarena != "0")
709                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
710
711                 // TODO to mutator system
712                 if(autocvar_g_norecoil)
713                         s = strcat(s, ":norecoil");
714
715                 // TODO to mutator system
716                 if(autocvar_g_midair)
717                         s = strcat(s, ":midair");
718
719                 // TODO to mutator system
720                 if(autocvar_g_minstagib)
721                         s = strcat(s, ":minstagib");
722
723                 // TODO to mutator system
724                 if(autocvar_g_powerups == 0)
725                         s = strcat(s, ":no_powerups");
726                 if(autocvar_g_powerups > 0)
727                         s = strcat(s, ":powerups");
728
729                 GameLogEcho(s);
730                 GameLogEcho(":gameinfo:end");
731         }
732         else
733                 matchid = strzone(ftos(random()));
734
735         cvar_set("nextmap", "");
736
737         SetDefaultAlpha();
738
739         if(autocvar_g_campaign)
740                 CampaignPostInit();
741
742         fteqcc_testbugs();
743
744         Ban_LoadBans();
745
746         MapInfo_Enumerate();
747         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
748
749         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
750         {
751                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
752                 if(fd != -1)
753                 {
754                         while((s = fgets(fd)))
755                         {
756                                 l = tokenize_console(s);
757                                 if(l < 2)
758                                         continue;
759                                 if(argv(0) == "cd")
760                                 {
761                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
762                                         print("  cdtrack ", argv(2), "\n");
763                                 }
764                                 else if(argv(0) == "fog")
765                                 {
766                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
767                                         print("  \"fog\" \"", s, "\"\n");
768                                 }
769                                 else if(argv(0) == "set")
770                                 {
771                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
772                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
773                                 }
774                                 else if(argv(0) != "//")
775                                 {
776                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
777                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
778                                 }
779                         }
780                         fclose(fd);
781                 }
782         }
783
784         WeaponStats_Init();
785
786         WEPSET_ADDSTAT();
787         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
788         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
789         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
790         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
791         Nagger_Init();
792
793         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
794         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
795         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
796         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
797         addstat(STAT_FUEL, AS_INT, ammo_fuel);
798         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
799         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
800         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
801         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
802         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
803         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
804         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
805         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
806
807         addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
808         addstat(STAT_NEX_CHARGEPOOL, AS_FLOAT, nex_chargepool_ammo);
809
810         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
811
812         addstat(STAT_ARMOR_LARGE_TIME, AS_FLOAT, item_armor_large_time);
813         addstat(STAT_HEALTH_MEGA_TIME, AS_FLOAT, item_health_mega_time);
814         addstat(STAT_INVISIBLE_TIME, AS_FLOAT, item_invisible_time);
815         addstat(STAT_SPEED_TIME, AS_FLOAT, item_speed_time);
816         addstat(STAT_EXTRALIFE_TIME, AS_FLOAT, item_extralife_time);
817         addstat(STAT_STRENGTH_TIME, AS_FLOAT, item_strength_time);
818         addstat(STAT_SHIELD_TIME, AS_FLOAT, item_shield_time);
819         addstat(STAT_FUELREGEN_TIME, AS_FLOAT, item_fuelregen_time);
820         addstat(STAT_JETPACK_TIME, AS_FLOAT, item_jetpack_time);
821         addstat(STAT_SUPERWEAPONS_TIME, AS_FLOAT, item_superweapons_time);
822         Item_ItemsTime_Init();
823
824         if(g_ca || g_freezetag)
825         {
826                 addstat(STAT_REDALIVE, AS_INT, redalive_stat);
827                 addstat(STAT_BLUEALIVE, AS_INT, bluealive_stat);
828                 addstat(STAT_YELLOWALIVE, AS_INT, yellowalive_stat);
829                 addstat(STAT_PINKALIVE, AS_INT, pinkalive_stat);
830         }
831         if(g_freezetag)
832         {
833                 addstat(STAT_FROZEN, AS_INT, freezetag_frozen);
834                 addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, freezetag_revive_progress);
835         }
836
837         // g_movementspeed hack
838         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
839         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
840         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
841         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
842
843         // secrets
844         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
845         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
846
847         // misc
848         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
849
850         next_pingtime = time + 5;
851
852         detect_maptype();
853
854         // set up information replies for clients and server to use
855         lsmaps_reply = "^7Maps available: ";
856         lsnewmaps_reply = "^7Maps without a record set: ";
857         for(i = 0, j = 0; i < MapInfo_count; ++i)
858         {
859                 if(MapInfo_Get_ByID(i))
860                         if not(MapInfo_Map_flags & MapInfo_ForbiddenFlags())
861                         {
862                                 if(mod(i, 2))
863                                         col = "^2";
864                                 else
865                                         col = "^3";
866
867                                 ++j;
868
869                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
870
871                                 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
872                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
873                                 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
874                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
875                         }
876         }
877
878         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
879         lsnewmaps_reply = strzone(strcat(((!g_race && !g_cts) ? "Need to be playing race or CTS for lsnewmaps to work." : lsnewmaps_reply), "\n"));
880
881         maplist_reply = "^7Maps in list: ";
882         n = tokenize_console(autocvar_g_maplist);
883         for(i = 0, j = 0; i < n; ++i)
884         {
885                 if(MapInfo_CheckMap(argv(i)))
886                 {
887                         if(mod(j, 2))
888                                 col = "^2";
889                         else
890                                 col = "^3";
891                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
892                         ++j;
893                 }
894         }
895         maplist_reply = strzone(strcat(maplist_reply, "\n"));
896         MapInfo_ClearTemps();
897
898         for(i = 0; i < 10; ++i)
899         {
900                 s = getrecords(i);
901                 if (s)
902                         records_reply[i] = strzone(s);
903         }
904
905         ladder_reply = strzone(getladder());
906
907         rankings_reply = strzone(getrankings());
908
909         // begin other init
910         ClientInit_Spawn();
911         RandomSeed_Spawn();
912         PingPLReport_Spawn();
913
914         CheatInit();
915
916         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
917
918         // fill sv_curl_serverpackages from .serverpackage files
919         if(autocvar_sv_curl_serverpackages_auto)
920         {
921                 s = "";
922                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
923                 for(i = 0; i < n; ++i)
924                         if(substring(argv(i), -14, -1) != "-serverpackage.txt")
925                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
926                                 s = strcat(s, " ", argv(i));
927                 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
928                 if(fd >= 0)
929                 {
930                         j = search_getsize(fd);
931                         for(i = 0; i < j; ++i)
932                                 s = strcat(s, " ", search_getfilename(fd, i));
933                         search_end(fd);
934                 }
935                 fd = search_begin("*.serverpackage", TRUE, FALSE);
936                 if(fd >= 0)
937                 {
938                         j = search_getsize(fd);
939                         for(i = 0; i < j; ++i)
940                                 s = strcat(s, " ", search_getfilename(fd, i));
941                         search_end(fd);
942                 }
943                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
944         }
945
946         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
947         modname = "Xonotic";
948         // physics/balance/config changes that count as mod
949         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
950                 modname = cvar_string("g_mod_physics");
951         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
952                 modname = cvar_string("g_mod_balance");
953         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
954                 modname = cvar_string("g_mod_config");
955         // weird mutators that deserve to count as mod
956         if(autocvar_g_minstagib)
957                 modname = "MinstaGib";
958         // extra mutators that deserve to count as mod
959         MUTATOR_CALLHOOK(SetModname);
960
961         // save it for later
962         modname = strzone(modname);
963
964         WinningConditionHelper(); // set worldstatus
965
966         world_initialized = 1;
967 }
968
969 void spawnfunc_light (void)
970 {
971         //makestatic (self); // Who the f___ did that?
972         remove(self);
973 }
974
975 string GetGametype()
976 {
977         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
978 }
979
980 string getmapname_stored;
981 string GetMapname()
982 {
983         return mapname;
984 }
985
986 float Map_Count, Map_Current;
987 string Map_Current_Name;
988
989 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
990 float GetMaplistPosition()
991 {
992         float pos, idx;
993         string map;
994
995         map = GetMapname();
996         idx = autocvar_g_maplist_index;
997
998         if(idx >= 0)
999                 if(idx < Map_Count)
1000                         if(map == argv(idx))
1001                                 return idx;
1002
1003         for(pos = 0; pos < Map_Count; ++pos)
1004                 if(map == argv(pos))
1005                         return pos;
1006
1007         // resume normal maplist rotation if current map is not in g_maplist
1008         return idx;
1009 }
1010
1011 float MapHasRightSize(string map)
1012 {
1013         float fh;
1014         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
1015         if(autocvar_g_maplist_check_waypoints)
1016         {
1017                 dprint("checkwp "); dprint(map);
1018                 if(!fexists(strcat("maps/", map, ".waypoints")))
1019                 {
1020                         dprint(": no waypoints\n");
1021                         return FALSE;
1022                 }
1023                 dprint(": has waypoints\n");
1024         }
1025
1026         // open map size restriction file
1027         dprint("opensize "); dprint(map);
1028         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1029         if(fh >= 0)
1030         {
1031                 float mapmin, mapmax;
1032                 dprint(": ok, ");
1033                 mapmin = stof(fgets(fh));
1034                 mapmax = stof(fgets(fh));
1035                 fclose(fh);
1036                 if(player_count < mapmin)
1037                 {
1038                         dprint("not enough\n");
1039                         return FALSE;
1040                 }
1041                 if(player_count > mapmax)
1042                 {
1043                         dprint("too many\n");
1044                         return FALSE;
1045                 }
1046                 dprint("right size\n");
1047                 return TRUE;
1048         }
1049         dprint(": not found\n");
1050         return TRUE;
1051 }
1052
1053 string Map_Filename(float position)
1054 {
1055         return strcat("maps/", argv(position), ".bsp");
1056 }
1057
1058 string strwords(string s, float w)
1059 {
1060         float endpos;
1061         for(endpos = 0; w && endpos >= 0; --w)
1062                 endpos = strstrofs(s, " ", endpos + 1);
1063         if(endpos < 0)
1064                 return s;
1065         else
1066                 return substring(s, 0, endpos);
1067 }
1068
1069 float strhasword(string s, string w)
1070 {
1071         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1072 }
1073
1074 void Map_MarkAsRecent(string m)
1075 {
1076         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1077 }
1078
1079 float Map_IsRecent(string m)
1080 {
1081         return strhasword(autocvar_g_maplist_mostrecent, m);
1082 }
1083
1084 float Map_Check(float position, float pass)
1085 {
1086         string filename;
1087         string map_next;
1088         map_next = argv(position);
1089         if(pass <= 1)
1090         {
1091                 if(Map_IsRecent(map_next))
1092                         return 0;
1093         }
1094         filename = Map_Filename(position);
1095         if(MapInfo_CheckMap(map_next))
1096         {
1097                 if(pass == 2)
1098                         return 1;
1099                 if(MapHasRightSize(map_next))
1100                         return 1;
1101                 return 0;
1102         }
1103         else
1104                 dprint( "Couldn't select '", filename, "'..\n" );
1105
1106         return 0;
1107 }
1108
1109 void Map_Goto_SetStr(string nextmapname)
1110 {
1111         if(getmapname_stored != "")
1112                 strunzone(getmapname_stored);
1113         if(nextmapname == "")
1114                 getmapname_stored = "";
1115         else
1116                 getmapname_stored = strzone(nextmapname);
1117 }
1118
1119 void Map_Goto_SetFloat(float position)
1120 {
1121         cvar_set("g_maplist_index", ftos(position));
1122         Map_Goto_SetStr(argv(position));
1123 }
1124
1125 void Map_Goto(float reinit)
1126 {
1127         MapInfo_LoadMap(getmapname_stored, reinit);
1128 }
1129
1130 // return codes of map selectors:
1131 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1132 //   -2 = permanent failure
1133 float() MaplistMethod_Iterate = // usual method
1134 {
1135         float pass, i;
1136
1137         for(pass = 1; pass <= 2; ++pass)
1138         {
1139                 for(i = 1; i < Map_Count; ++i)
1140                 {
1141                         float mapindex;
1142                         mapindex = mod(i + Map_Current, Map_Count);
1143                         if(Map_Check(mapindex, pass))
1144                                 return mapindex;
1145                 }
1146         }
1147         return -1;
1148 }
1149
1150 float() MaplistMethod_Repeat = // fallback method
1151 {
1152         if(Map_Check(Map_Current, 2))
1153                 return Map_Current;
1154         return -2;
1155 }
1156
1157 float() MaplistMethod_Random = // random map selection
1158 {
1159         float i, imax;
1160
1161         imax = 42;
1162
1163         for(i = 0; i <= imax; ++i)
1164         {
1165                 float mapindex;
1166                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
1167                 if(Map_Check(mapindex, 1))
1168                         return mapindex;
1169         }
1170         return -1;
1171 }
1172
1173 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1174 // the exponent sets a bias on the map selection:
1175 // the higher the exponent, the less likely "shortly repeated" same maps are
1176 {
1177         float i, j, imax, insertpos;
1178
1179         imax = 42;
1180
1181         for(i = 0; i <= imax; ++i)
1182         {
1183                 string newlist;
1184
1185                 // now reinsert this at another position
1186                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1187                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1188                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1189                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1190
1191                 // insert the current map there
1192                 newlist = "";
1193                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1194                         newlist = strcat(newlist, " ", argv(j));
1195                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1196                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1197                         newlist = strcat(newlist, " ", argv(j));
1198                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1199                 cvar_set("g_maplist", newlist);
1200                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1201
1202                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1203                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1204                 if(Map_Check(Map_Current, 1))
1205                         return Map_Current;
1206         }
1207         return -1;
1208 }
1209
1210 void Maplist_Init()
1211 {
1212         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1213         if(Map_Count == 0)
1214         {
1215                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
1216                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1217                 if(autocvar_g_maplist_shuffle)
1218                         ShuffleMaplist();
1219                 localcmd("\nmenu_cmd sync\n");
1220                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1221         }
1222         if(Map_Count == 0)
1223                 error("empty maplist, cannot select a new map");
1224         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1225
1226         if(Map_Current_Name)
1227                 strunzone(Map_Current_Name);
1228         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1229         // this may or may not be correct, but who cares, in the worst case a map
1230         // isn't chosen in the first pass that should have been
1231 }
1232
1233 string GetNextMap()
1234 {
1235         float nextMap;
1236
1237         Maplist_Init();
1238         nextMap = -1;
1239
1240         if(nextMap == -1)
1241                 if(autocvar_g_maplist_shuffle > 0)
1242                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1243
1244         if(nextMap == -1)
1245                 if(autocvar_g_maplist_selectrandom)
1246                         nextMap = MaplistMethod_Random();
1247
1248         if(nextMap == -1)
1249                 nextMap = MaplistMethod_Iterate();
1250
1251         if(nextMap == -1)
1252                 nextMap = MaplistMethod_Repeat();
1253
1254         if(nextMap >= 0)
1255         {
1256                 Map_Goto_SetFloat(nextMap);
1257                 return getmapname_stored;
1258         }
1259
1260         return "";
1261 }
1262
1263 float DoNextMapOverride(float reinit)
1264 {
1265         if(autocvar_g_campaign)
1266         {
1267                 CampaignPostIntermission();
1268                 alreadychangedlevel = TRUE;
1269                 return TRUE;
1270         }
1271         if(autocvar_quit_when_empty)
1272         {
1273                 if(player_count <= currentbots)
1274                 {
1275                         localcmd("quit\n");
1276                         alreadychangedlevel = TRUE;
1277                         return TRUE;
1278                 }
1279         }
1280         if(autocvar_quit_and_redirect != "")
1281         {
1282                 redirection_target = strzone(autocvar_quit_and_redirect);
1283                 alreadychangedlevel = TRUE;
1284                 return TRUE;
1285         }
1286         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1287         {
1288                 localcmd("restart\n");
1289                 alreadychangedlevel = TRUE;
1290                 return TRUE;
1291         }
1292         if(autocvar_nextmap != "")
1293                 if(MapInfo_CheckMap(autocvar_nextmap))
1294                 {
1295                         Map_Goto_SetStr(autocvar_nextmap);
1296                         Map_Goto(reinit);
1297                         alreadychangedlevel = TRUE;
1298                         return TRUE;
1299                 }
1300         if(!reinit && autocvar_lastlevel)
1301         {
1302                 cvar_settemp_restore();
1303                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1304                 alreadychangedlevel = TRUE;
1305                 return TRUE;
1306         }
1307         return FALSE;
1308 }
1309
1310 void GotoNextMap(float reinit)
1311 {
1312         //string nextmap;
1313         //float n, nummaps;
1314         //string s;
1315         if (alreadychangedlevel)
1316                 return;
1317         alreadychangedlevel = TRUE;
1318
1319         {
1320                 string nextMap;
1321                 float allowReset;
1322
1323                 for(allowReset = 1; allowReset >= 0; --allowReset)
1324                 {
1325                         nextMap = GetNextMap();
1326                         if(nextMap != "")
1327                                 break;
1328
1329                         if(allowReset)
1330                         {
1331                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1332                                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1333                                 if(autocvar_g_maplist_shuffle)
1334                                         ShuffleMaplist();
1335                                 localcmd("\nmenu_cmd sync\n");
1336                         }
1337                         else
1338                         {
1339                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1340                         }
1341                 }
1342                 Map_Goto(reinit);
1343         }
1344 }
1345
1346
1347 /*
1348 ============
1349 IntermissionThink
1350
1351 When the player presses attack or jump, change to the next level
1352 ============
1353 */
1354 .float autoscreenshot;
1355 void() MapVote_Start;
1356 void() MapVote_Think;
1357 float mapvote_initialized;
1358 void IntermissionThink()
1359 {
1360         FixIntermissionClient(self);
1361
1362         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1363         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1364
1365         if( (server_screenshot || client_screenshot)
1366                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1367         {
1368                 self.autoscreenshot = -1;
1369                 if(clienttype(self) == CLIENTTYPE_REAL) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"", GetMapname(), strftime(FALSE, "%s"))); }
1370                 return;
1371         }
1372
1373         if (time < intermission_exittime)
1374                 return;
1375
1376         if(!mapvote_initialized)
1377                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1378                         return;
1379
1380         MapVote_Start();
1381 }
1382
1383 /*
1384 ============
1385 FindIntermission
1386
1387 Returns the entity to view from
1388 ============
1389 */
1390 /*
1391 entity FindIntermission()
1392 {
1393         local   entity spot;
1394         local   float cyc;
1395
1396 // look for info_intermission first
1397         spot = find (world, classname, "info_intermission");
1398         if (spot)
1399         {       // pick a random one
1400                 cyc = random() * 4;
1401                 while (cyc > 1)
1402                 {
1403                         spot = find (spot, classname, "info_intermission");
1404                         if (!spot)
1405                                 spot = find (spot, classname, "info_intermission");
1406                         cyc = cyc - 1;
1407                 }
1408                 return spot;
1409         }
1410
1411 // then look for the start position
1412         spot = find (world, classname, "info_player_start");
1413         if (spot)
1414                 return spot;
1415
1416 // testinfo_player_start is only found in regioned levels
1417         spot = find (world, classname, "testplayerstart");
1418         if (spot)
1419                 return spot;
1420
1421 // then look for the start position
1422         spot = find (world, classname, "info_player_deathmatch");
1423         if (spot)
1424                 return spot;
1425
1426         //objerror ("FindIntermission: no spot");
1427         return world;
1428 }
1429 */
1430
1431 /*
1432 ===============================================================================
1433
1434 RULES
1435
1436 ===============================================================================
1437 */
1438
1439 void DumpStats(float final)
1440 {
1441         float file;
1442         string s;
1443         float to_console;
1444         float to_eventlog;
1445         float to_file;
1446         float i;
1447
1448         to_console = autocvar_sv_logscores_console;
1449         to_eventlog = autocvar_sv_eventlog;
1450         to_file = autocvar_sv_logscores_file;
1451
1452         if(!final)
1453         {
1454                 to_console = TRUE; // always print printstats replies
1455                 to_eventlog = FALSE; // but never print them to the event log
1456         }
1457
1458         if(to_eventlog)
1459                 if(autocvar_sv_eventlog_console)
1460                         to_console = FALSE; // otherwise we get the output twice
1461
1462         if(final)
1463                 s = ":scores:";
1464         else
1465                 s = ":status:";
1466         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1467
1468         if(to_console)
1469                 print(s, "\n");
1470         if(to_eventlog)
1471                 GameLogEcho(s);
1472
1473         file = -1;
1474         if(to_file)
1475         {
1476                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1477                 if(file == -1)
1478                         to_file = FALSE;
1479                 else
1480                         fputs(file, strcat(s, "\n"));
1481         }
1482
1483         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1484         if(to_console)
1485                 print(s, "\n");
1486         if(to_eventlog)
1487                 GameLogEcho(s);
1488         if(to_file)
1489                 fputs(file, strcat(s, "\n"));
1490
1491         FOR_EACH_CLIENT(other)
1492         {
1493                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && autocvar_sv_logscores_bots))
1494                 {
1495                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1496                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1497                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1498                                 s = strcat(s, ftos(other.team), ":");
1499                         else
1500                                 s = strcat(s, "spectator:");
1501
1502                         if(to_console)
1503                                 print(s, other.netname, "\n");
1504                         if(to_eventlog)
1505                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1506                         if(to_file)
1507                                 fputs(file, strcat(s, other.netname, "\n"));
1508                 }
1509         }
1510
1511         if(teamplay)
1512         {
1513                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1514                 if(to_console)
1515                         print(s, "\n");
1516                 if(to_eventlog)
1517                         GameLogEcho(s);
1518                 if(to_file)
1519                         fputs(file, strcat(s, "\n"));
1520
1521                 for(i = 1; i < 16; ++i)
1522                 {
1523                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1524                         s = strcat(s, ":", ftos(i));
1525                         if(to_console)
1526                                 print(s, "\n");
1527                         if(to_eventlog)
1528                                 GameLogEcho(s);
1529                         if(to_file)
1530                                 fputs(file, strcat(s, "\n"));
1531                 }
1532         }
1533
1534         if(to_console)
1535                 print(":end\n");
1536         if(to_eventlog)
1537                 GameLogEcho(":end");
1538         if(to_file)
1539         {
1540                 fputs(file, ":end\n");
1541                 fclose(file);
1542         }
1543 }
1544
1545 void FixIntermissionClient(entity e)
1546 {
1547         string s;
1548         if(!e.autoscreenshot) // initial call
1549         {
1550                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1551                 e.health = -2342;
1552                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1553                 e.solid = SOLID_NOT;
1554                 e.movetype = MOVETYPE_NONE;
1555                 e.takedamage = DAMAGE_NO;
1556                 if(e.weaponentity)
1557                 {
1558                         e.weaponentity.effects = EF_NODRAW;
1559                         if (e.weaponentity.weaponentity)
1560                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1561                 }
1562                 if(clienttype(e) == CLIENTTYPE_REAL)
1563                 {
1564                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1565                         s = autocvar_sv_intermission_cdtrack;
1566                         if(s != "")
1567                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1568                         msg_entity = e;
1569                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1570                 }
1571         }
1572 }
1573
1574 void minstagib_stop_countdown(entity e);
1575 /*
1576 go to the next level for deathmatch
1577 only called if a time or frag limit has expired
1578 */
1579 void NextLevel()
1580 {
1581         gameover = TRUE;
1582
1583         intermission_running = 1;
1584
1585 // enforce a wait time before allowing changelevel
1586         if(player_count > 0)
1587                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1588         else
1589                 intermission_exittime = -1;
1590
1591         /*
1592         WriteByte (MSG_ALL, SVC_CDTRACK);
1593         WriteByte (MSG_ALL, 3);
1594         WriteByte (MSG_ALL, 3);
1595         // done in FixIntermission
1596         */
1597
1598         //pos = FindIntermission ();
1599
1600         VoteReset();
1601
1602         DumpStats(TRUE);
1603
1604         // send statistics
1605         entity e;
1606         PlayerStats_EndMatch(1);
1607         FOR_EACH_CLIENT(e)
1608                 PlayerStats_AddGlobalInfo(e);
1609         PlayerStats_Shutdown();
1610         WeaponStats_Shutdown();
1611
1612         Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1613
1614         if(autocvar_sv_eventlog)
1615                 GameLogEcho(":gameover");
1616
1617         GameLogClose();
1618
1619         FOR_EACH_PLAYER(other) {
1620                 minstagib_stop_countdown(other);
1621                 FixIntermissionClient(other);
1622                 if(other.winning)
1623                         bprint(other.netname, " ^7wins.\n");
1624         }
1625
1626         if(autocvar_g_campaign)
1627                 CampaignPreIntermission();
1628
1629         MUTATOR_CALLHOOK(MatchEnd);
1630
1631         localcmd("\nsv_hook_gameend\n");
1632 }
1633
1634 /*
1635 ============
1636 CheckRules_Player
1637
1638 Exit deathmatch games upon conditions
1639 ============
1640 */
1641 void CheckRules_Player()
1642 {
1643         if (gameover)   // someone else quit the game already
1644                 return;
1645
1646         if(self.deadflag == DEAD_NO)
1647                 self.play_time += frametime;
1648
1649         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1650         //   (div0: and that in CheckRules_World please)
1651 }
1652
1653 float checkrules_equality;
1654 float checkrules_suddendeathwarning;
1655 float checkrules_suddendeathend;
1656 float checkrules_overtimesadded; //how many overtimes have been already added
1657
1658 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1659 float WINNING_YES = 1; // winner found
1660 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1661 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1662
1663 float InitiateSuddenDeath()
1664 {
1665         // Check first whether normal overtimes could be added before initiating suddendeath mode
1666         // - for this timelimit_overtime needs to be >0 of course
1667         // - also check the winning condition calculated in the previous frame and only add normal overtime
1668         //   again, if at the point at which timelimit would be extended again, still no winner was found
1669         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1670         {
1671                 return 1; // need to call InitiateOvertime later
1672         }
1673         else
1674         {
1675                 if(!checkrules_suddendeathend)
1676                 {
1677                         if(autocvar_g_campaign)
1678                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1679                         else
1680                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1681                         if(g_race && !g_race_qualifying)
1682                                 race_StartCompleting();
1683                 }
1684                 return 0;
1685         }
1686 }
1687
1688 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1689 {
1690         ++checkrules_overtimesadded;
1691         //add one more overtime by simply extending the timelimit
1692         float tl;
1693         tl = autocvar_timelimit;
1694         tl += autocvar_timelimit_overtime;
1695         cvar_set("timelimit", ftos(tl));
1696
1697         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime);
1698 }
1699
1700 float GetWinningCode(float fraglimitreached, float equality)
1701 {
1702         if(autocvar_g_campaign == 1)
1703                 if(fraglimitreached)
1704                         return WINNING_YES;
1705                 else
1706                         return WINNING_NO;
1707
1708         else
1709                 if(equality)
1710                         if(fraglimitreached)
1711                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1712                         else
1713                                 return WINNING_NEVER;
1714                 else
1715                         if(fraglimitreached)
1716                                 return WINNING_YES;
1717                         else
1718                                 return WINNING_NO;
1719 }
1720
1721 // set the .winning flag for exactly those players with a given field value
1722 void SetWinners(.float field, float value)
1723 {
1724         entity head;
1725         FOR_EACH_PLAYER(head)
1726                 head.winning = (head.field == value);
1727 }
1728
1729 // set the .winning flag for those players with a given field value
1730 void AddWinners(.float field, float value)
1731 {
1732         entity head;
1733         FOR_EACH_PLAYER(head)
1734                 if(head.field == value)
1735                         head.winning = 1;
1736 }
1737
1738 // clear the .winning flags
1739 void ClearWinners(void)
1740 {
1741         entity head;
1742         FOR_EACH_PLAYER(head)
1743                 head.winning = 0;
1744 }
1745
1746 // Onslaught winning condition:
1747 // game terminates if only one team has a working generator (or none)
1748 float WinningCondition_Onslaught()
1749 {
1750         entity head;
1751         float t1, t2, t3, t4;
1752
1753         WinningConditionHelper(); // set worldstatus
1754
1755         if(inWarmupStage)
1756                 return WINNING_NO;
1757
1758         // first check if the game has ended
1759         t1 = t2 = t3 = t4 = 0;
1760         head = find(world, classname, "onslaught_generator");
1761         while (head)
1762         {
1763                 if (head.health > 0)
1764                 {
1765                         if (head.team == NUM_TEAM_1) t1 = 1;
1766                         if (head.team == NUM_TEAM_2) t2 = 1;
1767                         if (head.team == NUM_TEAM_3) t3 = 1;
1768                         if (head.team == NUM_TEAM_4) t4 = 1;
1769                 }
1770                 head = find(head, classname, "onslaught_generator");
1771         }
1772         if (t1 + t2 + t3 + t4 < 2)
1773         {
1774                 // game over, only one team remains (or none)
1775                 ClearWinners();
1776                 if (t1) SetWinners(team, NUM_TEAM_1);
1777                 if (t2) SetWinners(team, NUM_TEAM_2);
1778                 if (t3) SetWinners(team, NUM_TEAM_3);
1779                 if (t4) SetWinners(team, NUM_TEAM_4);
1780                 dprint("Have a winner, ending game.\n");
1781                 return WINNING_YES;
1782         }
1783
1784         // Two or more teams remain
1785         return WINNING_NO;
1786 }
1787
1788 float LMS_NewPlayerLives()
1789 {
1790         float fl;
1791         fl = autocvar_fraglimit;
1792         if(fl == 0)
1793                 fl = 999;
1794
1795         // first player has left the game for dying too much? Nobody else can get in.
1796         if(lms_lowest_lives < 1)
1797                 return 0;
1798
1799         if(!autocvar_g_lms_join_anytime)
1800                 if(lms_lowest_lives < fl - autocvar_g_lms_last_join)
1801                         return 0;
1802
1803         return bound(1, lms_lowest_lives, fl);
1804 }
1805
1806 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1807 // they win. Otherwise the defending team wins once the timelimit passes.
1808 void assault_new_round();
1809 float WinningCondition_Assault()
1810 {
1811         float status;
1812
1813         WinningConditionHelper(); // set worldstatus
1814
1815         status = WINNING_NO;
1816         // as the timelimit has not yet passed just assume the defending team will win
1817         if(assault_attacker_team == NUM_TEAM_1)
1818         {
1819                 SetWinners(team, NUM_TEAM_2);
1820         }
1821         else
1822         {
1823                 SetWinners(team, NUM_TEAM_1);
1824         }
1825
1826         entity ent;
1827         ent = find(world, classname, "target_assault_roundend");
1828         if(ent)
1829         {
1830                 if(ent.winning) // round end has been triggered by attacking team
1831                 {
1832                         bprint("ASSAULT: round completed...\n");
1833                         SetWinners(team, assault_attacker_team);
1834
1835                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1836
1837                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1838                         {
1839                                 status = WINNING_YES;
1840                         }
1841                         else
1842                         {
1843                                 entity oldself;
1844                                 oldself = self;
1845                                 self = ent;
1846                                 assault_new_round();
1847                                 self = oldself;
1848                         }
1849                 }
1850         }
1851
1852         return status;
1853 }
1854
1855 // LMS winning condition: game terminates if and only if there's at most one
1856 // one player who's living lives. Top two scores being equal cancels the time
1857 // limit.
1858 float WinningCondition_LMS()
1859 {
1860         entity head, head2;
1861         float have_player;
1862         float have_players;
1863         float l;
1864
1865         have_player = FALSE;
1866         have_players = FALSE;
1867         l = LMS_NewPlayerLives();
1868
1869         head = find(world, classname, "player");
1870         if(head)
1871                 have_player = TRUE;
1872         head2 = find(head, classname, "player");
1873         if(head2)
1874                 have_players = TRUE;
1875
1876         if(have_player)
1877         {
1878                 // we have at least one player
1879                 if(have_players)
1880                 {
1881                         // two or more active players - continue with the game
1882                 }
1883                 else
1884                 {
1885                         // exactly one player?
1886
1887                         ClearWinners();
1888                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1889
1890                         if(l)
1891                         {
1892                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1893                                 return WINNING_NO;
1894                         }
1895                         else
1896                         {
1897                                 // a winner!
1898                                 // and assign him his first place
1899                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1900                                 return WINNING_YES;
1901                         }
1902                 }
1903         }
1904         else
1905         {
1906                 // nobody is playing at all...
1907                 if(l)
1908                 {
1909                         // wait for players...
1910                 }
1911                 else
1912                 {
1913                         // SNAFU (maybe a draw game?)
1914                         ClearWinners();
1915                         dprint("No players, ending game.\n");
1916                         return WINNING_YES;
1917                 }
1918         }
1919
1920         // When we get here, we have at least two players who are actually LIVING,
1921         // now check if the top two players have equal score.
1922         WinningConditionHelper();
1923
1924         ClearWinners();
1925         if(WinningConditionHelper_winner)
1926                 WinningConditionHelper_winner.winning = TRUE;
1927         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1928                 return WINNING_NEVER;
1929
1930         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1931         return WINNING_NO;
1932 }
1933
1934 void ShuffleMaplist()
1935 {
1936         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1937 }
1938
1939 float leaderfrags;
1940 float WinningCondition_Scores(float limit, float leadlimit)
1941 {
1942         float limitreached;
1943
1944         // TODO make everything use THIS winning condition (except LMS)
1945         WinningConditionHelper();
1946
1947         if(teamplay)
1948         {
1949                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1950                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1951                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1952                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1953         }
1954
1955         ClearWinners();
1956         if(WinningConditionHelper_winner)
1957                 WinningConditionHelper_winner.winning = 1;
1958         if(WinningConditionHelper_winnerteam >= 0)
1959                 SetWinners(team, WinningConditionHelper_winnerteam);
1960
1961         if(WinningConditionHelper_lowerisbetter)
1962         {
1963                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1964                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1965                 limit = -limit;
1966         }
1967
1968         if(WinningConditionHelper_zeroisworst)
1969                 leadlimit = 0; // not supported in this mode
1970
1971         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1972         // these modes always score in increments of 1, thus this makes sense
1973         {
1974                 if(leaderfrags != WinningConditionHelper_topscore)
1975                 {
1976                         leaderfrags = WinningConditionHelper_topscore;
1977
1978                         if (limit)
1979                         if (leaderfrags == limit - 1)
1980                                 Announce("1fragleft");
1981                         else if (leaderfrags == limit - 2)
1982                                 Announce("2fragsleft");
1983                         else if (leaderfrags == limit - 3)
1984                                 Announce("3fragsleft");
1985                 }
1986         }
1987
1988         limitreached = FALSE;
1989         if(limit)
1990                 if(WinningConditionHelper_topscore >= limit)
1991                         limitreached = TRUE;
1992         if(leadlimit)
1993         {
1994                 float leadlimitreached;
1995                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1996                 if(autocvar_leadlimit_and_fraglimit)
1997                         limitreached = (limitreached && leadlimitreached);
1998                 else
1999                         limitreached = (limitreached || leadlimitreached);
2000         }
2001
2002         if(limit)
2003                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
2004
2005         return GetWinningCode(
2006                 WinningConditionHelper_topscore && limitreached,
2007                 WinningConditionHelper_equality
2008         );
2009 }
2010
2011 float WinningCondition_Race(float fraglimit)
2012 {
2013         float wc;
2014         entity p;
2015         float n, c;
2016
2017         n = 0;
2018         c = 0;
2019         FOR_EACH_PLAYER(p)
2020         {
2021                 ++n;
2022                 if(p.race_completed)
2023                         ++c;
2024         }
2025         if(n && (n == c))
2026                 return WINNING_YES;
2027         wc = WinningCondition_Scores(fraglimit, 0);
2028
2029         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
2030         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2031         // do NOT support equality when the laps are all raced!
2032                 return WINNING_STARTSUDDENDEATHOVERTIME;
2033         else
2034                 return WINNING_NEVER;
2035 }
2036
2037 float WinningCondition_QualifyingThenRace(float limit)
2038 {
2039         float wc;
2040         wc = WinningCondition_Scores(limit, 0);
2041
2042         // NEVER initiate overtime
2043         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2044         {
2045                 return WINNING_YES;
2046         }
2047
2048         return wc;
2049 }
2050
2051 float WinningCondition_RanOutOfSpawns()
2052 {
2053         entity head;
2054
2055         if(have_team_spawns <= 0)
2056                 return WINNING_NO;
2057
2058         if(autocvar_g_spawn_useallspawns <= 0)
2059                 return WINNING_NO;
2060
2061         if(!some_spawn_has_been_used)
2062                 return WINNING_NO;
2063
2064         team1_score = team2_score = team3_score = team4_score = 0;
2065
2066         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
2067         {
2068                 if(head.team == NUM_TEAM_1)
2069                         team1_score = 1;
2070                 else if(head.team == NUM_TEAM_2)
2071                         team2_score = 1;
2072                 else if(head.team == NUM_TEAM_3)
2073                         team3_score = 1;
2074                 else if(head.team == NUM_TEAM_4)
2075                         team4_score = 1;
2076         }
2077
2078         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
2079         {
2080                 if(head.team == NUM_TEAM_1)
2081                         team1_score = 1;
2082                 else if(head.team == NUM_TEAM_2)
2083                         team2_score = 1;
2084                 else if(head.team == NUM_TEAM_3)
2085                         team3_score = 1;
2086                 else if(head.team == NUM_TEAM_4)
2087                         team4_score = 1;
2088         }
2089
2090         ClearWinners();
2091         if(team1_score + team2_score + team3_score + team4_score == 0)
2092         {
2093                 checkrules_equality = TRUE;
2094                 return WINNING_YES;
2095         }
2096         else if(team1_score + team2_score + team3_score + team4_score == 1)
2097         {
2098                 float t, i;
2099                 if(team1_score)
2100                         t = NUM_TEAM_1;
2101                 else if(team2_score)
2102                         t = NUM_TEAM_2;
2103                 else if(team3_score)
2104                         t = NUM_TEAM_3;
2105                 else // if(team4_score)
2106                         t = NUM_TEAM_4;
2107                 CheckAllowedTeams(world);
2108                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2109                 {
2110                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
2111                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
2112                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
2113                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
2114                 }
2115
2116                 AddWinners(team, t);
2117                 return WINNING_YES;
2118         }
2119         else
2120                 return WINNING_NO;
2121 }
2122
2123 /*
2124 ============
2125 CheckRules_World
2126
2127 Exit deathmatch games upon conditions
2128 ============
2129 */
2130 void ReadyRestart();
2131 void CheckRules_World()
2132 {
2133         float timelimit;
2134         float fraglimit;
2135         float leadlimit;
2136
2137         VoteThink();
2138         MapVote_Think();
2139
2140         SetDefaultAlpha();
2141
2142         /*
2143         MapVote_Think should now do that part
2144         if (intermission_running)
2145                 if (time >= intermission_exittime + 60)
2146                 {
2147                         if(!DoNextMapOverride())
2148                                 GotoNextMap();
2149                         return;
2150                 }
2151         */
2152
2153         if (gameover)   // someone else quit the game already
2154         {
2155                 if(player_count == 0) // Nobody there? Then let's go to the next map
2156                         MapVote_Start();
2157                         // this will actually check the player count in the next frame
2158                         // again, but this shouldn't hurt
2159                 return;
2160         }
2161
2162         timelimit = autocvar_timelimit * 60;
2163         fraglimit = autocvar_fraglimit;
2164         leadlimit = autocvar_leadlimit;
2165
2166         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2167         {
2168                 if(timelimit > 0)
2169                         timelimit = 0; // timelimit is not made for warmup
2170                 if(fraglimit > 0)
2171                         fraglimit = 0; // no fraglimit for now
2172                 leadlimit = 0; // no leadlimit for now
2173         }
2174
2175         if(timelimit > 0)
2176         {
2177                 timelimit += game_starttime;
2178         }
2179         else if (timelimit < 0)
2180         {
2181                 // endmatch
2182                 NextLevel();
2183                 return;
2184         }
2185
2186         if(g_onslaught)
2187                 timelimit = 0; // ONS has its own overtime rule
2188
2189         float wantovertime;
2190         wantovertime = 0;
2191
2192         if(timelimit > game_starttime)
2193                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2194         else
2195                 game_completion_ratio = 0;
2196
2197         if(checkrules_suddendeathend)
2198         {
2199                 if(!checkrules_suddendeathwarning)
2200                 {
2201                         checkrules_suddendeathwarning = TRUE;
2202                         if(g_race && !g_race_qualifying)
2203                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_RACE_FINISHLAP);
2204                         else
2205                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_FRAG);
2206                 }
2207         }
2208         else
2209         {
2210                 if (timelimit && time >= timelimit)
2211                 {
2212                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2213                         {
2214                                 float totalplayers;
2215                                 float playerswithlaps;
2216                                 float readyplayers;
2217                                 entity head;
2218                                 totalplayers = playerswithlaps = readyplayers = 0;
2219                                 FOR_EACH_PLAYER(head)
2220                                 {
2221                                         ++totalplayers;
2222                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2223                                                 ++playerswithlaps;
2224                                         if(head.ready)
2225                                                 ++readyplayers;
2226                                 }
2227
2228                                 // at least 2 of the players have completed a lap: start the RACE
2229                                 // otherwise, the players should end the qualifying on their own
2230                                 if(readyplayers || playerswithlaps >= 2)
2231                                 {
2232                                         checkrules_suddendeathend = 0;
2233                                         ReadyRestart(); // go to race
2234                                         return;
2235                                 }
2236                                 else
2237                                         wantovertime |= InitiateSuddenDeath();
2238                         }
2239                         else
2240                                 wantovertime |= InitiateSuddenDeath();
2241                 }
2242         }
2243
2244         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2245         {
2246                 NextLevel();
2247                 return;
2248         }
2249
2250         float checkrules_status;
2251         checkrules_status = WinningCondition_RanOutOfSpawns();
2252         if(checkrules_status == WINNING_YES)
2253         {
2254                 bprint("Hey! Someone ran out of spawns!\n");
2255         }
2256         else if(g_race && !g_race_qualifying && timelimit >= 0)
2257         {
2258                 checkrules_status = WinningCondition_Race(fraglimit);
2259                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2260         }
2261         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2262         {
2263                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2264                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2265         }
2266         else if(g_assault)
2267         {
2268                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2269         }
2270         else if(g_lms)
2271         {
2272                 checkrules_status = WinningCondition_LMS();
2273         }
2274         else if (g_onslaught)
2275         {
2276                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2277         }
2278         else
2279         {
2280                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2281                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2282         }
2283
2284         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2285         {
2286                 checkrules_status = WINNING_NEVER;
2287                 checkrules_overtimesadded = -1;
2288                 wantovertime |= InitiateSuddenDeath();
2289         }
2290
2291         if(checkrules_status == WINNING_NEVER)
2292                 // equality cases! Nobody wins if the overtime ends in a draw.
2293                 ClearWinners();
2294
2295         if(wantovertime)
2296         {
2297                 if(checkrules_status == WINNING_NEVER)
2298                         InitiateOvertime();
2299                 else
2300                         checkrules_status = WINNING_YES;
2301         }
2302
2303         if(checkrules_suddendeathend)
2304                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2305                         checkrules_status = WINNING_YES;
2306
2307         if(checkrules_status == WINNING_YES)
2308         {
2309                 //print("WINNING\n");
2310                 NextLevel();
2311         }
2312 }
2313
2314 float mapvote_nextthink;
2315 float mapvote_initialized;
2316 float mapvote_keeptwotime;
2317 float mapvote_timeout;
2318 string mapvote_message;
2319 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2320 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2321 float mapvote_screenshot_dirs_count;
2322
2323 float mapvote_count;
2324 float mapvote_count_real;
2325 string mapvote_maps[MAPVOTE_COUNT];
2326 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2327 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2328 float mapvote_maps_suggested[MAPVOTE_COUNT];
2329 string mapvote_suggestions[MAPVOTE_COUNT];
2330 float mapvote_suggestion_ptr;
2331 float mapvote_voters;
2332 float mapvote_selections[MAPVOTE_COUNT];
2333 float mapvote_run;
2334 float mapvote_detail;
2335 float mapvote_abstain;
2336 .float mapvote;
2337
2338 void MapVote_ClearAllVotes()
2339 {
2340         FOR_EACH_CLIENT(other)
2341                 other.mapvote = 0;
2342 }
2343
2344 string MapVote_Suggest(string m)
2345 {
2346         float i;
2347         if(m == "")
2348                 return "That's not how to use this command.";
2349         if(!autocvar_g_maplist_votable_suggestions)
2350                 return "Suggestions are not accepted on this server.";
2351         if(mapvote_initialized)
2352                 return "Can't suggest - voting is already in progress!";
2353         m = MapInfo_FixName(m);
2354         if not(m)
2355                 return "The map you suggested is not available on this server.";
2356         if(!autocvar_g_maplist_votable_suggestions_override_mostrecent)
2357                 if(Map_IsRecent(m))
2358                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2359
2360         if(!MapInfo_CheckMap(m))
2361                 return "The map you suggested does not support the current game mode.";
2362         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2363                 if(mapvote_suggestions[i] == m)
2364                         return "This map was already suggested.";
2365         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2366         {
2367                 i = floor(random() * mapvote_suggestion_ptr);
2368         }
2369         else
2370         {
2371                 i = mapvote_suggestion_ptr;
2372                 mapvote_suggestion_ptr += 1;
2373         }
2374         if(mapvote_suggestions[i] != "")
2375                 strunzone(mapvote_suggestions[i]);
2376         mapvote_suggestions[i] = strzone(m);
2377         if(autocvar_sv_eventlog)
2378                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2379         return strcat("Suggestion of ", m, " accepted.");
2380 }
2381
2382 void MapVote_AddVotable(string nextMap, float isSuggestion)
2383 {
2384         float j, i, o;
2385         string pakfile, mapfile;
2386
2387         if(nextMap == "")
2388                 return;
2389         for(j = 0; j < mapvote_count; ++j)
2390                 if(mapvote_maps[j] == nextMap)
2391                         return;
2392         // suggestions might be no longer valid/allowed after gametype switch!
2393         if(isSuggestion)
2394                 if(!MapInfo_CheckMap(nextMap))
2395                         return;
2396         mapvote_maps[mapvote_count] = strzone(nextMap);
2397         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2398
2399         pakfile = string_null;
2400         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2401         {
2402                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2403                 pakfile = whichpack(strcat(mapfile, ".tga"));
2404                 if(pakfile == "")
2405                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2406                 if(pakfile == "")
2407                         pakfile = whichpack(strcat(mapfile, ".png"));
2408                 if(pakfile != "")
2409                         break;
2410         }
2411         if(i >= mapvote_screenshot_dirs_count)
2412                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2413         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2414                 pakfile = substring(pakfile, o, -1);
2415
2416         mapvote_maps_screenshot_dir[mapvote_count] = i;
2417         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2418
2419         mapvote_count += 1;
2420 }
2421
2422 void MapVote_Spawn();
2423 void MapVote_Init()
2424 {
2425         float i;
2426         float nmax, smax;
2427
2428         MapVote_ClearAllVotes();
2429
2430         mapvote_count = 0;
2431         mapvote_detail = !autocvar_g_maplist_votable_nodetail;
2432         mapvote_abstain = autocvar_g_maplist_votable_abstain;
2433
2434         if(mapvote_abstain)
2435                 nmax = min(MAPVOTE_COUNT - 1, autocvar_g_maplist_votable);
2436         else
2437                 nmax = min(MAPVOTE_COUNT, autocvar_g_maplist_votable);
2438         smax = min3(nmax, autocvar_g_maplist_votable_suggestions, mapvote_suggestion_ptr);
2439
2440         // we need this for AddVotable, as that cycles through the screenshot dirs
2441         mapvote_screenshot_dirs_count = tokenize_console(autocvar_g_maplist_votable_screenshot_dir);
2442         if(mapvote_screenshot_dirs_count == 0)
2443                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2444         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2445         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2446                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2447
2448         if(mapvote_suggestion_ptr)
2449                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2450                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2451
2452         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2453                 MapVote_AddVotable(GetNextMap(), FALSE);
2454
2455         if(mapvote_count == 0)
2456         {
2457                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2458                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2459                 if(autocvar_g_maplist_shuffle)
2460                         ShuffleMaplist();
2461                 localcmd("\nmenu_cmd sync\n");
2462                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2463                         MapVote_AddVotable(GetNextMap(), FALSE);
2464         }
2465
2466         mapvote_count_real = mapvote_count;
2467         if(mapvote_abstain)
2468                 MapVote_AddVotable("don't care", 0);
2469
2470         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2471
2472         mapvote_keeptwotime = time + autocvar_g_maplist_votable_keeptwotime;
2473         mapvote_timeout = time + autocvar_g_maplist_votable_timeout;
2474         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2475                 mapvote_keeptwotime = 0;
2476         mapvote_message = "Choose a map and press its key!";
2477
2478         MapVote_Spawn();
2479 }
2480
2481 void MapVote_SendPicture(float id)
2482 {
2483         msg_entity = self;
2484         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2485         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2486         WriteByte(MSG_ONE, id);
2487         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2488 }
2489
2490 float MapVote_GetMapMask()
2491 {
2492         float mask, i, power;
2493         mask = 0;
2494         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2495                 if(mapvote_maps[i] != "")
2496                         mask |= power;
2497         return mask;
2498 }
2499
2500 entity mapvote_ent;
2501 float MapVote_SendEntity(entity to, float sf)
2502 {
2503         float i;
2504
2505         if(sf & 1)
2506                 sf &~= 2; // if we send 1, we don't need to also send 2
2507
2508         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2509         WriteByte(MSG_ENTITY, sf);
2510
2511         if(sf & 1)
2512         {
2513                 // flag 1 == initialization
2514                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2515                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2516                 WriteString(MSG_ENTITY, "");
2517                 WriteByte(MSG_ENTITY, mapvote_count);
2518                 WriteByte(MSG_ENTITY, mapvote_abstain);
2519                 WriteByte(MSG_ENTITY, mapvote_detail);
2520                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2521                 if(mapvote_count <= 8)
2522                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2523                 else
2524                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2525                 for(i = 0; i < mapvote_count; ++i)
2526                         if(mapvote_maps[i] != "")
2527                         {
2528                                 if(mapvote_abstain && i == mapvote_count - 1)
2529                                 {
2530                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2531                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2532                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2533                                 }
2534                                 else
2535                                 {
2536                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2537                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2538                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2539                                 }
2540                         }
2541         }
2542
2543         if(sf & 2)
2544         {
2545                 // flag 2 == update of mask
2546                 if(mapvote_count <= 8)
2547                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2548                 else
2549                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2550         }
2551
2552         if(sf & 4)
2553         {
2554                 if(mapvote_detail)
2555                         for(i = 0; i < mapvote_count; ++i)
2556                                 if(mapvote_maps[i] != "")
2557                                         WriteByte(MSG_ENTITY, mapvote_selections[i]);
2558
2559                 WriteByte(MSG_ENTITY, to.mapvote);
2560         }
2561
2562         return TRUE;
2563 }
2564
2565 void MapVote_Spawn()
2566 {
2567         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2568 }
2569
2570 void MapVote_TouchMask()
2571 {
2572         mapvote_ent.SendFlags |= 2;
2573 }
2574
2575 void MapVote_TouchVotes(entity voter)
2576 {
2577         mapvote_ent.SendFlags |= 4;
2578 }
2579
2580 float MapVote_Finished(float mappos)
2581 {
2582         string result;
2583         float i;
2584         float didntvote;
2585
2586         if(autocvar_sv_eventlog)
2587         {
2588                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2589                 result = strcat(result, ":", ftos(mapvote_selections[mappos]), "::");
2590                 didntvote = mapvote_voters;
2591                 for(i = 0; i < mapvote_count; ++i)
2592                         if(mapvote_maps[i] != "")
2593                         {
2594                                 didntvote -= mapvote_selections[i];
2595                                 if(i != mappos)
2596                                 {
2597                                         result = strcat(result, ":", mapvote_maps[i]);
2598                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2599                                 }
2600                         }
2601                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2602
2603                 GameLogEcho(result);
2604                 if(mapvote_maps_suggested[mappos])
2605                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2606         }
2607
2608         FOR_EACH_REALCLIENT(other)
2609                 FixClientCvars(other);
2610
2611         Map_Goto_SetStr(mapvote_maps[mappos]);
2612         Map_Goto(0);
2613         alreadychangedlevel = TRUE;
2614         return TRUE;
2615 }
2616 void MapVote_CheckRules_1()
2617 {
2618         float i;
2619
2620         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2621         {
2622                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2623                 mapvote_selections[i] = 0;
2624         }
2625
2626         mapvote_voters = 0;
2627         FOR_EACH_REALCLIENT(other)
2628         {
2629                 ++mapvote_voters;
2630                 if(other.mapvote)
2631                 {
2632                         i = other.mapvote - 1;
2633                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2634                         mapvote_selections[i] = mapvote_selections[i] + 1;
2635                 }
2636         }
2637 }
2638
2639 float MapVote_CheckRules_2()
2640 {
2641         float i;
2642         float firstPlace, secondPlace;
2643         float firstPlaceVotes, secondPlaceVotes;
2644         float mapvote_voters_real;
2645         string result;
2646
2647         if(mapvote_count_real == 1)
2648                 return MapVote_Finished(0);
2649
2650         mapvote_voters_real = mapvote_voters;
2651         if(mapvote_abstain)
2652                 mapvote_voters_real -= mapvote_selections[mapvote_count - 1];
2653
2654         RandomSelection_Init();
2655         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2656                 RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2657         firstPlace = RandomSelection_chosen_float;
2658         firstPlaceVotes = RandomSelection_best_priority;
2659         //dprint("First place: ", ftos(firstPlace), "\n");
2660         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2661
2662         RandomSelection_Init();
2663         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2664                 if(i != firstPlace)
2665                         RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2666         secondPlace = RandomSelection_chosen_float;
2667         secondPlaceVotes = RandomSelection_best_priority;
2668         //dprint("Second place: ", ftos(secondPlace), "\n");
2669         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2670
2671         if(firstPlace == -1)
2672                 error("No first place in map vote... WTF?");
2673
2674         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2675                 return MapVote_Finished(firstPlace);
2676
2677         if(mapvote_keeptwotime)
2678                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2679                 {
2680                         float didntvote;
2681                         MapVote_TouchMask();
2682                         mapvote_message = "Now decide between the TOP TWO!";
2683                         mapvote_keeptwotime = 0;
2684                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2685                         result = strcat(result, ":", ftos(firstPlaceVotes));
2686                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2687                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2688                         didntvote = mapvote_voters;
2689                         for(i = 0; i < mapvote_count; ++i)
2690                                 if(mapvote_maps[i] != "")
2691                                 {
2692                                         didntvote -= mapvote_selections[i];
2693                                         if(i != firstPlace)
2694                                                 if(i != secondPlace)
2695                                                 {
2696                                                         result = strcat(result, ":", mapvote_maps[i]);
2697                                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2698                                                         if(i < mapvote_count_real)
2699                                                         {
2700                                                                 strunzone(mapvote_maps[i]);
2701                                                                 mapvote_maps[i] = "";
2702                                                                 strunzone(mapvote_maps_pakfile[i]);
2703                                                                 mapvote_maps_pakfile[i] = "";
2704                                                         }
2705                                                 }
2706                                 }
2707                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2708                         if(autocvar_sv_eventlog)
2709                                 GameLogEcho(result);
2710                 }
2711
2712         return FALSE;
2713 }
2714 void MapVote_Tick()
2715 {
2716         float keeptwo;
2717         float totalvotes;
2718
2719         keeptwo = mapvote_keeptwotime;
2720         MapVote_CheckRules_1(); // count
2721         if(MapVote_CheckRules_2()) // decide
2722                 return;
2723
2724         totalvotes = 0;
2725         FOR_EACH_REALCLIENT(other)
2726         {
2727                 // hide scoreboard again
2728                 if(other.health != 2342)
2729                 {
2730                         other.health = 2342;
2731                         other.impulse = 0;
2732                         if(clienttype(other) == CLIENTTYPE_REAL)
2733                         {
2734                                 msg_entity = other;
2735                                 WriteByte(MSG_ONE, SVC_FINALE);
2736                                 WriteString(MSG_ONE, "");
2737                         }
2738                 }
2739
2740                 // clear possibly invalid votes
2741                 if(mapvote_maps[other.mapvote - 1] == "")
2742                         other.mapvote = 0;
2743                 // use impulses as new vote
2744                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2745                         if(mapvote_maps[other.impulse - 1] != "")
2746                         {
2747                                 other.mapvote = other.impulse;
2748                                 MapVote_TouchVotes(other);
2749                         }
2750                 other.impulse = 0;
2751
2752                 if(other.mapvote)
2753                         ++totalvotes;
2754         }
2755
2756         MapVote_CheckRules_1(); // just count
2757 }
2758 void MapVote_Start()
2759 {
2760         if(mapvote_run)
2761                 return;
2762
2763         // wait for stats to be sent first
2764         if(!playerstats_waitforme)
2765                 return;
2766
2767         MapInfo_Enumerate();
2768         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2769                 mapvote_run = TRUE;
2770 }
2771 void MapVote_Think()
2772 {
2773         if(!mapvote_run)
2774                 return;
2775
2776         if(alreadychangedlevel)
2777                 return;
2778
2779         if(time < mapvote_nextthink)
2780                 return;
2781         //dprint("tick\n");
2782
2783         mapvote_nextthink = time + 0.5;
2784
2785         if(!mapvote_initialized)
2786         {
2787                 if(autocvar_rescan_pending == 1)
2788                 {
2789                         cvar_set("rescan_pending", "2");
2790                         localcmd("fs_rescan\nrescan_pending 3\n");
2791                         return;
2792                 }
2793                 else if(autocvar_rescan_pending == 2)
2794                 {
2795                         return;
2796                 }
2797                 else if(autocvar_rescan_pending == 3)
2798                 {
2799                         // now build missing mapinfo files
2800                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2801                                 return;
2802
2803                         // we're done, start the timer
2804                         cvar_set("rescan_pending", "0");
2805                 }
2806
2807                 mapvote_initialized = TRUE;
2808                 if(DoNextMapOverride(0))
2809                         return;
2810                 if(!autocvar_g_maplist_votable || player_count <= 0)
2811                 {
2812                         GotoNextMap(0);
2813                         return;
2814                 }
2815                 MapVote_Init();
2816         }
2817
2818         MapVote_Tick();
2819 }
2820
2821 string GotoMap(string m)
2822 {
2823         if(!MapInfo_CheckMap(m))
2824                 return "The map you chose is not available on this server.";
2825         cvar_set("nextmap", m);
2826         cvar_set("timelimit", "-1");
2827         if(mapvote_initialized || alreadychangedlevel)
2828         {
2829                 if(DoNextMapOverride(0))
2830                         return "Map switch initiated.";
2831                 else
2832                         return "Hm... no. For some reason I like THIS map more.";
2833         }
2834         else
2835                 return "Map switch will happen after scoreboard.";
2836 }
2837
2838
2839 void EndFrame()
2840 {
2841         float altime;
2842         FOR_EACH_REALCLIENT(self)
2843         {
2844                 if(self.classname == "spectator")
2845                 {
2846                         if(self.enemy.typehitsound)
2847                                 self.typehit_time = time;
2848                         else if(self.enemy.hitsound)
2849                                 self.hit_time = time;
2850                 }
2851                 else
2852                 {
2853                         if(self.typehitsound)
2854                                 self.typehit_time = time;
2855                         else if(self.hitsound)
2856                                 self.hit_time = time;
2857                 }
2858         }
2859         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2860         // add 1 frametime because after this, engine SV_Physics
2861         // increases time by a frametime and then networks the frame
2862         // add another frametime because client shows everything with
2863         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2864         // needed!
2865         FOR_EACH_CLIENT(self)
2866         {
2867                 self.hitsound = FALSE;
2868                 self.typehitsound = FALSE;
2869                 antilag_record(self, altime);
2870         }
2871 }
2872
2873
2874 /*
2875  * RedirectionThink:
2876  * returns TRUE if redirecting
2877  */
2878 float redirection_timeout;
2879 float redirection_nextthink;
2880 float RedirectionThink()
2881 {
2882         float clients_found;
2883
2884         if(redirection_target == "")
2885                 return FALSE;
2886
2887         if(!redirection_timeout)
2888         {
2889                 cvar_set("sv_public", "-2");
2890                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2891                 if(redirection_target == "self")
2892                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2893                 else
2894                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2895         }
2896
2897         if(time < redirection_nextthink)
2898                 return TRUE;
2899
2900         redirection_nextthink = time + 1;
2901
2902         clients_found = 0;
2903         FOR_EACH_REALCLIENT(self)
2904         {
2905                 // TODO add timer
2906                 print("Redirecting: sending connect command to ", self.netname, "\n");
2907                 if(redirection_target == "self")
2908                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2909                 else
2910                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2911                 ++clients_found;
2912         }
2913
2914         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2915
2916         if(time > redirection_timeout || clients_found == 0)
2917                 localcmd("\nwait; wait; wait; quit\n");
2918
2919         return TRUE;
2920 }
2921
2922 void TargetMusic_RestoreGame();
2923 void RestoreGame()
2924 {
2925         // Loaded from a save game
2926         // some things then break, so let's work around them...
2927
2928         // Progs DB (capture records)
2929         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2930
2931         // Mapinfo
2932         MapInfo_Shutdown();
2933         MapInfo_Enumerate();
2934         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2935         WeaponStats_Init();
2936
2937         TargetMusic_RestoreGame();
2938 }
2939
2940 void Shutdown()
2941 {
2942         entity e;
2943
2944         gameover = 2;
2945
2946         if(world_initialized > 0)
2947         {
2948                 world_initialized = 0;
2949                 print("Saving persistent data...\n");
2950                 Ban_SaveBans();
2951
2952                 PlayerStats_EndMatch(0);
2953                 FOR_EACH_CLIENT(e)
2954                         PlayerStats_AddGlobalInfo(e);
2955                 PlayerStats_Shutdown();
2956
2957                 if(!cheatcount_total)
2958                 {
2959                         if(autocvar_sv_db_saveasdump)
2960                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2961                         else
2962                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2963                 }
2964                 if(autocvar_developer)
2965                 {
2966                         if(autocvar_sv_db_saveasdump)
2967                                 db_dump(TemporaryDB, "server-temp.db");
2968                         else
2969                                 db_save(TemporaryDB, "server-temp.db");
2970                 }
2971                 CheatShutdown(); // must be after cheatcount check
2972                 db_close(ServerProgsDB);
2973                 db_close(TemporaryDB);
2974                 print("done!\n");
2975                 // tell the bot system the game is ending now
2976                 bot_endgame();
2977
2978                 WeaponStats_Shutdown();
2979                 MapInfo_Shutdown();
2980         }
2981         else if(world_initialized == 0)
2982         {
2983                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2984         }
2985 }