]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
8649c07a6b25d4a8449aef37e8794cd67f89bb13
[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
555         MapInfo_Enumerate();
556         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
557 }
558
559 void Map_MarkAsRecent(string m);
560 float world_already_spawned;
561 void Nagger_Init();
562 void ClientInit_Spawn();
563 void WeaponStats_Init();
564 void WeaponStats_Shutdown();
565 void spawnfunc_worldspawn (void)
566 {
567         float fd, l, i, j, n;
568         string s, col;
569
570         cvar = cvar_normal;
571         cvar_string = cvar_string_normal;
572         cvar_set = cvar_set_normal;
573
574         if(world_already_spawned)
575                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
576         world_already_spawned = TRUE;
577
578         remove = remove_safely; // during spawning, watch what you remove!
579
580         check_unacceptable_compiler_bugs();
581
582         cvar_changes_init(); // do this very early now so it REALLY matches the server config
583
584         compressShortVector_init();
585
586         allowed_to_spawn = TRUE;
587
588         entity head;
589         head = nextent(world);
590         maxclients = 0;
591         while(head)
592         {
593                 ++maxclients;
594                 head = nextent(head);
595         }
596
597         // needs to be done so early because of the constants they create
598         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
599         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
600
601         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
602
603         TemporaryDB = db_create();
604
605         // 0 normal
606         lightstyle(0, "m");
607
608         // 1 FLICKER (first variety)
609         lightstyle(1, "mmnmmommommnonmmonqnmmo");
610
611         // 2 SLOW STRONG PULSE
612         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
613
614         // 3 CANDLE (first variety)
615         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
616
617         // 4 FAST STROBE
618         lightstyle(4, "mamamamamama");
619
620         // 5 GENTLE PULSE 1
621         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
622
623         // 6 FLICKER (second variety)
624         lightstyle(6, "nmonqnmomnmomomno");
625
626         // 7 CANDLE (second variety)
627         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
628
629         // 8 CANDLE (third variety)
630         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
631
632         // 9 SLOW STROBE (fourth variety)
633         lightstyle(9, "aaaaaaaazzzzzzzz");
634
635         // 10 FLUORESCENT FLICKER
636         lightstyle(10, "mmamammmmammamamaaamammma");
637
638         // 11 SLOW PULSE NOT FADE TO BLACK
639         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
640
641         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
642
643         // 63 testing
644         lightstyle(63, "a");
645
646         if(autocvar_g_campaign)
647                 CampaignPreInit();
648
649         Map_MarkAsRecent(mapname);
650
651         PlayerStats_Init(); // we need this to be initiated before InitGameplayMode
652
653         precache_model ("null"); // we need this one before InitGameplayMode
654         InitGameplayMode();
655         readlevelcvars();
656         GrappleHookInit();
657         ElectroInit();
658         LaserInit();
659
660         player_count = 0;
661         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
662         if(bot_waypoints_for_items == 1)
663                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
664                         bot_waypoints_for_items = 0;
665
666         precache();
667
668         WaypointSprite_Init();
669
670         GameLogInit(); // prepare everything
671         // NOTE for matchid:
672         // changing the logic generating it is okay. But:
673         // it HAS to stay <= 64 chars
674         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
675         if(autocvar_sv_eventlog)
676         {
677                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
678                 matchid = strzone(s);
679
680                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
681                 s = ":gameinfo:mutators:LIST";
682
683                 ret_string = s;
684                 MUTATOR_CALLHOOK(BuildMutatorsString);
685                 s = ret_string;
686
687                 // simple, probably not good in the mutator system
688                 if(autocvar_g_grappling_hook)
689                         s = strcat(s, ":grappling_hook");
690
691                 // initialiation stuff, not good in the mutator system
692                 if(!autocvar_g_use_ammunition)
693                         s = strcat(s, ":no_use_ammunition");
694
695                 // initialiation stuff, not good in the mutator system
696                 if(autocvar_g_pickup_items == 0)
697                         s = strcat(s, ":no_pickup_items");
698                 if(autocvar_g_pickup_items > 0)
699                         s = strcat(s, ":pickup_items");
700
701                 // initialiation stuff, not good in the mutator system
702                 if(autocvar_g_weaponarena != "0")
703                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
704
705                 // TODO to mutator system
706                 if(autocvar_g_norecoil)
707                         s = strcat(s, ":norecoil");
708
709                 // TODO to mutator system
710                 if(autocvar_g_midair)
711                         s = strcat(s, ":midair");
712
713                 // TODO to mutator system
714                 if(autocvar_g_minstagib)
715                         s = strcat(s, ":minstagib");
716
717                 // TODO to mutator system
718                 if(autocvar_g_powerups == 0)
719                         s = strcat(s, ":no_powerups");
720                 if(autocvar_g_powerups > 0)
721                         s = strcat(s, ":powerups");
722
723                 GameLogEcho(s);
724                 GameLogEcho(":gameinfo:end");
725         }
726         else
727                 matchid = strzone(ftos(random()));
728
729         cvar_set("nextmap", "");
730
731         SetDefaultAlpha();
732
733         if(autocvar_g_campaign)
734                 CampaignPostInit();
735
736         fteqcc_testbugs();
737
738         Ban_LoadBans();
739
740         MapInfo_Enumerate();
741         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
742
743         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
744         {
745                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
746                 if(fd != -1)
747                 {
748                         while((s = fgets(fd)))
749                         {
750                                 l = tokenize_console(s);
751                                 if(l < 2)
752                                         continue;
753                                 if(argv(0) == "cd")
754                                 {
755                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
756                                         print("  cdtrack ", argv(2), "\n");
757                                 }
758                                 else if(argv(0) == "fog")
759                                 {
760                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
761                                         print("  \"fog\" \"", s, "\"\n");
762                                 }
763                                 else if(argv(0) == "set")
764                                 {
765                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
766                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
767                                 }
768                                 else if(argv(0) != "//")
769                                 {
770                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
771                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
772                                 }
773                         }
774                         fclose(fd);
775                 }
776         }
777
778         WeaponStats_Init();
779
780         WEPSET_ADDSTAT();
781         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
782         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
783         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
784         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
785         Nagger_Init();
786
787         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
788         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
789         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
790         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
791         addstat(STAT_FUEL, AS_INT, ammo_fuel);
792         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
793         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
794         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
795         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
796         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
797         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
798         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
799         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
800
801         addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
802         addstat(STAT_NEX_CHARGEPOOL, AS_FLOAT, nex_chargepool_ammo);
803
804         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
805
806         if(g_ca || g_freezetag)
807         {
808                 addstat(STAT_REDALIVE, AS_INT, redalive_stat);
809                 addstat(STAT_BLUEALIVE, AS_INT, bluealive_stat);
810                 addstat(STAT_YELLOWALIVE, AS_INT, yellowalive_stat);
811                 addstat(STAT_PINKALIVE, AS_INT, pinkalive_stat);
812         }
813         if(g_freezetag)
814         {
815                 addstat(STAT_FROZEN, AS_INT, freezetag_frozen);
816                 addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, freezetag_revive_progress);
817         }
818         
819         if(g_td)
820         {
821                 addstat(STAT_CURRENT_WAVE, AS_FLOAT, stat_current_wave);
822                 addstat(STAT_TOTALWAVES, AS_FLOAT, stat_totalwaves);
823         }
824         
825         // freeze attacks
826         addstat(STAT_FROZEN, AS_INT, frozen);
827         addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
828
829         // g_movementspeed hack
830         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
831         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
832         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
833         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
834
835         // secrets
836         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
837         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
838         
839         // monsters
840         addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
841         addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
842
843         // misc
844         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
845
846         next_pingtime = time + 5;
847
848         detect_maptype();
849
850         // set up information replies for clients and server to use
851         lsmaps_reply = "^7Maps available: ";
852         lsnewmaps_reply = "^7Maps without a record set: ";
853         for(i = 0, j = 0; i < MapInfo_count; ++i)
854         {
855                 if(MapInfo_Get_ByID(i))
856                         if not(MapInfo_Map_flags & MapInfo_ForbiddenFlags())
857                         {
858                                 if(mod(i, 2))
859                                         col = "^2";
860                                 else
861                                         col = "^3";
862
863                                 ++j;
864
865                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
866
867                                 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
868                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
869                                 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
870                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
871                         }
872         }
873
874         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
875         lsnewmaps_reply = strzone(strcat(((!g_race && !g_cts) ? "Need to be playing race or CTS for lsnewmaps to work." : lsnewmaps_reply), "\n"));
876
877         maplist_reply = "^7Maps in list: ";
878         n = tokenize_console(autocvar_g_maplist);
879         for(i = 0, j = 0; i < n; ++i)
880         {
881                 if(MapInfo_CheckMap(argv(i)))
882                 {
883                         if(mod(j, 2))
884                                 col = "^2";
885                         else
886                                 col = "^3";
887                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
888                         ++j;
889                 }
890         }
891         maplist_reply = strzone(strcat(maplist_reply, "\n"));
892         MapInfo_ClearTemps();
893
894         for(i = 0; i < 10; ++i)
895         {
896                 s = getrecords(i);
897                 if (s)
898                         records_reply[i] = strzone(s);
899         }
900
901         ladder_reply = strzone(getladder());
902
903         rankings_reply = strzone(getrankings());
904
905         // begin other init
906         ClientInit_Spawn();
907         RandomSeed_Spawn();
908         PingPLReport_Spawn();
909
910         CheatInit();
911
912         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
913
914         // fill sv_curl_serverpackages from .serverpackage files
915         if(autocvar_sv_curl_serverpackages_auto)
916         {
917                 s = "";
918                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
919                 for(i = 0; i < n; ++i)
920                         if(substring(argv(i), -14, -1) != "-serverpackage.txt")
921                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
922                                 s = strcat(s, " ", argv(i));
923                 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
924                 if(fd >= 0)
925                 {
926                         j = search_getsize(fd);
927                         for(i = 0; i < j; ++i)
928                                 s = strcat(s, " ", search_getfilename(fd, i));
929                         search_end(fd);
930                 }
931                 fd = search_begin("*.serverpackage", TRUE, FALSE);
932                 if(fd >= 0)
933                 {
934                         j = search_getsize(fd);
935                         for(i = 0; i < j; ++i)
936                                 s = strcat(s, " ", search_getfilename(fd, i));
937                         search_end(fd);
938                 }
939                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
940         }
941
942         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
943         modname = "Xonotic";
944         // physics/balance/config changes that count as mod
945         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
946                 modname = cvar_string("g_mod_physics");
947         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
948                 modname = cvar_string("g_mod_balance");
949         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
950                 modname = cvar_string("g_mod_config");
951         // weird mutators that deserve to count as mod
952         if(autocvar_g_minstagib)
953                 modname = "MinstaGib";
954         if(autocvar_g_monsters)
955                 modname = "Monsters";
956         // extra mutators that deserve to count as mod
957         MUTATOR_CALLHOOK(SetModname);
958
959         // save it for later
960         modname = strzone(modname);
961
962         WinningConditionHelper(); // set worldstatus
963
964         world_initialized = 1;
965 }
966
967 void spawnfunc_light (void)
968 {
969         //makestatic (self); // Who the f___ did that?
970         remove(self);
971 }
972
973 string GetGametype()
974 {
975         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
976 }
977
978 string getmapname_stored;
979 string GetMapname()
980 {
981         return mapname;
982 }
983
984 float Map_Count, Map_Current;
985 string Map_Current_Name;
986
987 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
988 float GetMaplistPosition()
989 {
990         float pos, idx;
991         string map;
992
993         map = GetMapname();
994         idx = autocvar_g_maplist_index;
995
996         if(idx >= 0)
997                 if(idx < Map_Count)
998                         if(map == argv(idx))
999                                 return idx;
1000
1001         for(pos = 0; pos < Map_Count; ++pos)
1002                 if(map == argv(pos))
1003                         return pos;
1004
1005         // resume normal maplist rotation if current map is not in g_maplist
1006         return idx;
1007 }
1008
1009 float MapHasRightSize(string map)
1010 {
1011         float fh;
1012         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
1013         if(autocvar_g_maplist_check_waypoints)
1014         {
1015                 dprint("checkwp "); dprint(map);
1016                 if(!fexists(strcat("maps/", map, ".waypoints")))
1017                 {
1018                         dprint(": no waypoints\n");
1019                         return FALSE;
1020                 }
1021                 dprint(": has waypoints\n");
1022         }
1023
1024         // open map size restriction file
1025         dprint("opensize "); dprint(map);
1026         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1027         if(fh >= 0)
1028         {
1029                 float mapmin, mapmax;
1030                 dprint(": ok, ");
1031                 mapmin = stof(fgets(fh));
1032                 mapmax = stof(fgets(fh));
1033                 fclose(fh);
1034                 if(player_count < mapmin)
1035                 {
1036                         dprint("not enough\n");
1037                         return FALSE;
1038                 }
1039                 if(player_count > mapmax)
1040                 {
1041                         dprint("too many\n");
1042                         return FALSE;
1043                 }
1044                 dprint("right size\n");
1045                 return TRUE;
1046         }
1047         dprint(": not found\n");
1048         return TRUE;
1049 }
1050
1051 string Map_Filename(float position)
1052 {
1053         return strcat("maps/", argv(position), ".bsp");
1054 }
1055
1056 string strwords(string s, float w)
1057 {
1058         float endpos;
1059         for(endpos = 0; w && endpos >= 0; --w)
1060                 endpos = strstrofs(s, " ", endpos + 1);
1061         if(endpos < 0)
1062                 return s;
1063         else
1064                 return substring(s, 0, endpos);
1065 }
1066
1067 float strhasword(string s, string w)
1068 {
1069         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1070 }
1071
1072 void Map_MarkAsRecent(string m)
1073 {
1074         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1075 }
1076
1077 float Map_IsRecent(string m)
1078 {
1079         return strhasword(autocvar_g_maplist_mostrecent, m);
1080 }
1081
1082 float Map_Check(float position, float pass)
1083 {
1084         string filename;
1085         string map_next;
1086         map_next = argv(position);
1087         if(pass <= 1)
1088         {
1089                 if(Map_IsRecent(map_next))
1090                         return 0;
1091         }
1092         filename = Map_Filename(position);
1093         if(MapInfo_CheckMap(map_next))
1094         {
1095                 if(pass == 2)
1096                         return 1;
1097                 if(MapHasRightSize(map_next))
1098                         return 1;
1099                 return 0;
1100         }
1101         else
1102                 dprint( "Couldn't select '", filename, "'..\n" );
1103
1104         return 0;
1105 }
1106
1107 void Map_Goto_SetStr(string nextmapname)
1108 {
1109         if(getmapname_stored != "")
1110                 strunzone(getmapname_stored);
1111         if(nextmapname == "")
1112                 getmapname_stored = "";
1113         else
1114                 getmapname_stored = strzone(nextmapname);
1115 }
1116
1117 void Map_Goto_SetFloat(float position)
1118 {
1119         cvar_set("g_maplist_index", ftos(position));
1120         Map_Goto_SetStr(argv(position));
1121 }
1122
1123 void Map_Goto(float reinit)
1124 {
1125         MapInfo_LoadMap(getmapname_stored, reinit);
1126 }
1127
1128 // return codes of map selectors:
1129 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1130 //   -2 = permanent failure
1131 float() MaplistMethod_Iterate = // usual method
1132 {
1133         float pass, i;
1134
1135         for(pass = 1; pass <= 2; ++pass)
1136         {
1137                 for(i = 1; i < Map_Count; ++i)
1138                 {
1139                         float mapindex;
1140                         mapindex = mod(i + Map_Current, Map_Count);
1141                         if(Map_Check(mapindex, pass))
1142                                 return mapindex;
1143                 }
1144         }
1145         return -1;
1146 }
1147
1148 float() MaplistMethod_Repeat = // fallback method
1149 {
1150         if(Map_Check(Map_Current, 2))
1151                 return Map_Current;
1152         return -2;
1153 }
1154
1155 float() MaplistMethod_Random = // random map selection
1156 {
1157         float i, imax;
1158
1159         imax = 42;
1160
1161         for(i = 0; i <= imax; ++i)
1162         {
1163                 float mapindex;
1164                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
1165                 if(Map_Check(mapindex, 1))
1166                         return mapindex;
1167         }
1168         return -1;
1169 }
1170
1171 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1172 // the exponent sets a bias on the map selection:
1173 // the higher the exponent, the less likely "shortly repeated" same maps are
1174 {
1175         float i, j, imax, insertpos;
1176
1177         imax = 42;
1178
1179         for(i = 0; i <= imax; ++i)
1180         {
1181                 string newlist;
1182
1183                 // now reinsert this at another position
1184                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1185                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1186                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1187                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1188
1189                 // insert the current map there
1190                 newlist = "";
1191                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1192                         newlist = strcat(newlist, " ", argv(j));
1193                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1194                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1195                         newlist = strcat(newlist, " ", argv(j));
1196                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1197                 cvar_set("g_maplist", newlist);
1198                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1199
1200                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1201                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1202                 if(Map_Check(Map_Current, 1))
1203                         return Map_Current;
1204         }
1205         return -1;
1206 }
1207
1208 void Maplist_Init()
1209 {
1210         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1211         if(Map_Count == 0)
1212         {
1213                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
1214                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1215                 if(autocvar_g_maplist_shuffle)
1216                         ShuffleMaplist();
1217                 localcmd("\nmenu_cmd sync\n");
1218                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1219         }
1220         if(Map_Count == 0)
1221                 error("empty maplist, cannot select a new map");
1222         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1223
1224         if(Map_Current_Name)
1225                 strunzone(Map_Current_Name);
1226         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1227         // this may or may not be correct, but who cares, in the worst case a map
1228         // isn't chosen in the first pass that should have been
1229 }
1230
1231 string GetNextMap()
1232 {
1233         float nextMap;
1234
1235         Maplist_Init();
1236         nextMap = -1;
1237
1238         if(nextMap == -1)
1239                 if(autocvar_g_maplist_shuffle > 0)
1240                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1241
1242         if(nextMap == -1)
1243                 if(autocvar_g_maplist_selectrandom)
1244                         nextMap = MaplistMethod_Random();
1245
1246         if(nextMap == -1)
1247                 nextMap = MaplistMethod_Iterate();
1248
1249         if(nextMap == -1)
1250                 nextMap = MaplistMethod_Repeat();
1251
1252         if(nextMap >= 0)
1253         {
1254                 Map_Goto_SetFloat(nextMap);
1255                 return getmapname_stored;
1256         }
1257
1258         return "";
1259 }
1260
1261 float DoNextMapOverride(float reinit)
1262 {
1263         if(autocvar_g_campaign)
1264         {
1265                 CampaignPostIntermission();
1266                 alreadychangedlevel = TRUE;
1267                 return TRUE;
1268         }
1269         if(autocvar_quit_when_empty)
1270         {
1271                 if(player_count <= currentbots)
1272                 {
1273                         localcmd("quit\n");
1274                         alreadychangedlevel = TRUE;
1275                         return TRUE;
1276                 }
1277         }
1278         if(autocvar_quit_and_redirect != "")
1279         {
1280                 redirection_target = strzone(autocvar_quit_and_redirect);
1281                 alreadychangedlevel = TRUE;
1282                 return TRUE;
1283         }
1284         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1285         {
1286                 localcmd("restart\n");
1287                 alreadychangedlevel = TRUE;
1288                 return TRUE;
1289         }
1290         if(autocvar_nextmap != "")
1291                 if(MapInfo_CheckMap(autocvar_nextmap))
1292                 {
1293                         Map_Goto_SetStr(autocvar_nextmap);
1294                         Map_Goto(reinit);
1295                         alreadychangedlevel = TRUE;
1296                         return TRUE;
1297                 }
1298         if(!reinit && autocvar_lastlevel)
1299         {
1300                 cvar_settemp_restore();
1301                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1302                 alreadychangedlevel = TRUE;
1303                 return TRUE;
1304         }
1305         return FALSE;
1306 }
1307
1308 void GotoNextMap(float reinit)
1309 {
1310         //string nextmap;
1311         //float n, nummaps;
1312         //string s;
1313         if (alreadychangedlevel)
1314                 return;
1315         alreadychangedlevel = TRUE;
1316
1317         {
1318                 string nextMap;
1319                 float allowReset;
1320
1321                 for(allowReset = 1; allowReset >= 0; --allowReset)
1322                 {
1323                         nextMap = GetNextMap();
1324                         if(nextMap != "")
1325                                 break;
1326
1327                         if(allowReset)
1328                         {
1329                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1330                                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1331                                 if(autocvar_g_maplist_shuffle)
1332                                         ShuffleMaplist();
1333                                 localcmd("\nmenu_cmd sync\n");
1334                         }
1335                         else
1336                         {
1337                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1338                         }
1339                 }
1340                 Map_Goto(reinit);
1341         }
1342 }
1343
1344
1345 /*
1346 ============
1347 IntermissionThink
1348
1349 When the player presses attack or jump, change to the next level
1350 ============
1351 */
1352 .float autoscreenshot;
1353 void() MapVote_Start;
1354 void() MapVote_Think;
1355 float mapvote_initialized;
1356 void IntermissionThink()
1357 {
1358         FixIntermissionClient(self);
1359
1360         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1361         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1362
1363         if( (server_screenshot || client_screenshot)
1364                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1365         {
1366                 self.autoscreenshot = -1;
1367                 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"))); }
1368                 return;
1369         }
1370
1371         if (time < intermission_exittime)
1372                 return;
1373
1374         if(!mapvote_initialized)
1375                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1376                         return;
1377
1378         MapVote_Start();
1379 }
1380
1381 /*
1382 ============
1383 FindIntermission
1384
1385 Returns the entity to view from
1386 ============
1387 */
1388 /*
1389 entity FindIntermission()
1390 {
1391         local   entity spot;
1392         local   float cyc;
1393
1394 // look for info_intermission first
1395         spot = find (world, classname, "info_intermission");
1396         if (spot)
1397         {       // pick a random one
1398                 cyc = random() * 4;
1399                 while (cyc > 1)
1400                 {
1401                         spot = find (spot, classname, "info_intermission");
1402                         if (!spot)
1403                                 spot = find (spot, classname, "info_intermission");
1404                         cyc = cyc - 1;
1405                 }
1406                 return spot;
1407         }
1408
1409 // then look for the start position
1410         spot = find (world, classname, "info_player_start");
1411         if (spot)
1412                 return spot;
1413
1414 // testinfo_player_start is only found in regioned levels
1415         spot = find (world, classname, "testplayerstart");
1416         if (spot)
1417                 return spot;
1418
1419 // then look for the start position
1420         spot = find (world, classname, "info_player_deathmatch");
1421         if (spot)
1422                 return spot;
1423
1424         //objerror ("FindIntermission: no spot");
1425         return world;
1426 }
1427 */
1428
1429 /*
1430 ===============================================================================
1431
1432 RULES
1433
1434 ===============================================================================
1435 */
1436
1437 void DumpStats(float final)
1438 {
1439         float file;
1440         string s;
1441         float to_console;
1442         float to_eventlog;
1443         float to_file;
1444         float i;
1445
1446         to_console = autocvar_sv_logscores_console;
1447         to_eventlog = autocvar_sv_eventlog;
1448         to_file = autocvar_sv_logscores_file;
1449
1450         if(!final)
1451         {
1452                 to_console = TRUE; // always print printstats replies
1453                 to_eventlog = FALSE; // but never print them to the event log
1454         }
1455
1456         if(to_eventlog)
1457                 if(autocvar_sv_eventlog_console)
1458                         to_console = FALSE; // otherwise we get the output twice
1459
1460         if(final)
1461                 s = ":scores:";
1462         else
1463                 s = ":status:";
1464         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1465
1466         if(to_console)
1467                 print(s, "\n");
1468         if(to_eventlog)
1469                 GameLogEcho(s);
1470
1471         file = -1;
1472         if(to_file)
1473         {
1474                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1475                 if(file == -1)
1476                         to_file = FALSE;
1477                 else
1478                         fputs(file, strcat(s, "\n"));
1479         }
1480
1481         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1482         if(to_console)
1483                 print(s, "\n");
1484         if(to_eventlog)
1485                 GameLogEcho(s);
1486         if(to_file)
1487                 fputs(file, strcat(s, "\n"));
1488
1489         FOR_EACH_CLIENT(other)
1490         {
1491                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && autocvar_sv_logscores_bots))
1492                 {
1493                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1494                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1495                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1496                                 s = strcat(s, ftos(other.team), ":");
1497                         else
1498                                 s = strcat(s, "spectator:");
1499
1500                         if(to_console)
1501                                 print(s, other.netname, "\n");
1502                         if(to_eventlog)
1503                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1504                         if(to_file)
1505                                 fputs(file, strcat(s, other.netname, "\n"));
1506                 }
1507         }
1508
1509         if(teamplay)
1510         {
1511                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1512                 if(to_console)
1513                         print(s, "\n");
1514                 if(to_eventlog)
1515                         GameLogEcho(s);
1516                 if(to_file)
1517                         fputs(file, strcat(s, "\n"));
1518
1519                 for(i = 1; i < 16; ++i)
1520                 {
1521                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1522                         s = strcat(s, ":", ftos(i));
1523                         if(to_console)
1524                                 print(s, "\n");
1525                         if(to_eventlog)
1526                                 GameLogEcho(s);
1527                         if(to_file)
1528                                 fputs(file, strcat(s, "\n"));
1529                 }
1530         }
1531
1532         if(to_console)
1533                 print(":end\n");
1534         if(to_eventlog)
1535                 GameLogEcho(":end");
1536         if(to_file)
1537         {
1538                 fputs(file, ":end\n");
1539                 fclose(file);
1540         }
1541 }
1542
1543 void FixIntermissionClient(entity e)
1544 {
1545         string s;
1546         if(!e.autoscreenshot) // initial call
1547         {
1548                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1549                 e.health = -2342;
1550                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1551                 e.solid = SOLID_NOT;
1552                 e.movetype = MOVETYPE_NONE;
1553                 e.takedamage = DAMAGE_NO;
1554                 if(e.weaponentity)
1555                 {
1556                         e.weaponentity.effects = EF_NODRAW;
1557                         if (e.weaponentity.weaponentity)
1558                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1559                 }
1560                 if(clienttype(e) == CLIENTTYPE_REAL)
1561                 {
1562                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1563                         s = autocvar_sv_intermission_cdtrack;
1564                         if(s != "")
1565                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1566                         msg_entity = e;
1567                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1568                 }
1569         }
1570 }
1571
1572 void minstagib_stop_countdown(entity e);
1573 /*
1574 go to the next level for deathmatch
1575 only called if a time or frag limit has expired
1576 */
1577 void NextLevel()
1578 {
1579         gameover = TRUE;
1580
1581         intermission_running = 1;
1582
1583 // enforce a wait time before allowing changelevel
1584         if(player_count > 0)
1585                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1586         else
1587                 intermission_exittime = -1;
1588
1589         /*
1590         WriteByte (MSG_ALL, SVC_CDTRACK);
1591         WriteByte (MSG_ALL, 3);
1592         WriteByte (MSG_ALL, 3);
1593         // done in FixIntermission
1594         */
1595
1596         //pos = FindIntermission ();
1597
1598         VoteReset();
1599
1600         DumpStats(TRUE);
1601
1602         // send statistics
1603         entity e;
1604         PlayerStats_EndMatch(1);
1605         FOR_EACH_CLIENT(e)
1606                 PlayerStats_AddGlobalInfo(e);
1607         PlayerStats_Shutdown();
1608         WeaponStats_Shutdown();
1609
1610         if(autocvar_sv_eventlog)
1611                 GameLogEcho(":gameover");
1612
1613         GameLogClose();
1614
1615         FOR_EACH_PLAYER(other) {
1616                 minstagib_stop_countdown(other);
1617                 FixIntermissionClient(other);
1618                 if(other.winning)
1619                         bprint(other.netname, " ^7wins.\n");
1620         }
1621
1622         if(autocvar_g_campaign)
1623                 CampaignPreIntermission();
1624
1625         MUTATOR_CALLHOOK(MatchEnd);
1626
1627         localcmd("\nsv_hook_gameend\n");
1628 }
1629
1630 /*
1631 ============
1632 CheckRules_Player
1633
1634 Exit deathmatch games upon conditions
1635 ============
1636 */
1637 void CheckRules_Player()
1638 {
1639         if (gameover)   // someone else quit the game already
1640                 return;
1641
1642         if(self.deadflag == DEAD_NO)
1643                 self.play_time += frametime;
1644
1645         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1646         //   (div0: and that in CheckRules_World please)
1647 }
1648
1649 float checkrules_equality;
1650 float checkrules_suddendeathwarning;
1651 float checkrules_suddendeathend;
1652 float checkrules_overtimesadded; //how many overtimes have been already added
1653
1654 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1655 float WINNING_YES = 1; // winner found
1656 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1657 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1658
1659 float InitiateSuddenDeath()
1660 {
1661         // Check first whether normal overtimes could be added before initiating suddendeath mode
1662         // - for this timelimit_overtime needs to be >0 of course
1663         // - also check the winning condition calculated in the previous frame and only add normal overtime
1664         //   again, if at the point at which timelimit would be extended again, still no winner was found
1665         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1666         {
1667                 return 1; // need to call InitiateOvertime later
1668         }
1669         else
1670         {
1671                 if(!checkrules_suddendeathend)
1672                 {
1673                         if(autocvar_g_campaign)
1674                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1675                         else
1676                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1677                         if(g_race && !g_race_qualifying)
1678                                 race_StartCompleting();
1679                 }
1680                 return 0;
1681         }
1682 }
1683
1684 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1685 {
1686         ++checkrules_overtimesadded;
1687         //add one more overtime by simply extending the timelimit
1688         float tl;
1689         tl = autocvar_timelimit;
1690         tl += autocvar_timelimit_overtime;
1691         cvar_set("timelimit", ftos(tl));
1692         string minutesPlural;
1693         if (autocvar_timelimit_overtime == 1)
1694                 minutesPlural = " ^3minute";
1695         else
1696                 minutesPlural = " ^3minutes";
1697
1698         bcenterprint(
1699                 strcat(
1700                         "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1701                         ftos(autocvar_timelimit_overtime),
1702                         minutesPlural,
1703                         " to the game!"
1704                 )
1705         );
1706 }
1707
1708 float GetWinningCode(float fraglimitreached, float equality)
1709 {
1710         if(autocvar_g_campaign == 1)
1711                 if(fraglimitreached)
1712                         return WINNING_YES;
1713                 else
1714                         return WINNING_NO;
1715
1716         else
1717                 if(equality)
1718                         if(fraglimitreached)
1719                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1720                         else
1721                                 return WINNING_NEVER;
1722                 else
1723                         if(fraglimitreached)
1724                                 return WINNING_YES;
1725                         else
1726                                 return WINNING_NO;
1727 }
1728
1729 // set the .winning flag for exactly those players with a given field value
1730 void SetWinners(.float field, float value)
1731 {
1732         entity head;
1733         FOR_EACH_PLAYER(head)
1734                 head.winning = (head.field == value);
1735 }
1736
1737 // set the .winning flag for those players with a given field value
1738 void AddWinners(.float field, float value)
1739 {
1740         entity head;
1741         FOR_EACH_PLAYER(head)
1742                 if(head.field == value)
1743                         head.winning = 1;
1744 }
1745
1746 // clear the .winning flags
1747 void ClearWinners(void)
1748 {
1749         entity head;
1750         FOR_EACH_PLAYER(head)
1751                 head.winning = 0;
1752 }
1753
1754 // Onslaught winning condition:
1755 // game terminates if only one team has a working generator (or none)
1756 float WinningCondition_Onslaught()
1757 {
1758         entity head;
1759         float t1, t2, t3, t4;
1760
1761         WinningConditionHelper(); // set worldstatus
1762
1763         if(inWarmupStage)
1764                 return WINNING_NO;
1765
1766         // first check if the game has ended
1767         t1 = t2 = t3 = t4 = 0;
1768         head = find(world, classname, "onslaught_generator");
1769         while (head)
1770         {
1771                 if (head.health > 0)
1772                 {
1773                         if (head.team == COLOR_TEAM1) t1 = 1;
1774                         if (head.team == COLOR_TEAM2) t2 = 1;
1775                         if (head.team == COLOR_TEAM3) t3 = 1;
1776                         if (head.team == COLOR_TEAM4) t4 = 1;
1777                 }
1778                 head = find(head, classname, "onslaught_generator");
1779         }
1780         if (t1 + t2 + t3 + t4 < 2)
1781         {
1782                 // game over, only one team remains (or none)
1783                 ClearWinners();
1784                 if (t1) SetWinners(team, COLOR_TEAM1);
1785                 if (t2) SetWinners(team, COLOR_TEAM2);
1786                 if (t3) SetWinners(team, COLOR_TEAM3);
1787                 if (t4) SetWinners(team, COLOR_TEAM4);
1788                 dprint("Have a winner, ending game.\n");
1789                 return WINNING_YES;
1790         }
1791
1792         // Two or more teams remain
1793         return WINNING_NO;
1794 }
1795
1796 float LMS_NewPlayerLives()
1797 {
1798         float fl;
1799         fl = autocvar_fraglimit;
1800         if(fl == 0)
1801                 fl = 999;
1802
1803         // first player has left the game for dying too much? Nobody else can get in.
1804         if(lms_lowest_lives < 1)
1805                 return 0;
1806
1807         if(!autocvar_g_lms_join_anytime)
1808                 if(lms_lowest_lives < fl - autocvar_g_lms_last_join)
1809                         return 0;
1810
1811         return bound(1, lms_lowest_lives, fl);
1812 }
1813
1814 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1815 // they win. Otherwise the defending team wins once the timelimit passes.
1816 void assault_new_round();
1817 float WinningCondition_Assault()
1818 {
1819         float status;
1820
1821         WinningConditionHelper(); // set worldstatus
1822
1823         status = WINNING_NO;
1824         // as the timelimit has not yet passed just assume the defending team will win
1825         if(assault_attacker_team == COLOR_TEAM1)
1826         {
1827                 SetWinners(team, COLOR_TEAM2);
1828         }
1829         else
1830         {
1831                 SetWinners(team, COLOR_TEAM1);
1832         }
1833
1834         entity ent;
1835         ent = find(world, classname, "target_assault_roundend");
1836         if(ent)
1837         {
1838                 if(ent.winning) // round end has been triggered by attacking team
1839                 {
1840                         bprint("ASSAULT: round completed...\n");
1841                         SetWinners(team, assault_attacker_team);
1842
1843                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1844
1845                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1846                         {
1847                                 status = WINNING_YES;
1848                         }
1849                         else
1850                         {
1851                                 entity oldself;
1852                                 oldself = self;
1853                                 self = ent;
1854                                 assault_new_round();
1855                                 self = oldself;
1856                         }
1857                 }
1858         }
1859
1860         return status;
1861 }
1862
1863 // LMS winning condition: game terminates if and only if there's at most one
1864 // one player who's living lives. Top two scores being equal cancels the time
1865 // limit.
1866 float WinningCondition_LMS()
1867 {
1868         entity head, head2;
1869         float have_player;
1870         float have_players;
1871         float l;
1872
1873         have_player = FALSE;
1874         have_players = FALSE;
1875         l = LMS_NewPlayerLives();
1876
1877         head = find(world, classname, "player");
1878         if(head)
1879                 have_player = TRUE;
1880         head2 = find(head, classname, "player");
1881         if(head2)
1882                 have_players = TRUE;
1883
1884         if(have_player)
1885         {
1886                 // we have at least one player
1887                 if(have_players)
1888                 {
1889                         // two or more active players - continue with the game
1890                 }
1891                 else
1892                 {
1893                         // exactly one player?
1894
1895                         ClearWinners();
1896                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1897
1898                         if(l)
1899                         {
1900                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1901                                 return WINNING_NO;
1902                         }
1903                         else
1904                         {
1905                                 // a winner!
1906                                 // and assign him his first place
1907                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1908                                 return WINNING_YES;
1909                         }
1910                 }
1911         }
1912         else
1913         {
1914                 // nobody is playing at all...
1915                 if(l)
1916                 {
1917                         // wait for players...
1918                 }
1919                 else
1920                 {
1921                         // SNAFU (maybe a draw game?)
1922                         ClearWinners();
1923                         dprint("No players, ending game.\n");
1924                         return WINNING_YES;
1925                 }
1926         }
1927
1928         // When we get here, we have at least two players who are actually LIVING,
1929         // now check if the top two players have equal score.
1930         WinningConditionHelper();
1931
1932         ClearWinners();
1933         if(WinningConditionHelper_winner)
1934                 WinningConditionHelper_winner.winning = TRUE;
1935         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1936                 return WINNING_NEVER;
1937
1938         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1939         return WINNING_NO;
1940 }
1941
1942 void ShuffleMaplist()
1943 {
1944         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1945 }
1946
1947 float leaderfrags;
1948 float WinningCondition_Scores(float limit, float leadlimit)
1949 {
1950         float limitreached;
1951
1952         // TODO make everything use THIS winning condition (except LMS)
1953         WinningConditionHelper();
1954
1955         if(teamplay)
1956         {
1957                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1958                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1959                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1960                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1961         }
1962
1963         ClearWinners();
1964         if(WinningConditionHelper_winner)
1965                 WinningConditionHelper_winner.winning = 1;
1966         if(WinningConditionHelper_winnerteam >= 0)
1967                 SetWinners(team, WinningConditionHelper_winnerteam);
1968
1969         if(WinningConditionHelper_lowerisbetter)
1970         {
1971                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1972                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1973                 limit = -limit;
1974         }
1975
1976         if(WinningConditionHelper_zeroisworst)
1977                 leadlimit = 0; // not supported in this mode
1978
1979         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1980         // these modes always score in increments of 1, thus this makes sense
1981         {
1982                 if(leaderfrags != WinningConditionHelper_topscore)
1983                 {
1984                         leaderfrags = WinningConditionHelper_topscore;
1985
1986                         if (limit)
1987                         if (leaderfrags == limit - 1)
1988                                 Announce("1fragleft");
1989                         else if (leaderfrags == limit - 2)
1990                                 Announce("2fragsleft");
1991                         else if (leaderfrags == limit - 3)
1992                                 Announce("3fragsleft");
1993                 }
1994         }
1995
1996         limitreached = FALSE;
1997         if(limit)
1998                 if(WinningConditionHelper_topscore >= limit)
1999                         limitreached = TRUE;
2000         if(leadlimit)
2001         {
2002                 float leadlimitreached;
2003                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
2004                 if(autocvar_leadlimit_and_fraglimit)
2005                         limitreached = (limitreached && leadlimitreached);
2006                 else
2007                         limitreached = (limitreached || leadlimitreached);
2008         }
2009
2010         if(limit)
2011                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
2012
2013         return GetWinningCode(
2014                 WinningConditionHelper_topscore && limitreached,
2015                 WinningConditionHelper_equality
2016         );
2017 }
2018
2019 float WinningCondition_Race(float fraglimit)
2020 {
2021         float wc;
2022         entity p;
2023         float n, c;
2024
2025         n = 0;
2026         c = 0;
2027         FOR_EACH_PLAYER(p)
2028         {
2029                 ++n;
2030                 if(p.race_completed)
2031                         ++c;
2032         }
2033         if(n && (n == c))
2034                 return WINNING_YES;
2035         wc = WinningCondition_Scores(fraglimit, 0);
2036
2037         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
2038         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2039         // do NOT support equality when the laps are all raced!
2040                 return WINNING_STARTSUDDENDEATHOVERTIME;
2041         else
2042                 return WINNING_NEVER;
2043 }
2044
2045 float WinningCondition_QualifyingThenRace(float limit)
2046 {
2047         float wc;
2048         wc = WinningCondition_Scores(limit, 0);
2049
2050         // NEVER initiate overtime
2051         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2052         {
2053                 return WINNING_YES;
2054         }
2055
2056         return wc;
2057 }
2058
2059 float WinningCondition_RanOutOfSpawns()
2060 {
2061         entity head;
2062
2063         if(have_team_spawns <= 0)
2064                 return WINNING_NO;
2065
2066         if(autocvar_g_spawn_useallspawns <= 0)
2067                 return WINNING_NO;
2068
2069         if(!some_spawn_has_been_used)
2070                 return WINNING_NO;
2071
2072         team1_score = team2_score = team3_score = team4_score = 0;
2073
2074         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
2075         {
2076                 if(head.team == COLOR_TEAM1)
2077                         team1_score = 1;
2078                 else if(head.team == COLOR_TEAM2)
2079                         team2_score = 1;
2080                 else if(head.team == COLOR_TEAM3)
2081                         team3_score = 1;
2082                 else if(head.team == COLOR_TEAM4)
2083                         team4_score = 1;
2084         }
2085
2086         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
2087         {
2088                 if(head.team == COLOR_TEAM1)
2089                         team1_score = 1;
2090                 else if(head.team == COLOR_TEAM2)
2091                         team2_score = 1;
2092                 else if(head.team == COLOR_TEAM3)
2093                         team3_score = 1;
2094                 else if(head.team == COLOR_TEAM4)
2095                         team4_score = 1;
2096         }
2097
2098         ClearWinners();
2099         if(team1_score + team2_score + team3_score + team4_score == 0)
2100         {
2101                 checkrules_equality = TRUE;
2102                 return WINNING_YES;
2103         }
2104         else if(team1_score + team2_score + team3_score + team4_score == 1)
2105         {
2106                 float t, i;
2107                 if(team1_score)
2108                         t = COLOR_TEAM1;
2109                 else if(team2_score)
2110                         t = COLOR_TEAM2;
2111                 else if(team3_score)
2112                         t = COLOR_TEAM3;
2113                 else // if(team4_score)
2114                         t = COLOR_TEAM4;
2115                 CheckAllowedTeams(world);
2116                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2117                 {
2118                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
2119                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
2120                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
2121                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
2122                 }
2123
2124                 AddWinners(team, t);
2125                 return WINNING_YES;
2126         }
2127         else
2128                 return WINNING_NO;
2129 }
2130
2131 // TD winning condition:
2132 // game terminates if there are no generators (or 1 dies if td_dontend is TRUE)
2133 float gensurvived;
2134 float WinningCondition_TowerDefense()
2135 {
2136         WinningConditionHelper(); // set worldstatus
2137
2138         if(inWarmupStage)
2139                 return WINNING_NO;
2140
2141         // first check if the game has ended
2142         if(gendestroyed == TRUE) // FALSE means either generator hasen't spawned yet, or mapper didn't add one
2143         if(td_gencount < 1 || !td_dont_end)
2144         {
2145                 ClearWinners();
2146                 dprint("Everyone lost, ending game.\n");
2147                 return WINNING_YES;
2148         }
2149         
2150         if(gensurvived)
2151         {
2152                 ClearWinners();
2153                 SetWinners(winning, 4);
2154                 return WINNING_YES;
2155         }
2156
2157         // Two or more teams remain
2158         return WINNING_NO;
2159 }
2160
2161 /*
2162 ============
2163 CheckRules_World
2164
2165 Exit deathmatch games upon conditions
2166 ============
2167 */
2168 void ReadyRestart();
2169 void CheckRules_World()
2170 {
2171         float timelimit;
2172         float fraglimit;
2173         float leadlimit;
2174
2175         VoteThink();
2176         MapVote_Think();
2177
2178         SetDefaultAlpha();
2179
2180         /*
2181         MapVote_Think should now do that part
2182         if (intermission_running)
2183                 if (time >= intermission_exittime + 60)
2184                 {
2185                         if(!DoNextMapOverride())
2186                                 GotoNextMap();
2187                         return;
2188                 }
2189         */
2190
2191         if (gameover)   // someone else quit the game already
2192         {
2193                 if(player_count == 0) // Nobody there? Then let's go to the next map
2194                         MapVote_Start();
2195                         // this will actually check the player count in the next frame
2196                         // again, but this shouldn't hurt
2197                 return;
2198         }
2199
2200         timelimit = autocvar_timelimit * 60;
2201         fraglimit = autocvar_fraglimit;
2202         leadlimit = autocvar_leadlimit;
2203
2204         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2205         {
2206                 if(timelimit > 0)
2207                         timelimit = 0; // timelimit is not made for warmup
2208                 if(fraglimit > 0)
2209                         fraglimit = 0; // no fraglimit for now
2210                 leadlimit = 0; // no leadlimit for now
2211         }
2212
2213         if(timelimit > 0)
2214         {
2215                 timelimit += game_starttime;
2216         }
2217         else if (timelimit < 0)
2218         {
2219                 // endmatch
2220                 NextLevel();
2221                 return;
2222         }
2223
2224         if(g_onslaught)
2225                 timelimit = 0; // ONS has its own overtime rule
2226
2227         float wantovertime;
2228         wantovertime = 0;
2229
2230         if(timelimit > game_starttime)
2231                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2232         else
2233                 game_completion_ratio = 0;
2234
2235         if(checkrules_suddendeathend)
2236         {
2237                 if(!checkrules_suddendeathwarning)
2238                 {
2239                         checkrules_suddendeathwarning = TRUE;
2240                         if(g_race && !g_race_qualifying)
2241                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
2242                         else
2243                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
2244                 }
2245         }
2246         else
2247         {
2248                 if (timelimit && time >= timelimit)
2249                 {
2250                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2251                         {
2252                                 float totalplayers;
2253                                 float playerswithlaps;
2254                                 float readyplayers;
2255                                 entity head;
2256                                 totalplayers = playerswithlaps = readyplayers = 0;
2257                                 FOR_EACH_PLAYER(head)
2258                                 {
2259                                         ++totalplayers;
2260                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2261                                                 ++playerswithlaps;
2262                                         if(head.ready)
2263                                                 ++readyplayers;
2264                                 }
2265
2266                                 // at least 2 of the players have completed a lap: start the RACE
2267                                 // otherwise, the players should end the qualifying on their own
2268                                 if(readyplayers || playerswithlaps >= 2)
2269                                 {
2270                                         checkrules_suddendeathend = 0;
2271                                         ReadyRestart(); // go to race
2272                                         return;
2273                                 }
2274                                 else
2275                                         wantovertime |= InitiateSuddenDeath();
2276                         }
2277                         else
2278                                 wantovertime |= InitiateSuddenDeath();
2279                 }
2280         }
2281
2282         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2283         {
2284                 NextLevel();
2285                 return;
2286         }
2287
2288         float checkrules_status;
2289         checkrules_status = WinningCondition_RanOutOfSpawns();
2290         if(checkrules_status == WINNING_YES)
2291         {
2292                 bprint("Hey! Someone ran out of spawns!\n");
2293         }
2294         else if(g_race && !g_race_qualifying && timelimit >= 0)
2295         {
2296                 checkrules_status = WinningCondition_Race(fraglimit);
2297                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2298         }
2299         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2300         {
2301                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2302                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2303         }
2304         else if(g_assault)
2305         {
2306                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2307         }
2308         else if(g_lms)
2309         {
2310                 checkrules_status = WinningCondition_LMS();
2311         }
2312         else if (g_onslaught)
2313         {
2314                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2315         }
2316         else if(g_td)
2317         {
2318                 checkrules_status = WinningCondition_TowerDefense(); // TODO make these mutator hooks?
2319         }
2320         else
2321         {
2322                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2323                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2324         }
2325
2326         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2327         {
2328                 checkrules_status = WINNING_NEVER;
2329                 checkrules_overtimesadded = -1;
2330                 wantovertime |= InitiateSuddenDeath();
2331         }
2332
2333         if(checkrules_status == WINNING_NEVER)
2334                 // equality cases! Nobody wins if the overtime ends in a draw.
2335                 ClearWinners();
2336
2337         if(wantovertime)
2338         {
2339                 if(checkrules_status == WINNING_NEVER)
2340                         InitiateOvertime();
2341                 else
2342                         checkrules_status = WINNING_YES;
2343         }
2344
2345         if(checkrules_suddendeathend)
2346                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2347                         checkrules_status = WINNING_YES;
2348
2349         if(checkrules_status == WINNING_YES)
2350         {
2351                 //print("WINNING\n");
2352                 NextLevel();
2353         }
2354 }
2355
2356 float mapvote_nextthink;
2357 float mapvote_initialized;
2358 float mapvote_keeptwotime;
2359 float mapvote_timeout;
2360 string mapvote_message;
2361 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2362 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2363 float mapvote_screenshot_dirs_count;
2364
2365 float mapvote_count;
2366 float mapvote_count_real;
2367 string mapvote_maps[MAPVOTE_COUNT];
2368 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2369 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2370 float mapvote_maps_suggested[MAPVOTE_COUNT];
2371 string mapvote_suggestions[MAPVOTE_COUNT];
2372 float mapvote_suggestion_ptr;
2373 float mapvote_voters;
2374 float mapvote_selections[MAPVOTE_COUNT];
2375 float mapvote_run;
2376 float mapvote_detail;
2377 float mapvote_abstain;
2378 .float mapvote;
2379
2380 void MapVote_ClearAllVotes()
2381 {
2382         FOR_EACH_CLIENT(other)
2383                 other.mapvote = 0;
2384 }
2385
2386 string MapVote_Suggest(string m)
2387 {
2388         float i;
2389         if(m == "")
2390                 return "That's not how to use this command.";
2391         if(!autocvar_g_maplist_votable_suggestions)
2392                 return "Suggestions are not accepted on this server.";
2393         if(mapvote_initialized)
2394                 return "Can't suggest - voting is already in progress!";
2395         m = MapInfo_FixName(m);
2396         if not(m)
2397                 return "The map you suggested is not available on this server.";
2398         if(!autocvar_g_maplist_votable_suggestions_override_mostrecent)
2399                 if(Map_IsRecent(m))
2400                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2401
2402         if(!MapInfo_CheckMap(m))
2403                 return "The map you suggested does not support the current game mode.";
2404         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2405                 if(mapvote_suggestions[i] == m)
2406                         return "This map was already suggested.";
2407         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2408         {
2409                 i = floor(random() * mapvote_suggestion_ptr);
2410         }
2411         else
2412         {
2413                 i = mapvote_suggestion_ptr;
2414                 mapvote_suggestion_ptr += 1;
2415         }
2416         if(mapvote_suggestions[i] != "")
2417                 strunzone(mapvote_suggestions[i]);
2418         mapvote_suggestions[i] = strzone(m);
2419         if(autocvar_sv_eventlog)
2420                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2421         return strcat("Suggestion of ", m, " accepted.");
2422 }
2423
2424 void MapVote_AddVotable(string nextMap, float isSuggestion)
2425 {
2426         float j, i, o;
2427         string pakfile, mapfile;
2428
2429         if(nextMap == "")
2430                 return;
2431         for(j = 0; j < mapvote_count; ++j)
2432                 if(mapvote_maps[j] == nextMap)
2433                         return;
2434         // suggestions might be no longer valid/allowed after gametype switch!
2435         if(isSuggestion)
2436                 if(!MapInfo_CheckMap(nextMap))
2437                         return;
2438         mapvote_maps[mapvote_count] = strzone(nextMap);
2439         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2440
2441         pakfile = string_null;
2442         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2443         {
2444                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2445                 pakfile = whichpack(strcat(mapfile, ".tga"));
2446                 if(pakfile == "")
2447                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2448                 if(pakfile == "")
2449                         pakfile = whichpack(strcat(mapfile, ".png"));
2450                 if(pakfile != "")
2451                         break;
2452         }
2453         if(i >= mapvote_screenshot_dirs_count)
2454                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2455         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2456                 pakfile = substring(pakfile, o, -1);
2457
2458         mapvote_maps_screenshot_dir[mapvote_count] = i;
2459         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2460
2461         mapvote_count += 1;
2462 }
2463
2464 void MapVote_Spawn();
2465 void MapVote_Init()
2466 {
2467         float i;
2468         float nmax, smax;
2469
2470         MapVote_ClearAllVotes();
2471
2472         mapvote_count = 0;
2473         mapvote_detail = !autocvar_g_maplist_votable_nodetail;
2474         mapvote_abstain = autocvar_g_maplist_votable_abstain;
2475
2476         if(mapvote_abstain)
2477                 nmax = min(MAPVOTE_COUNT - 1, autocvar_g_maplist_votable);
2478         else
2479                 nmax = min(MAPVOTE_COUNT, autocvar_g_maplist_votable);
2480         smax = min3(nmax, autocvar_g_maplist_votable_suggestions, mapvote_suggestion_ptr);
2481
2482         // we need this for AddVotable, as that cycles through the screenshot dirs
2483         mapvote_screenshot_dirs_count = tokenize_console(autocvar_g_maplist_votable_screenshot_dir);
2484         if(mapvote_screenshot_dirs_count == 0)
2485                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2486         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2487         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2488                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2489
2490         if(mapvote_suggestion_ptr)
2491                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2492                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2493
2494         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2495                 MapVote_AddVotable(GetNextMap(), FALSE);
2496
2497         if(mapvote_count == 0)
2498         {
2499                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2500                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2501                 if(autocvar_g_maplist_shuffle)
2502                         ShuffleMaplist();
2503                 localcmd("\nmenu_cmd sync\n");
2504                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2505                         MapVote_AddVotable(GetNextMap(), FALSE);
2506         }
2507
2508         mapvote_count_real = mapvote_count;
2509         if(mapvote_abstain)
2510                 MapVote_AddVotable("don't care", 0);
2511
2512         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2513
2514         mapvote_keeptwotime = time + autocvar_g_maplist_votable_keeptwotime;
2515         mapvote_timeout = time + autocvar_g_maplist_votable_timeout;
2516         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2517                 mapvote_keeptwotime = 0;
2518         mapvote_message = "Choose a map and press its key!";
2519
2520         MapVote_Spawn();
2521 }
2522
2523 void MapVote_SendPicture(float id)
2524 {
2525         msg_entity = self;
2526         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2527         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2528         WriteByte(MSG_ONE, id);
2529         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2530 }
2531
2532 float MapVote_GetMapMask()
2533 {
2534         float mask, i, power;
2535         mask = 0;
2536         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2537                 if(mapvote_maps[i] != "")
2538                         mask |= power;
2539         return mask;
2540 }
2541
2542 entity mapvote_ent;
2543 float MapVote_SendEntity(entity to, float sf)
2544 {
2545         float i;
2546
2547         if(sf & 1)
2548                 sf &~= 2; // if we send 1, we don't need to also send 2
2549
2550         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2551         WriteByte(MSG_ENTITY, sf);
2552
2553         if(sf & 1)
2554         {
2555                 // flag 1 == initialization
2556                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2557                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2558                 WriteString(MSG_ENTITY, "");
2559                 WriteByte(MSG_ENTITY, mapvote_count);
2560                 WriteByte(MSG_ENTITY, mapvote_abstain);
2561                 WriteByte(MSG_ENTITY, mapvote_detail);
2562                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2563                 if(mapvote_count <= 8)
2564                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2565                 else
2566                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2567                 for(i = 0; i < mapvote_count; ++i)
2568                         if(mapvote_maps[i] != "")
2569                         {
2570                                 if(mapvote_abstain && i == mapvote_count - 1)
2571                                 {
2572                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2573                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2574                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2575                                 }
2576                                 else
2577                                 {
2578                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2579                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2580                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2581                                 }
2582                         }
2583         }
2584
2585         if(sf & 2)
2586         {
2587                 // flag 2 == update of mask
2588                 if(mapvote_count <= 8)
2589                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2590                 else
2591                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2592         }
2593
2594         if(sf & 4)
2595         {
2596                 if(mapvote_detail)
2597                         for(i = 0; i < mapvote_count; ++i)
2598                                 if(mapvote_maps[i] != "")
2599                                         WriteByte(MSG_ENTITY, mapvote_selections[i]);
2600
2601                 WriteByte(MSG_ENTITY, to.mapvote);
2602         }
2603
2604         return TRUE;
2605 }
2606
2607 void MapVote_Spawn()
2608 {
2609         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2610 }
2611
2612 void MapVote_TouchMask()
2613 {
2614         mapvote_ent.SendFlags |= 2;
2615 }
2616
2617 void MapVote_TouchVotes(entity voter)
2618 {
2619         mapvote_ent.SendFlags |= 4;
2620 }
2621
2622 float MapVote_Finished(float mappos)
2623 {
2624         string result;
2625         float i;
2626         float didntvote;
2627
2628         if(autocvar_sv_eventlog)
2629         {
2630                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2631                 result = strcat(result, ":", ftos(mapvote_selections[mappos]), "::");
2632                 didntvote = mapvote_voters;
2633                 for(i = 0; i < mapvote_count; ++i)
2634                         if(mapvote_maps[i] != "")
2635                         {
2636                                 didntvote -= mapvote_selections[i];
2637                                 if(i != mappos)
2638                                 {
2639                                         result = strcat(result, ":", mapvote_maps[i]);
2640                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2641                                 }
2642                         }
2643                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2644
2645                 GameLogEcho(result);
2646                 if(mapvote_maps_suggested[mappos])
2647                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2648         }
2649
2650         FOR_EACH_REALCLIENT(other)
2651                 FixClientCvars(other);
2652
2653         Map_Goto_SetStr(mapvote_maps[mappos]);
2654         Map_Goto(0);
2655         alreadychangedlevel = TRUE;
2656         return TRUE;
2657 }
2658 void MapVote_CheckRules_1()
2659 {
2660         float i;
2661
2662         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2663         {
2664                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2665                 mapvote_selections[i] = 0;
2666         }
2667
2668         mapvote_voters = 0;
2669         FOR_EACH_REALCLIENT(other)
2670         {
2671                 ++mapvote_voters;
2672                 if(other.mapvote)
2673                 {
2674                         i = other.mapvote - 1;
2675                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2676                         mapvote_selections[i] = mapvote_selections[i] + 1;
2677                 }
2678         }
2679 }
2680
2681 float MapVote_CheckRules_2()
2682 {
2683         float i;
2684         float firstPlace, secondPlace;
2685         float firstPlaceVotes, secondPlaceVotes;
2686         float mapvote_voters_real;
2687         string result;
2688
2689         if(mapvote_count_real == 1)
2690                 return MapVote_Finished(0);
2691
2692         mapvote_voters_real = mapvote_voters;
2693         if(mapvote_abstain)
2694                 mapvote_voters_real -= mapvote_selections[mapvote_count - 1];
2695
2696         RandomSelection_Init();
2697         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2698                 RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2699         firstPlace = RandomSelection_chosen_float;
2700         firstPlaceVotes = RandomSelection_best_priority;
2701         //dprint("First place: ", ftos(firstPlace), "\n");
2702         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2703
2704         RandomSelection_Init();
2705         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2706                 if(i != firstPlace)
2707                         RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2708         secondPlace = RandomSelection_chosen_float;
2709         secondPlaceVotes = RandomSelection_best_priority;
2710         //dprint("Second place: ", ftos(secondPlace), "\n");
2711         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2712
2713         if(firstPlace == -1)
2714                 error("No first place in map vote... WTF?");
2715
2716         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2717                 return MapVote_Finished(firstPlace);
2718
2719         if(mapvote_keeptwotime)
2720                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2721                 {
2722                         float didntvote;
2723                         MapVote_TouchMask();
2724                         mapvote_message = "Now decide between the TOP TWO!";
2725                         mapvote_keeptwotime = 0;
2726                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2727                         result = strcat(result, ":", ftos(firstPlaceVotes));
2728                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2729                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2730                         didntvote = mapvote_voters;
2731                         for(i = 0; i < mapvote_count; ++i)
2732                                 if(mapvote_maps[i] != "")
2733                                 {
2734                                         didntvote -= mapvote_selections[i];
2735                                         if(i != firstPlace)
2736                                                 if(i != secondPlace)
2737                                                 {
2738                                                         result = strcat(result, ":", mapvote_maps[i]);
2739                                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2740                                                         if(i < mapvote_count_real)
2741                                                         {
2742                                                                 strunzone(mapvote_maps[i]);
2743                                                                 mapvote_maps[i] = "";
2744                                                                 strunzone(mapvote_maps_pakfile[i]);
2745                                                                 mapvote_maps_pakfile[i] = "";
2746                                                         }
2747                                                 }
2748                                 }
2749                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2750                         if(autocvar_sv_eventlog)
2751                                 GameLogEcho(result);
2752                 }
2753
2754         return FALSE;
2755 }
2756 void MapVote_Tick()
2757 {
2758         float keeptwo;
2759         float totalvotes;
2760
2761         keeptwo = mapvote_keeptwotime;
2762         MapVote_CheckRules_1(); // count
2763         if(MapVote_CheckRules_2()) // decide
2764                 return;
2765
2766         totalvotes = 0;
2767         FOR_EACH_REALCLIENT(other)
2768         {
2769                 // hide scoreboard again
2770                 if(other.health != 2342)
2771                 {
2772                         other.health = 2342;
2773                         other.impulse = 0;
2774                         if(clienttype(other) == CLIENTTYPE_REAL)
2775                         {
2776                                 msg_entity = other;
2777                                 WriteByte(MSG_ONE, SVC_FINALE);
2778                                 WriteString(MSG_ONE, "");
2779                         }
2780                 }
2781
2782                 // clear possibly invalid votes
2783                 if(mapvote_maps[other.mapvote - 1] == "")
2784                         other.mapvote = 0;
2785                 // use impulses as new vote
2786                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2787                         if(mapvote_maps[other.impulse - 1] != "")
2788                         {
2789                                 other.mapvote = other.impulse;
2790                                 MapVote_TouchVotes(other);
2791                         }
2792                 other.impulse = 0;
2793
2794                 if(other.mapvote)
2795                         ++totalvotes;
2796         }
2797
2798         MapVote_CheckRules_1(); // just count
2799 }
2800 void MapVote_Start()
2801 {
2802         if(mapvote_run)
2803                 return;
2804
2805         // wait for stats to be sent first
2806         if(!playerstats_waitforme)
2807                 return;
2808
2809         MapInfo_Enumerate();
2810         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2811                 mapvote_run = TRUE;
2812 }
2813 void MapVote_Think()
2814 {
2815         if(!mapvote_run)
2816                 return;
2817
2818         if(alreadychangedlevel)
2819                 return;
2820
2821         if(time < mapvote_nextthink)
2822                 return;
2823         //dprint("tick\n");
2824
2825         mapvote_nextthink = time + 0.5;
2826
2827         if(!mapvote_initialized)
2828         {
2829                 if(autocvar_rescan_pending == 1)
2830                 {
2831                         cvar_set("rescan_pending", "2");
2832                         localcmd("fs_rescan\nrescan_pending 3\n");
2833                         return;
2834                 }
2835                 else if(autocvar_rescan_pending == 2)
2836                 {
2837                         return;
2838                 }
2839                 else if(autocvar_rescan_pending == 3)
2840                 {
2841                         // now build missing mapinfo files
2842                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2843                                 return;
2844
2845                         // we're done, start the timer
2846                         cvar_set("rescan_pending", "0");
2847                 }
2848
2849                 mapvote_initialized = TRUE;
2850                 if(DoNextMapOverride(0))
2851                         return;
2852                 if(!autocvar_g_maplist_votable || player_count <= 0)
2853                 {
2854                         GotoNextMap(0);
2855                         return;
2856                 }
2857                 MapVote_Init();
2858         }
2859
2860         MapVote_Tick();
2861 }
2862
2863 string GotoMap(string m)
2864 {
2865         if(!MapInfo_CheckMap(m))
2866                 return "The map you chose is not available on this server.";
2867         cvar_set("nextmap", m);
2868         cvar_set("timelimit", "-1");
2869         if(mapvote_initialized || alreadychangedlevel)
2870         {
2871                 if(DoNextMapOverride(0))
2872                         return "Map switch initiated.";
2873                 else
2874                         return "Hm... no. For some reason I like THIS map more.";
2875         }
2876         else
2877                 return "Map switch will happen after scoreboard.";
2878 }
2879
2880
2881 void EndFrame()
2882 {
2883         float altime;
2884         FOR_EACH_REALCLIENT(self)
2885         {
2886                 if(self.classname == "spectator")
2887                 {
2888                         if(self.enemy.typehitsound)
2889                                 self.typehit_time = time;
2890                         else if(self.enemy.hitsound)
2891                                 self.hit_time = time;
2892                 }
2893                 else
2894                 {
2895                         if(self.typehitsound)
2896                                 self.typehit_time = time;
2897                         else if(self.hitsound)
2898                                 self.hit_time = time;
2899                 }
2900         }
2901         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2902         // add 1 frametime because after this, engine SV_Physics
2903         // increases time by a frametime and then networks the frame
2904         // add another frametime because client shows everything with
2905         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2906         // needed!
2907         FOR_EACH_CLIENT(self)
2908         {
2909                 self.hitsound = FALSE;
2910                 self.typehitsound = FALSE;
2911                 antilag_record(self, altime);
2912         }
2913 }
2914
2915
2916 /*
2917  * RedirectionThink:
2918  * returns TRUE if redirecting
2919  */
2920 float redirection_timeout;
2921 float redirection_nextthink;
2922 float RedirectionThink()
2923 {
2924         float clients_found;
2925
2926         if(redirection_target == "")
2927                 return FALSE;
2928
2929         if(!redirection_timeout)
2930         {
2931                 cvar_set("sv_public", "-2");
2932                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2933                 if(redirection_target == "self")
2934                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2935                 else
2936                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2937         }
2938
2939         if(time < redirection_nextthink)
2940                 return TRUE;
2941
2942         redirection_nextthink = time + 1;
2943
2944         clients_found = 0;
2945         FOR_EACH_REALCLIENT(self)
2946         {
2947                 // TODO add timer
2948                 print("Redirecting: sending connect command to ", self.netname, "\n");
2949                 if(redirection_target == "self")
2950                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2951                 else
2952                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2953                 ++clients_found;
2954         }
2955
2956         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2957
2958         if(time > redirection_timeout || clients_found == 0)
2959                 localcmd("\nwait; wait; wait; quit\n");
2960
2961         return TRUE;
2962 }
2963
2964 void TargetMusic_RestoreGame();
2965 void RestoreGame()
2966 {
2967         // Loaded from a save game
2968         // some things then break, so let's work around them...
2969
2970         // Progs DB (capture records)
2971         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2972
2973         // Mapinfo
2974         MapInfo_Shutdown();
2975         MapInfo_Enumerate();
2976         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2977         WeaponStats_Init();
2978
2979         TargetMusic_RestoreGame();
2980 }
2981
2982 void Shutdown()
2983 {
2984         entity e;
2985
2986         gameover = 2;
2987
2988         if(world_initialized > 0)
2989         {
2990                 world_initialized = 0;
2991                 print("Saving persistent data...\n");
2992                 Ban_SaveBans();
2993
2994                 PlayerStats_EndMatch(0);
2995                 FOR_EACH_CLIENT(e)
2996                         PlayerStats_AddGlobalInfo(e);
2997                 PlayerStats_Shutdown();
2998
2999                 if(!cheatcount_total)
3000                 {
3001                         if(autocvar_sv_db_saveasdump)
3002                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
3003                         else
3004                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
3005                 }
3006                 if(autocvar_developer)
3007                 {
3008                         if(autocvar_sv_db_saveasdump)
3009                                 db_dump(TemporaryDB, "server-temp.db");
3010                         else
3011                                 db_save(TemporaryDB, "server-temp.db");
3012                 }
3013                 CheatShutdown(); // must be after cheatcount check
3014                 db_close(ServerProgsDB);
3015                 db_close(TemporaryDB);
3016                 print("done!\n");
3017                 // tell the bot system the game is ending now
3018                 bot_endgame();
3019
3020                 WeaponStats_Shutdown();
3021                 MapInfo_Shutdown();
3022         }
3023         else if(world_initialized == 0)
3024         {
3025                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
3026         }
3027 }