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