]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Merge branch 'master' into Mario/vehicles
[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(IS_REAL_CLIENT(e))
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 = (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 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
55 string redirection_target;
56 float world_initialized;
57
58 string GetGametype();
59 void GotoNextMap(float reinit);
60 void ShuffleMaplist();
61 float(float reinit) DoNextMapOverride;
62
63 void SetDefaultAlpha()
64 {
65         if(autocvar_g_running_guns)
66         {
67                 default_player_alpha = -1;
68                 default_weapon_alpha = +1;
69         }
70         else if(g_cloaked)
71         {
72                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
73                 default_weapon_alpha = default_player_alpha;
74         }
75         else
76         {
77                 default_player_alpha = autocvar_g_player_alpha;
78                 if(default_player_alpha == 0)
79                         default_player_alpha = 1;
80                 default_weapon_alpha = default_player_alpha;
81         }
82 }
83
84 void GotoFirstMap()
85 {
86         float n;
87         if(autocvar__sv_init)
88         {
89                 // cvar_set("_sv_init", "0");
90                 // we do NOT set this to 0 any more, so someone "accidentally" changing
91                 // to this "init" map on a dedicated server will cause no permanent
92                 // harm
93                 if(autocvar_g_maplist_shuffle)
94                         ShuffleMaplist();
95                 n = tokenizebyseparator(autocvar_g_maplist, " ");
96                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
97
98                 MapInfo_Enumerate();
99                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
100
101                 if(!DoNextMapOverride(1))
102                         GotoNextMap(1);
103
104                 return;
105         }
106
107         if(time < 5)
108         {
109                 self.nextthink = time;
110         }
111         else
112         {
113                 self.nextthink = time + 1;
114                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
115         }
116 }
117
118 void cvar_changes_init()
119 {
120         float h;
121         string k, v, d;
122         float n, i, adding, pureadding;
123
124         if(cvar_changes)
125                 strunzone(cvar_changes);
126         cvar_changes = string_null;
127         if(cvar_purechanges)
128                 strunzone(cvar_purechanges);
129         cvar_purechanges = string_null;
130         cvar_purechanges_count = 0;
131
132         h = buf_create();
133         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
134         n = buf_getsize(h);
135
136         adding = TRUE;
137         pureadding = TRUE;
138
139         for(i = 0; i < n; ++i)
140         {
141                 k = bufstr_get(h, i);
142
143 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
144 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
145 #define BADCVAR(p) if(k == p) continue
146
147                 // general excludes and namespaces for server admin used cvars
148                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
149
150                 // internal
151                 BADPREFIX("csqc_");
152                 BADPREFIX("cvar_check_");
153                 BADCVAR("gamecfg");
154                 BADCVAR("g_configversion");
155                 BADCVAR("g_maplist_index");
156                 BADCVAR("halflifebsp");
157                 BADPREFIX("sv_world");
158
159                 // client
160                 BADPREFIX("chase_");
161                 BADPREFIX("cl_");
162                 BADPREFIX("con_");
163                 BADPREFIX("scoreboard_");
164                 BADPREFIX("g_campaign");
165                 BADPREFIX("g_waypointsprite_");
166                 BADPREFIX("gl_");
167                 BADPREFIX("joy");
168                 BADPREFIX("hud_");
169                 BADPREFIX("m_");
170                 BADPREFIX("menu_");
171                 BADPREFIX("net_slist_");
172                 BADPREFIX("r_");
173                 BADPREFIX("sbar_");
174                 BADPREFIX("scr_");
175                 BADPREFIX("snd_");
176                 BADPREFIX("show");
177                 BADPREFIX("sensitivity");
178                 BADPREFIX("userbind");
179                 BADPREFIX("v_");
180                 BADPREFIX("vid_");
181                 BADPREFIX("crosshair");
182                 BADCVAR("mod_q3bsp_lightmapmergepower");
183                 BADCVAR("mod_q3bsp_nolightmaps");
184                 BADCVAR("fov");
185                 BADCVAR("mastervolume");
186                 BADCVAR("volume");
187                 BADCVAR("bgmvolume");
188
189                 // private
190                 BADCVAR("developer");
191                 BADCVAR("log_dest_udp");
192                 BADCVAR("net_address");
193                 BADCVAR("net_address_ipv6");
194                 BADCVAR("port");
195                 BADCVAR("savedgamecfg");
196                 BADCVAR("serverconfig");
197                 BADCVAR("sv_autoscreenshot");
198                 BADCVAR("sv_heartbeatperiod");
199                 BADCVAR("sv_vote_master_password");
200                 BADCVAR("sys_colortranslation");
201                 BADCVAR("sys_specialcharactertranslation");
202                 BADCVAR("timeformat");
203                 BADCVAR("timestamps");
204                 BADPREFIX("developer_");
205                 BADPREFIX("g_ban_");
206                 BADPREFIX("g_banned_list");
207                 BADPREFIX("g_chat_flood_");
208                 BADPREFIX("g_ghost_items");
209                 BADPREFIX("g_playerstats_");
210                 BADPREFIX("g_respawn_ghosts");
211                 BADPREFIX("g_voice_flood_");
212                 BADPREFIX("log_file");
213                 BADPREFIX("rcon_");
214                 BADPREFIX("sv_allowdownloads");
215                 BADPREFIX("sv_autodemo");
216                 BADPREFIX("sv_curl_");
217                 BADPREFIX("sv_eventlog");
218                 BADPREFIX("sv_logscores_");
219                 BADPREFIX("sv_master");
220                 BADPREFIX("sv_weaponstats_");
221                 BADPREFIX("sv_waypointsprite_");
222                 BADCVAR("rescan_pending");
223
224                 // these can contain player IDs, so better hide
225                 BADPREFIX("g_forced_team_");
226
227                 // mapinfo
228                 BADCVAR("fraglimit");
229                 BADCVAR("g_assault");
230                 BADCVAR("g_ca");
231                 BADCVAR("g_ca_teams");
232                 BADCVAR("g_ctf");
233                 BADCVAR("g_cts");
234                 BADCVAR("g_dm");
235                 BADCVAR("g_domination");
236                 BADCVAR("g_domination_default_teams");
237                 BADCVAR("g_freezetag");
238                 BADCVAR("g_freezetag_teams");
239                 BADCVAR("g_keepaway");
240                 BADCVAR("g_keyhunt");
241                 BADCVAR("g_keyhunt_teams");
242                 BADCVAR("g_lms");
243                 BADCVAR("g_nexball");
244                 BADCVAR("g_onslaught");
245                 BADCVAR("g_race");
246                 BADCVAR("g_race_qualifying_timelimit");
247                 BADCVAR("g_tdm");
248                 BADCVAR("g_tdm_teams");
249                 BADCVAR("leadlimit");
250                 BADCVAR("nextmap");
251                 BADCVAR("teamplay");
252                 BADCVAR("timelimit");
253
254                 // long
255                 BADCVAR("hostname");
256                 BADCVAR("g_maplist");
257                 BADCVAR("g_maplist_mostrecent");
258                 BADCVAR("sv_motd");
259
260                 v = cvar_string(k);
261                 d = cvar_defstring(k);
262                 if(v == d)
263                         continue;
264
265                 if(adding)
266                 {
267                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
268                         if(strlen(cvar_changes) > 16384)
269                         {
270                                 cvar_changes = "// too many settings have been changed to show them here\n";
271                                 adding = 0;
272                         }
273                 }
274
275                 // now check if the changes are actually gameplay relevant
276
277                 // does nothing visible
278                 BADCVAR("captureleadlimit_override");
279                 BADCVAR("g_balance_kill_delay");
280                 BADCVAR("g_ca_point_leadlimit");
281                 BADCVAR("g_ctf_captimerecord_always");
282                 BADCVAR("g_ctf_flag_glowtrails");
283                 BADCVAR("g_ctf_flag_pickup_verbosename");
284                 BADCVAR("g_domination_point_leadlimit");
285                 BADCVAR("g_forced_respawn");
286                 BADCVAR("g_keyhunt_point_leadlimit");
287                 BADPREFIX("g_mod_");
288                 BADCVAR("g_nexball_goalleadlimit");
289                 BADCVAR("leadlimit_and_fraglimit");
290                 BADCVAR("leadlimit_override");
291                 BADCVAR("pausable");
292                 BADCVAR("sv_allow_fullbright");
293                 BADCVAR("sv_checkforpacketsduringsleep");
294                 BADCVAR("sv_fraginfo");
295                 BADCVAR("sv_timeout");
296                 BADPREFIX("sv_timeout_");
297                 BADPREFIX("crypto_");
298                 BADPREFIX("g_chat_");
299                 BADPREFIX("g_ctf_captimerecord_");
300                 BADPREFIX("g_maplist_votable_");
301                 BADPREFIX("net_");
302                 BADPREFIX("prvm_");
303                 BADPREFIX("skill_");
304                 BADPREFIX("sv_cullentities_");
305                 BADPREFIX("sv_fraginfo_");
306                 BADPREFIX("sv_maxidle_");
307                 BADPREFIX("sv_vote_");
308                 BADPREFIX("timelimit_");
309                 BADCVAR("gameversion");
310                 BADPREFIX("gameversion_");
311                 BADCVAR("sv_namechangetimer");
312
313                 // allowed changes to server admins (please sync this to server.cfg)
314                 // vi commands:
315                 //   :/"impure"/,$d
316                 //   :g!,^\/\/[^ /],d
317                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
318                 //   :%!sort
319                 // yes, this does contain some redundant stuff, don't really care
320                 BADCVAR("bot_config_file");
321                 BADCVAR("bot_number");
322                 BADCVAR("bot_prefix");
323                 BADCVAR("bot_suffix");
324                 BADCVAR("capturelimit_override");
325                 BADCVAR("fraglimit_override");
326                 BADCVAR("gametype");
327                 BADCVAR("g_antilag");
328                 BADCVAR("g_balance_teams");
329                 BADCVAR("g_balance_teams_prevent_imbalance");
330                 BADCVAR("g_balance_teams_scorefactor");
331                 BADCVAR("g_ban_sync_trusted_servers");
332                 BADCVAR("g_ban_sync_uri");
333                 BADCVAR("g_ca_teams_override");
334                 BADCVAR("g_ctf_ignore_frags");
335                 BADCVAR("g_domination_point_limit");
336                 BADCVAR("g_freezetag_teams_override");
337                 BADCVAR("g_friendlyfire");
338                 BADCVAR("g_fullbrightitems");
339                 BADCVAR("g_fullbrightplayers");
340                 BADCVAR("g_keyhunt_point_limit");
341                 BADCVAR("g_keyhunt_teams_override");
342                 BADCVAR("g_lms_lives_override");
343                 BADCVAR("g_maplist");
344                 BADCVAR("g_maplist_check_waypoints");
345                 BADCVAR("g_maplist_mostrecent_count");
346                 BADCVAR("g_maplist_shuffle");
347                 BADCVAR("g_maplist_votable");
348                 BADCVAR("g_maplist_votable_abstain");
349                 BADCVAR("g_maplist_votable_nodetail");
350                 BADCVAR("g_maplist_votable_suggestions");
351                 BADCVAR("g_maxplayers");
352                 BADCVAR("g_mirrordamage");
353                 BADCVAR("g_nexball_goallimit");
354                 BADCVAR("g_powerups");
355                 BADCVAR("g_start_delay");
356                 BADCVAR("g_warmup");
357                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
358                 BADCVAR("hostname");
359                 BADCVAR("log_file");
360                 BADCVAR("maxplayers");
361                 BADCVAR("minplayers");
362                 BADCVAR("net_address");
363                 BADCVAR("port");
364                 BADCVAR("rcon_password");
365                 BADCVAR("rcon_restricted_commands");
366                 BADCVAR("rcon_restricted_password");
367                 BADCVAR("skill");
368                 BADCVAR("sv_adminnick");
369                 BADCVAR("sv_autoscreenshot");
370                 BADCVAR("sv_autotaunt");
371                 BADCVAR("sv_curl_defaulturl");
372                 BADCVAR("sv_defaultcharacter");
373                 BADCVAR("sv_defaultplayercolors");
374                 BADCVAR("sv_defaultplayermodel");
375                 BADCVAR("sv_defaultplayerskin");
376                 BADCVAR("sv_maxidle");
377                 BADCVAR("sv_maxrate");
378                 BADCVAR("sv_motd");
379                 BADCVAR("sv_public");
380                 BADCVAR("sv_ready_restart");
381                 BADCVAR("sv_status_privacy");
382                 BADCVAR("sv_taunt");
383                 BADCVAR("sv_vote_call");
384                 BADCVAR("sv_vote_commands");
385                 BADCVAR("sv_vote_majority_factor");
386                 BADCVAR("sv_vote_master");
387                 BADCVAR("sv_vote_master_commands");
388                 BADCVAR("sv_vote_master_password");
389                 BADCVAR("sv_vote_simple_majority_factor");
390                 BADCVAR("teamplay_mode");
391                 BADCVAR("timelimit_override");
392                 BADCVAR("g_spawnshieldtime");
393                 BADPREFIX("g_warmup_");
394                 BADPREFIX("sv_ready_restart_");
395
396                 // mutators that announce themselves properly to the server browser
397                 BADCVAR("g_instagib");
398                 BADCVAR("g_new_toys");
399                 BADCVAR("g_nix");
400                 BADCVAR("g_grappling_hook");
401                 BADCVAR("g_jetpack");
402
403 #undef BADPREFIX
404 #undef BADCVAR
405
406                 if(pureadding)
407                 {
408                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
409                         if(strlen(cvar_purechanges) > 16384)
410                         {
411                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
412                                 pureadding = 0;
413                         }
414                 }
415                 ++cvar_purechanges_count;
416                 // WARNING: this variable is used for the server list
417                 // NEVER dare to skip this code!
418                 // Hacks to intentionally appearing as "pure server" even though you DO have
419                 // modified settings may be punished by removal from the server list.
420                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
421                 // though.
422         }
423         buf_del(h);
424         if(cvar_changes == "")
425                 cvar_changes = "// this server runs at default server settings\n";
426         else
427                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
428         cvar_changes = strzone(cvar_changes);
429         if(cvar_purechanges == "")
430                 cvar_purechanges = "// this server runs at default gameplay settings\n";
431         else
432                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
433         cvar_purechanges = strzone(cvar_purechanges);
434 }
435
436 void detect_maptype()
437 {
438 #if 0
439         vector o, v;
440         float i;
441
442         for(;;)
443         {
444                 o = world.mins;
445                 o_x += random() * (world.maxs_x - world.mins_x);
446                 o_y += random() * (world.maxs_y - world.mins_y);
447                 o_z += random() * (world.maxs_z - world.mins_z);
448
449                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
450                 if(trace_fraction == 1)
451                         continue;
452
453                 v = trace_endpos;
454
455                 for(i = 0; i < 64; i += 4)
456                 {
457                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
458         if(trace_fraction == 1)
459                 continue;
460                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
461                 }
462
463                 break;
464         }
465 #endif
466 }
467
468 entity randomseed;
469 float RandomSeed_Send(entity to, float sf)
470 {
471         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
472         WriteShort(MSG_ENTITY, self.cnt);
473         return TRUE;
474 }
475 void RandomSeed_Think()
476 {
477         self.cnt = bound(0, floor(random() * 65536), 65535);
478         self.nextthink = time + 5;
479
480         self.SendFlags |= 1;
481 }
482 void RandomSeed_Spawn()
483 {
484         randomseed = spawn();
485         randomseed.think = RandomSeed_Think;
486         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
487
488         entity oldself;
489         oldself = self;
490         self = randomseed;
491         self.think(); // sets random seed and nextthink
492         self = oldself;
493 }
494
495 void spawnfunc___init_dedicated_server(void)
496 {
497         // handler for _init/_init map (only for dedicated server initialization)
498
499         world_initialized = -1; // don't complain
500         cvar = cvar_normal;
501         cvar_string = cvar_string_normal;
502         cvar_set = cvar_set_normal;
503
504         remove = remove_unsafely;
505
506         entity e;
507         e = spawn();
508         e.think = GotoFirstMap;
509         e.nextthink = time; // this is usually 1 at this point
510
511         e = spawn();
512         e.classname = "info_player_deathmatch"; // safeguard against player joining
513
514         self.classname = "worldspawn"; // safeguard against various stuff ;)
515
516         // needs to be done so early because of the constants they create
517         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
518         CALL_ACCUMULATED_FUNCTION(RegisterVehicles);
519         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
520         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
521         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
522         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
523         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
524
525         MapInfo_Enumerate();
526         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
527 }
528
529 void Map_MarkAsRecent(string m);
530 float world_already_spawned;
531 void Nagger_Init();
532 void ClientInit_Spawn();
533 void WeaponStats_Init();
534 void WeaponStats_Shutdown();
535 void spawnfunc_worldspawn (void)
536 {
537         float fd, l, i, j, n;
538         string s;
539
540         cvar = cvar_normal;
541         cvar_string = cvar_string_normal;
542         cvar_set = cvar_set_normal;
543
544         if(world_already_spawned)
545                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
546         world_already_spawned = TRUE;
547
548         remove = remove_safely; // during spawning, watch what you remove!
549
550         cvar_changes_init(); // do this very early now so it REALLY matches the server config
551
552         compressShortVector_init();
553
554         entity head;
555         head = nextent(world);
556         maxclients = 0;
557         while(head)
558         {
559                 ++maxclients;
560                 head = nextent(head);
561         }
562
563         server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? TRUE : FALSE);
564
565         // needs to be done so early because of the constants they create
566         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
567         CALL_ACCUMULATED_FUNCTION(RegisterVehicles);
568         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
569         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
570         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
571         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
572         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
573
574         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
575
576         TemporaryDB = db_create();
577
578         // 0 normal
579         lightstyle(0, "m");
580
581         // 1 FLICKER (first variety)
582         lightstyle(1, "mmnmmommommnonmmonqnmmo");
583
584         // 2 SLOW STRONG PULSE
585         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
586
587         // 3 CANDLE (first variety)
588         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
589
590         // 4 FAST STROBE
591         lightstyle(4, "mamamamamama");
592
593         // 5 GENTLE PULSE 1
594         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
595
596         // 6 FLICKER (second variety)
597         lightstyle(6, "nmonqnmomnmomomno");
598
599         // 7 CANDLE (second variety)
600         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
601
602         // 8 CANDLE (third variety)
603         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
604
605         // 9 SLOW STROBE (fourth variety)
606         lightstyle(9, "aaaaaaaazzzzzzzz");
607
608         // 10 FLUORESCENT FLICKER
609         lightstyle(10, "mmamammmmammamamaaamammma");
610
611         // 11 SLOW PULSE NOT FADE TO BLACK
612         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
613
614         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
615
616         // 63 testing
617         lightstyle(63, "a");
618
619         if(autocvar_g_campaign)
620                 CampaignPreInit();
621
622         Map_MarkAsRecent(mapname);
623
624         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
625
626         precache_model ("null"); // we need this one before InitGameplayMode
627         InitGameplayMode();
628         readlevelcvars();
629         GrappleHookInit();
630
631         player_count = 0;
632         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
633         if(bot_waypoints_for_items == 1)
634                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
635                         bot_waypoints_for_items = 0;
636
637         precache();
638
639         WaypointSprite_Init();
640
641         GameLogInit(); // prepare everything
642         // NOTE for matchid:
643         // changing the logic generating it is okay. But:
644         // it HAS to stay <= 64 chars
645         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
646         if(autocvar_sv_eventlog)
647         {
648                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
649                 matchid = strzone(s);
650
651                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
652                 s = ":gameinfo:mutators:LIST";
653
654                 ret_string = s;
655                 MUTATOR_CALLHOOK(BuildMutatorsString);
656                 s = ret_string;
657
658                 // simple, probably not good in the mutator system
659                 if(autocvar_g_grappling_hook)
660                         s = strcat(s, ":grappling_hook");
661
662                 // initialiation stuff, not good in the mutator system
663                 if(!autocvar_g_use_ammunition)
664                         s = strcat(s, ":no_use_ammunition");
665
666                 // initialiation stuff, not good in the mutator system
667                 if(autocvar_g_pickup_items == 0)
668                         s = strcat(s, ":no_pickup_items");
669                 if(autocvar_g_pickup_items > 0)
670                         s = strcat(s, ":pickup_items");
671
672                 // initialiation stuff, not good in the mutator system
673                 if(autocvar_g_weaponarena != "0")
674                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
675
676                 // TODO to mutator system
677                 if(autocvar_g_norecoil)
678                         s = strcat(s, ":norecoil");
679
680                 // TODO to mutator system
681                 if(autocvar_g_powerups == 0)
682                         s = strcat(s, ":no_powerups");
683                 if(autocvar_g_powerups > 0)
684                         s = strcat(s, ":powerups");
685
686                 GameLogEcho(s);
687                 GameLogEcho(":gameinfo:end");
688         }
689         else
690                 matchid = strzone(ftos(random()));
691
692         cvar_set("nextmap", "");
693
694         SetDefaultAlpha();
695
696         if(autocvar_g_campaign)
697                 CampaignPostInit();
698
699         Ban_LoadBans();
700
701         MapInfo_Enumerate();
702         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
703
704         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
705         {
706                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
707                 if(fd != -1)
708                 {
709                         while((s = fgets(fd)))
710                         {
711                                 l = tokenize_console(s);
712                                 if(l < 2)
713                                         continue;
714                                 if(argv(0) == "cd")
715                                 {
716                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
717                                         print("  cdtrack ", argv(2), "\n");
718                                 }
719                                 else if(argv(0) == "fog")
720                                 {
721                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
722                                         print("  \"fog\" \"", s, "\"\n");
723                                 }
724                                 else if(argv(0) == "set")
725                                 {
726                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
727                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
728                                 }
729                                 else if(argv(0) != "//")
730                                 {
731                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
732                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
733                                 }
734                         }
735                         fclose(fd);
736                 }
737         }
738
739         WeaponStats_Init();
740
741         WepSet_AddStat();
742         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
743         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
744         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
745         addstat(STAT_ROUNDSTARTTIME, AS_FLOAT, stat_round_starttime);
746         addstat(STAT_ALLOW_OLDVORTEXBEAM, AS_INT, stat_allow_oldvortexbeam);
747         Nagger_Init();
748
749         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
750         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
751         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
752         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
753         addstat(STAT_FUEL, AS_INT, ammo_fuel);
754         addstat(STAT_PLASMA, AS_INT, ammo_plasma);
755         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
756         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
757         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
758         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
759         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
760         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
761         addstat(STAT_DAMAGE_DEALT_TOTAL, AS_INT, damage_dealt_total);
762         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
763         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
764
765         addstat(STAT_VORTEX_CHARGE, AS_FLOAT, vortex_charge);
766         addstat(STAT_VORTEX_CHARGEPOOL, AS_FLOAT, vortex_chargepool_ammo);
767
768         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
769         
770         addstat(STAT_ARC_HEAT, AS_FLOAT, arc_heat_percent);
771
772         // freeze attacks
773         addstat(STAT_FROZEN, AS_INT, frozen);
774         addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
775
776         // g_movementspeed hack
777         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
778         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
779         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
780         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
781
782         // secrets
783         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
784         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
785
786         // monsters
787         addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
788         addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
789
790         // misc
791         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
792
793         next_pingtime = time + 5;
794
795         detect_maptype();
796
797         // set up information replies for clients and server to use
798         maplist_reply = strzone(getmaplist());
799         lsmaps_reply = strzone(getlsmaps());
800         monsterlist_reply = strzone(getmonsterlist());
801         for(i = 0; i < 10; ++i)
802         {
803                 s = getrecords(i);
804                 if (s)
805                         records_reply[i] = strzone(s);
806         }
807         ladder_reply = strzone(getladder());
808         rankings_reply = strzone(getrankings());
809
810         // begin other init
811         ClientInit_Spawn();
812         RandomSeed_Spawn();
813         PingPLReport_Spawn();
814
815         CheatInit();
816
817         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
818
819         // fill sv_curl_serverpackages from .serverpackage files
820         if(autocvar_sv_curl_serverpackages_auto)
821         {
822                 s = "";
823                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
824                 for(i = 0; i < n; ++i)
825                         if(substring(argv(i), -18, -1) != "-serverpackage.txt")
826                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
827                                 s = strcat(s, " ", argv(i));
828                 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
829                 if(fd >= 0)
830                 {
831                         j = search_getsize(fd);
832                         for(i = 0; i < j; ++i)
833                                 s = strcat(s, " ", search_getfilename(fd, i));
834                         search_end(fd);
835                 }
836                 fd = search_begin("*.serverpackage", TRUE, FALSE);
837                 if(fd >= 0)
838                 {
839                         j = search_getsize(fd);
840                         for(i = 0; i < j; ++i)
841                                 s = strcat(s, " ", search_getfilename(fd, i));
842                         search_end(fd);
843                 }
844                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
845         }
846
847         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
848         modname = "Xonotic";
849         // physics/balance/config changes that count as mod
850         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
851                 modname = cvar_string("g_mod_physics");
852         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
853                 modname = cvar_string("g_mod_balance");
854         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
855                 modname = cvar_string("g_mod_config");
856         // extra mutators that deserve to count as mod
857         MUTATOR_CALLHOOK(SetModname);
858
859         // save it for later
860         modname = strzone(modname);
861
862         WinningConditionHelper(); // set worldstatus
863
864         world_initialized = 1;
865 }
866
867 void spawnfunc_light (void)
868 {
869         //makestatic (self); // Who the f___ did that?
870         remove(self);
871 }
872
873 string GetGametype()
874 {
875         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
876 }
877
878 string GetMapname()
879 {
880         return mapname;
881 }
882
883 float Map_Count, Map_Current;
884 string Map_Current_Name;
885
886 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
887 float GetMaplistPosition()
888 {
889         float pos, idx;
890         string map;
891
892         map = GetMapname();
893         idx = autocvar_g_maplist_index;
894
895         if(idx >= 0)
896                 if(idx < Map_Count)
897                         if(map == argv(idx))
898                                 return idx;
899
900         for(pos = 0; pos < Map_Count; ++pos)
901                 if(map == argv(pos))
902                         return pos;
903
904         // resume normal maplist rotation if current map is not in g_maplist
905         return idx;
906 }
907
908 float MapHasRightSize(string map)
909 {
910         float fh;
911         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
912         if(autocvar_g_maplist_check_waypoints)
913         {
914                 dprint("checkwp "); dprint(map);
915                 if(!fexists(strcat("maps/", map, ".waypoints")))
916                 {
917                         dprint(": no waypoints\n");
918                         return FALSE;
919                 }
920                 dprint(": has waypoints\n");
921         }
922
923         // open map size restriction file
924         dprint("opensize "); dprint(map);
925         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
926         if(fh >= 0)
927         {
928                 float mapmin, mapmax;
929                 dprint(": ok, ");
930                 mapmin = stof(fgets(fh));
931                 mapmax = stof(fgets(fh));
932                 fclose(fh);
933                 if(player_count < mapmin)
934                 {
935                         dprint("not enough\n");
936                         return FALSE;
937                 }
938                 if(player_count > mapmax)
939                 {
940                         dprint("too many\n");
941                         return FALSE;
942                 }
943                 dprint("right size\n");
944                 return TRUE;
945         }
946         dprint(": not found\n");
947         return TRUE;
948 }
949
950 string Map_Filename(float position)
951 {
952         return strcat("maps/", argv(position), ".bsp");
953 }
954
955 string strwords(string s, float w)
956 {
957         float endpos;
958         for(endpos = 0; w && endpos >= 0; --w)
959                 endpos = strstrofs(s, " ", endpos + 1);
960         if(endpos < 0)
961                 return s;
962         else
963                 return substring(s, 0, endpos);
964 }
965
966 float strhasword(string s, string w)
967 {
968         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
969 }
970
971 void Map_MarkAsRecent(string m)
972 {
973         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
974 }
975
976 float Map_IsRecent(string m)
977 {
978         return strhasword(autocvar_g_maplist_mostrecent, m);
979 }
980
981 float Map_Check(float position, float pass)
982 {
983         string filename;
984         string map_next;
985         map_next = argv(position);
986         if(pass <= 1)
987         {
988                 if(Map_IsRecent(map_next))
989                         return 0;
990         }
991         filename = Map_Filename(position);
992         if(MapInfo_CheckMap(map_next))
993         {
994                 if(pass == 2)
995                         return 1;
996                 if(MapHasRightSize(map_next))
997                         return 1;
998                 return 0;
999         }
1000         else
1001                 dprint( "Couldn't select '", filename, "'..\n" );
1002
1003         return 0;
1004 }
1005
1006 void Map_Goto_SetStr(string nextmapname)
1007 {
1008         if(getmapname_stored != "")
1009                 strunzone(getmapname_stored);
1010         if(nextmapname == "")
1011                 getmapname_stored = "";
1012         else
1013                 getmapname_stored = strzone(nextmapname);
1014 }
1015
1016 void Map_Goto_SetFloat(float position)
1017 {
1018         cvar_set("g_maplist_index", ftos(position));
1019         Map_Goto_SetStr(argv(position));
1020 }
1021
1022 void Map_Goto(float reinit)
1023 {
1024         MapInfo_LoadMap(getmapname_stored, reinit);
1025 }
1026
1027 // return codes of map selectors:
1028 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1029 //   -2 = permanent failure
1030 float() MaplistMethod_Iterate = // usual method
1031 {
1032         float pass, i;
1033
1034         dprint("Trying MaplistMethod_Iterate\n");
1035
1036         for(pass = 1; pass <= 2; ++pass)
1037         {
1038                 for(i = 1; i < Map_Count; ++i)
1039                 {
1040                         float mapindex;
1041                         mapindex = (i + Map_Current) % Map_Count;
1042                         if(Map_Check(mapindex, pass))
1043                                 return mapindex;
1044                 }
1045         }
1046         return -1;
1047 }
1048
1049 float() MaplistMethod_Repeat = // fallback method
1050 {
1051         dprint("Trying MaplistMethod_Repeat\n");
1052
1053         if(Map_Check(Map_Current, 2))
1054                 return Map_Current;
1055         return -2;
1056 }
1057
1058 float() MaplistMethod_Random = // random map selection
1059 {
1060         float i, imax;
1061
1062         dprint("Trying MaplistMethod_Random\n");
1063
1064         imax = 42;
1065
1066         for(i = 0; i <= imax; ++i)
1067         {
1068                 float mapindex;
1069                 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1070                 if(Map_Check(mapindex, 1))
1071                         return mapindex;
1072         }
1073         return -1;
1074 }
1075
1076 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1077 // the exponent sets a bias on the map selection:
1078 // the higher the exponent, the less likely "shortly repeated" same maps are
1079 {
1080         float i, j, imax, insertpos;
1081
1082         dprint("Trying MaplistMethod_Shuffle\n");
1083
1084         imax = 42;
1085
1086         for(i = 0; i <= imax; ++i)
1087         {
1088                 string newlist;
1089
1090                 // now reinsert this at another position
1091                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1092                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1093                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1094                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1095
1096                 // insert the current map there
1097                 newlist = "";
1098                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1099                         newlist = strcat(newlist, " ", argv(j));
1100                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1101                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1102                         newlist = strcat(newlist, " ", argv(j));
1103                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1104                 cvar_set("g_maplist", newlist);
1105                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1106
1107                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1108                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1109                 if(Map_Check(Map_Current, 1))
1110                         return Map_Current;
1111         }
1112         return -1;
1113 }
1114
1115 void Maplist_Init()
1116 {
1117         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1118         float i;
1119         for (i = 0; i < Map_Count; ++i)
1120                 if (Map_Check(i, 2))
1121                         break;
1122         if (i == Map_Count)
1123         {
1124                 bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
1125                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1126                 if(autocvar_g_maplist_shuffle)
1127                         ShuffleMaplist();
1128                 localcmd("\nmenu_cmd sync\n");
1129                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1130         }
1131         if(Map_Count == 0)
1132                 error("empty maplist, cannot select a new map");
1133         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1134
1135         if(Map_Current_Name)
1136                 strunzone(Map_Current_Name);
1137         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1138         // this may or may not be correct, but who cares, in the worst case a map
1139         // isn't chosen in the first pass that should have been
1140 }
1141
1142 string GetNextMap()
1143 {
1144         float nextMap;
1145
1146         Maplist_Init();
1147         nextMap = -1;
1148
1149         if(nextMap == -1)
1150                 if(autocvar_g_maplist_shuffle > 0)
1151                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1152
1153         if(nextMap == -1)
1154                 if(autocvar_g_maplist_selectrandom)
1155                         nextMap = MaplistMethod_Random();
1156
1157         if(nextMap == -1)
1158                 nextMap = MaplistMethod_Iterate();
1159
1160         if(nextMap == -1)
1161                 nextMap = MaplistMethod_Repeat();
1162
1163         if(nextMap >= 0)
1164         {
1165                 Map_Goto_SetFloat(nextMap);
1166                 return getmapname_stored;
1167         }
1168
1169         return "";
1170 }
1171
1172 float DoNextMapOverride(float reinit)
1173 {
1174         if(autocvar_g_campaign)
1175         {
1176                 CampaignPostIntermission();
1177                 alreadychangedlevel = TRUE;
1178                 return TRUE;
1179         }
1180         if(autocvar_quit_when_empty)
1181         {
1182                 if(player_count <= currentbots)
1183                 {
1184                         localcmd("quit\n");
1185                         alreadychangedlevel = TRUE;
1186                         return TRUE;
1187                 }
1188         }
1189         if(autocvar_quit_and_redirect != "")
1190         {
1191                 redirection_target = strzone(autocvar_quit_and_redirect);
1192                 alreadychangedlevel = TRUE;
1193                 return TRUE;
1194         }
1195         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1196         {
1197                 localcmd("restart\n");
1198                 alreadychangedlevel = TRUE;
1199                 return TRUE;
1200         }
1201         if(autocvar_nextmap != "")
1202         {
1203                 string m;
1204                 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1205                 cvar_set("nextmap",m);
1206         
1207                 if(!m || gametypevote)
1208                         return FALSE;
1209                 if(autocvar_sv_vote_gametype)
1210                 {
1211                         Map_Goto_SetStr(m);
1212                         return FALSE;
1213                 }
1214                 
1215                 if(MapInfo_CheckMap(m))
1216                 {
1217                         Map_Goto_SetStr(m);
1218                         Map_Goto(reinit);
1219                         alreadychangedlevel = TRUE;
1220                         return TRUE;
1221                 }
1222         }
1223         if(!reinit && autocvar_lastlevel)
1224         {
1225                 cvar_settemp_restore();
1226                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1227                 alreadychangedlevel = TRUE;
1228                 return TRUE;
1229         }
1230         return FALSE;
1231 }
1232
1233 void GotoNextMap(float reinit)
1234 {
1235         //string nextmap;
1236         //float n, nummaps;
1237         //string s;
1238         if (alreadychangedlevel)
1239                 return;
1240         alreadychangedlevel = TRUE;
1241
1242         string nextMap;
1243
1244         nextMap = GetNextMap();
1245         if(nextMap == "")
1246                 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1247         Map_Goto(reinit);
1248 }
1249
1250
1251 /*
1252 ============
1253 IntermissionThink
1254
1255 When the player presses attack or jump, change to the next level
1256 ============
1257 */
1258 .float autoscreenshot;
1259 void IntermissionThink()
1260 {
1261         FixIntermissionClient(self);
1262
1263         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1264         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1265
1266         if( (server_screenshot || client_screenshot)
1267                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1268         {
1269                 self.autoscreenshot = -1;
1270                 if(IS_REAL_CLIENT(self)) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(FALSE, "%s"))); }
1271                 return;
1272         }
1273
1274         if (time < intermission_exittime)
1275                 return;
1276
1277         if(!mapvote_initialized)
1278                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1279                         return;
1280
1281         MapVote_Start();
1282 }
1283
1284 /*
1285 ============
1286 FindIntermission
1287
1288 Returns the entity to view from
1289 ============
1290 */
1291 /*
1292 entity FindIntermission()
1293 {
1294         local   entity spot;
1295         local   float cyc;
1296
1297 // look for info_intermission first
1298         spot = find (world, classname, "info_intermission");
1299         if (spot)
1300         {       // pick a random one
1301                 cyc = random() * 4;
1302                 while (cyc > 1)
1303                 {
1304                         spot = find (spot, classname, "info_intermission");
1305                         if (!spot)
1306                                 spot = find (spot, classname, "info_intermission");
1307                         cyc = cyc - 1;
1308                 }
1309                 return spot;
1310         }
1311
1312 // then look for the start position
1313         spot = find (world, classname, "info_player_start");
1314         if (spot)
1315                 return spot;
1316
1317 // testinfo_player_start is only found in regioned levels
1318         spot = find (world, classname, "testplayerstart");
1319         if (spot)
1320                 return spot;
1321
1322 // then look for the start position
1323         spot = find (world, classname, "info_player_deathmatch");
1324         if (spot)
1325                 return spot;
1326
1327         //objerror ("FindIntermission: no spot");
1328         return world;
1329 }
1330 */
1331
1332 /*
1333 ===============================================================================
1334
1335 RULES
1336
1337 ===============================================================================
1338 */
1339
1340 void DumpStats(float final)
1341 {
1342         float file;
1343         string s;
1344         float to_console;
1345         float to_eventlog;
1346         float to_file;
1347         float i;
1348
1349         to_console = autocvar_sv_logscores_console;
1350         to_eventlog = autocvar_sv_eventlog;
1351         to_file = autocvar_sv_logscores_file;
1352
1353         if(!final)
1354         {
1355                 to_console = TRUE; // always print printstats replies
1356                 to_eventlog = FALSE; // but never print them to the event log
1357         }
1358
1359         if(to_eventlog)
1360                 if(autocvar_sv_eventlog_console)
1361                         to_console = FALSE; // otherwise we get the output twice
1362
1363         if(final)
1364                 s = ":scores:";
1365         else
1366                 s = ":status:";
1367         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1368
1369         if(to_console)
1370                 print(s, "\n");
1371         if(to_eventlog)
1372                 GameLogEcho(s);
1373
1374         file = -1;
1375         if(to_file)
1376         {
1377                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1378                 if(file == -1)
1379                         to_file = FALSE;
1380                 else
1381                         fputs(file, strcat(s, "\n"));
1382         }
1383
1384         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1385         if(to_console)
1386                 print(s, "\n");
1387         if(to_eventlog)
1388                 GameLogEcho(s);
1389         if(to_file)
1390                 fputs(file, strcat(s, "\n"));
1391
1392         FOR_EACH_CLIENT(other)
1393         {
1394                 if ((IS_REAL_CLIENT(other)) || (IS_BOT_CLIENT(other) && autocvar_sv_logscores_bots))
1395                 {
1396                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1397                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1398                         if(IS_PLAYER(other) || other.caplayer == 1 || g_lms)
1399                                 s = strcat(s, ftos(other.team), ":");
1400                         else
1401                                 s = strcat(s, "spectator:");
1402
1403                         if(to_console)
1404                                 print(s, other.netname, "\n");
1405                         if(to_eventlog)
1406                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1407                         if(to_file)
1408                                 fputs(file, strcat(s, other.netname, "\n"));
1409                 }
1410         }
1411
1412         if(teamplay)
1413         {
1414                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1415                 if(to_console)
1416                         print(s, "\n");
1417                 if(to_eventlog)
1418                         GameLogEcho(s);
1419                 if(to_file)
1420                         fputs(file, strcat(s, "\n"));
1421
1422                 for(i = 1; i < 16; ++i)
1423                 {
1424                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1425                         s = strcat(s, ":", ftos(i));
1426                         if(to_console)
1427                                 print(s, "\n");
1428                         if(to_eventlog)
1429                                 GameLogEcho(s);
1430                         if(to_file)
1431                                 fputs(file, strcat(s, "\n"));
1432                 }
1433         }
1434
1435         if(to_console)
1436                 print(":end\n");
1437         if(to_eventlog)
1438                 GameLogEcho(":end");
1439         if(to_file)
1440         {
1441                 fputs(file, ":end\n");
1442                 fclose(file);
1443         }
1444 }
1445
1446 void FixIntermissionClient(entity e)
1447 {
1448         string s;
1449         if(!e.autoscreenshot) // initial call
1450         {
1451                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1452                 e.health = -2342;
1453                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1454                 e.solid = SOLID_NOT;
1455                 e.movetype = MOVETYPE_NONE;
1456                 e.takedamage = DAMAGE_NO;
1457                 if(e.weaponentity)
1458                 {
1459                         e.weaponentity.effects = EF_NODRAW;
1460                         if (e.weaponentity.weaponentity)
1461                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1462                 }
1463                 if(IS_REAL_CLIENT(e))
1464                 {
1465                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1466                         s = autocvar_sv_intermission_cdtrack;
1467                         if(s != "")
1468                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1469                         msg_entity = e;
1470                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1471                 }
1472         }
1473 }
1474
1475 /*
1476 go to the next level for deathmatch
1477 only called if a time or frag limit has expired
1478 */
1479 void NextLevel()
1480 {
1481         gameover = TRUE;
1482
1483         intermission_running = 1;
1484
1485 // enforce a wait time before allowing changelevel
1486         if(player_count > 0)
1487                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1488         else
1489                 intermission_exittime = -1;
1490
1491         /*
1492         WriteByte (MSG_ALL, SVC_CDTRACK);
1493         WriteByte (MSG_ALL, 3);
1494         WriteByte (MSG_ALL, 3);
1495         // done in FixIntermission
1496         */
1497
1498         //pos = FindIntermission ();
1499
1500         VoteReset();
1501
1502         DumpStats(TRUE);
1503
1504         // send statistics
1505         PlayerStats_GameReport(TRUE);
1506         WeaponStats_Shutdown();
1507
1508         Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1509
1510         if(autocvar_sv_eventlog)
1511                 GameLogEcho(":gameover");
1512
1513         GameLogClose();
1514
1515         FOR_EACH_PLAYER(other) {
1516                 FixIntermissionClient(other);
1517                 if(other.winning)
1518                         bprint(other.netname, " ^7wins.\n");
1519         }
1520
1521         if(autocvar_g_campaign)
1522                 CampaignPreIntermission();
1523
1524         MUTATOR_CALLHOOK(MatchEnd);
1525
1526         localcmd("\nsv_hook_gameend\n");
1527 }
1528
1529 /*
1530 ============
1531 CheckRules_Player
1532
1533 Exit deathmatch games upon conditions
1534 ============
1535 */
1536 void CheckRules_Player()
1537 {
1538         if (gameover)   // someone else quit the game already
1539                 return;
1540
1541         if(self.deadflag == DEAD_NO)
1542                 self.play_time += frametime;
1543
1544         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1545         //   (div0: and that in CheckRules_World please)
1546 }
1547
1548 float checkrules_equality;
1549 float checkrules_suddendeathwarning;
1550 float checkrules_suddendeathend;
1551 float checkrules_overtimesadded; //how many overtimes have been already added
1552
1553 const float WINNING_NO = 0; // no winner, but time limits may terminate the game
1554 const float WINNING_YES = 1; // winner found
1555 const float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1556 const float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1557
1558 float InitiateSuddenDeath()
1559 {
1560         // Check first whether normal overtimes could be added before initiating suddendeath mode
1561         // - for this timelimit_overtime needs to be >0 of course
1562         // - also check the winning condition calculated in the previous frame and only add normal overtime
1563         //   again, if at the point at which timelimit would be extended again, still no winner was found
1564         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1565         {
1566                 return 1; // need to call InitiateOvertime later
1567         }
1568         else
1569         {
1570                 if(!checkrules_suddendeathend)
1571                 {
1572                         if(autocvar_g_campaign)
1573                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1574                         else
1575                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1576                         if(g_race && !g_race_qualifying)
1577                                 race_StartCompleting();
1578                 }
1579                 return 0;
1580         }
1581 }
1582
1583 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1584 {
1585         ++checkrules_overtimesadded;
1586         //add one more overtime by simply extending the timelimit
1587         float tl;
1588         tl = autocvar_timelimit;
1589         tl += autocvar_timelimit_overtime;
1590         cvar_set("timelimit", ftos(tl));
1591
1592         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1593 }
1594
1595 float GetWinningCode(float fraglimitreached, float equality)
1596 {
1597         if(autocvar_g_campaign == 1)
1598                 if(fraglimitreached)
1599                         return WINNING_YES;
1600                 else
1601                         return WINNING_NO;
1602
1603         else
1604                 if(equality)
1605                         if(fraglimitreached)
1606                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1607                         else
1608                                 return WINNING_NEVER;
1609                 else
1610                         if(fraglimitreached)
1611                                 return WINNING_YES;
1612                         else
1613                                 return WINNING_NO;
1614 }
1615
1616 // set the .winning flag for exactly those players with a given field value
1617 void SetWinners(.float field, float value)
1618 {
1619         entity head;
1620         FOR_EACH_PLAYER(head)
1621                 head.winning = (head.field == value);
1622 }
1623
1624 // set the .winning flag for those players with a given field value
1625 void AddWinners(.float field, float value)
1626 {
1627         entity head;
1628         FOR_EACH_PLAYER(head)
1629                 if(head.field == value)
1630                         head.winning = 1;
1631 }
1632
1633 // clear the .winning flags
1634 void ClearWinners(void)
1635 {
1636         entity head;
1637         FOR_EACH_PLAYER(head)
1638                 head.winning = 0;
1639 }
1640
1641 // Onslaught winning condition:
1642 // game terminates if only one team has a working generator (or none)
1643 float WinningCondition_Onslaught()
1644 {
1645         entity head;
1646         float t1, t2, t3, t4;
1647
1648         WinningConditionHelper(); // set worldstatus
1649
1650         if(warmup_stage)
1651                 return WINNING_NO;
1652
1653         // first check if the game has ended
1654         t1 = t2 = t3 = t4 = 0;
1655         head = find(world, classname, "onslaught_generator");
1656         while (head)
1657         {
1658                 if (head.health > 0)
1659                 {
1660                         if (head.team == NUM_TEAM_1) t1 = 1;
1661                         if (head.team == NUM_TEAM_2) t2 = 1;
1662                         if (head.team == NUM_TEAM_3) t3 = 1;
1663                         if (head.team == NUM_TEAM_4) t4 = 1;
1664                 }
1665                 head = find(head, classname, "onslaught_generator");
1666         }
1667         if (t1 + t2 + t3 + t4 < 2)
1668         {
1669                 // game over, only one team remains (or none)
1670                 ClearWinners();
1671                 if (t1) SetWinners(team, NUM_TEAM_1);
1672                 if (t2) SetWinners(team, NUM_TEAM_2);
1673                 if (t3) SetWinners(team, NUM_TEAM_3);
1674                 if (t4) SetWinners(team, NUM_TEAM_4);
1675                 dprint("Have a winner, ending game.\n");
1676                 return WINNING_YES;
1677         }
1678
1679         // Two or more teams remain
1680         return WINNING_NO;
1681 }
1682
1683 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1684 // they win. Otherwise the defending team wins once the timelimit passes.
1685 void assault_new_round();
1686 float WinningCondition_Assault()
1687 {
1688         float status;
1689
1690         WinningConditionHelper(); // set worldstatus
1691
1692         status = WINNING_NO;
1693         // as the timelimit has not yet passed just assume the defending team will win
1694         if(assault_attacker_team == NUM_TEAM_1)
1695         {
1696                 SetWinners(team, NUM_TEAM_2);
1697         }
1698         else
1699         {
1700                 SetWinners(team, NUM_TEAM_1);
1701         }
1702
1703         entity ent;
1704         ent = find(world, classname, "target_assault_roundend");
1705         if(ent)
1706         {
1707                 if(ent.winning) // round end has been triggered by attacking team
1708                 {
1709                         bprint("ASSAULT: round completed...\n");
1710                         SetWinners(team, assault_attacker_team);
1711
1712                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1713
1714                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1715                         {
1716                                 status = WINNING_YES;
1717                         }
1718                         else
1719                         {
1720                                 entity oldself;
1721                                 oldself = self;
1722                                 self = ent;
1723                                 assault_new_round();
1724                                 self = oldself;
1725                         }
1726                 }
1727         }
1728
1729         return status;
1730 }
1731
1732 // LMS winning condition: game terminates if and only if there's at most one
1733 // one player who's living lives. Top two scores being equal cancels the time
1734 // limit.
1735 float WinningCondition_LMS()
1736 {
1737         entity head, head2;
1738         float have_player;
1739         float have_players;
1740         float l;
1741
1742         have_player = FALSE;
1743         have_players = FALSE;
1744         l = LMS_NewPlayerLives();
1745
1746         head = find(world, classname, "player");
1747         if(head)
1748                 have_player = TRUE;
1749         head2 = find(head, classname, "player");
1750         if(head2)
1751                 have_players = TRUE;
1752
1753         if(have_player)
1754         {
1755                 // we have at least one player
1756                 if(have_players)
1757                 {
1758                         // two or more active players - continue with the game
1759                 }
1760                 else
1761                 {
1762                         // exactly one player?
1763
1764                         ClearWinners();
1765                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1766
1767                         if(l)
1768                         {
1769                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1770                                 return WINNING_NO;
1771                         }
1772                         else
1773                         {
1774                                 // a winner!
1775                                 // and assign him his first place
1776                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1777                                 return WINNING_YES;
1778                         }
1779                 }
1780         }
1781         else
1782         {
1783                 // nobody is playing at all...
1784                 if(l)
1785                 {
1786                         // wait for players...
1787                 }
1788                 else
1789                 {
1790                         // SNAFU (maybe a draw game?)
1791                         ClearWinners();
1792                         dprint("No players, ending game.\n");
1793                         return WINNING_YES;
1794                 }
1795         }
1796
1797         // When we get here, we have at least two players who are actually LIVING,
1798         // now check if the top two players have equal score.
1799         WinningConditionHelper();
1800
1801         ClearWinners();
1802         if(WinningConditionHelper_winner)
1803                 WinningConditionHelper_winner.winning = TRUE;
1804         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1805                 return WINNING_NEVER;
1806
1807         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1808         return WINNING_NO;
1809 }
1810
1811 void ShuffleMaplist()
1812 {
1813         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1814 }
1815
1816 float leaderfrags;
1817 float WinningCondition_Scores(float limit, float leadlimit)
1818 {
1819         float limitreached;
1820
1821         // TODO make everything use THIS winning condition (except LMS)
1822         WinningConditionHelper();
1823
1824         if(teamplay)
1825         {
1826                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1827                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1828                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1829                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1830         }
1831
1832         ClearWinners();
1833         if(WinningConditionHelper_winner)
1834                 WinningConditionHelper_winner.winning = 1;
1835         if(WinningConditionHelper_winnerteam >= 0)
1836                 SetWinners(team, WinningConditionHelper_winnerteam);
1837
1838         if(WinningConditionHelper_lowerisbetter)
1839         {
1840                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1841                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1842                 limit = -limit;
1843         }
1844
1845         if(WinningConditionHelper_zeroisworst)
1846                 leadlimit = 0; // not supported in this mode
1847
1848         if(g_dm || g_tdm || g_ca || g_freezetag || (g_race && !g_race_qualifying) || g_nexball)
1849         // these modes always score in increments of 1, thus this makes sense
1850         {
1851                 if(leaderfrags != WinningConditionHelper_topscore)
1852                 {
1853                         leaderfrags = WinningConditionHelper_topscore;
1854
1855                         if (limit)
1856                         if (leaderfrags == limit - 1)
1857                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1858                         else if (leaderfrags == limit - 2)
1859                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1860                         else if (leaderfrags == limit - 3)
1861                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1862                 }
1863         }
1864
1865         limitreached = FALSE;
1866         if(limit)
1867                 if(WinningConditionHelper_topscore >= limit)
1868                         limitreached = TRUE;
1869         if(leadlimit)
1870         {
1871                 float leadlimitreached;
1872                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1873                 if(autocvar_leadlimit_and_fraglimit)
1874                         limitreached = (limitreached && leadlimitreached);
1875                 else
1876                         limitreached = (limitreached || leadlimitreached);
1877         }
1878
1879         if(limit)
1880                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1881
1882         return GetWinningCode(
1883                 WinningConditionHelper_topscore && limitreached,
1884                 WinningConditionHelper_equality
1885         );
1886 }
1887
1888 float WinningCondition_Race(float fraglimit)
1889 {
1890         float wc;
1891         entity p;
1892         float n, c;
1893
1894         n = 0;
1895         c = 0;
1896         FOR_EACH_PLAYER(p)
1897         {
1898                 ++n;
1899                 if(p.race_completed)
1900                         ++c;
1901         }
1902         if(n && (n == c))
1903                 return WINNING_YES;
1904         wc = WinningCondition_Scores(fraglimit, 0);
1905
1906         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1907         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1908         // do NOT support equality when the laps are all raced!
1909                 return WINNING_STARTSUDDENDEATHOVERTIME;
1910         else
1911                 return WINNING_NEVER;
1912 }
1913
1914 float WinningCondition_QualifyingThenRace(float limit)
1915 {
1916         float wc;
1917         wc = WinningCondition_Scores(limit, 0);
1918
1919         // NEVER initiate overtime
1920         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1921         {
1922                 return WINNING_YES;
1923         }
1924
1925         return wc;
1926 }
1927
1928 float WinningCondition_RanOutOfSpawns()
1929 {
1930         entity head;
1931
1932         if(have_team_spawns <= 0)
1933                 return WINNING_NO;
1934
1935         if(autocvar_g_spawn_useallspawns <= 0)
1936                 return WINNING_NO;
1937
1938         if(!some_spawn_has_been_used)
1939                 return WINNING_NO;
1940
1941         team1_score = team2_score = team3_score = team4_score = 0;
1942
1943         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1944         {
1945                 if(head.team == NUM_TEAM_1)
1946                         team1_score = 1;
1947                 else if(head.team == NUM_TEAM_2)
1948                         team2_score = 1;
1949                 else if(head.team == NUM_TEAM_3)
1950                         team3_score = 1;
1951                 else if(head.team == NUM_TEAM_4)
1952                         team4_score = 1;
1953         }
1954
1955         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1956         {
1957                 if(head.team == NUM_TEAM_1)
1958                         team1_score = 1;
1959                 else if(head.team == NUM_TEAM_2)
1960                         team2_score = 1;
1961                 else if(head.team == NUM_TEAM_3)
1962                         team3_score = 1;
1963                 else if(head.team == NUM_TEAM_4)
1964                         team4_score = 1;
1965         }
1966
1967         ClearWinners();
1968         if(team1_score + team2_score + team3_score + team4_score == 0)
1969         {
1970                 checkrules_equality = TRUE;
1971                 return WINNING_YES;
1972         }
1973         else if(team1_score + team2_score + team3_score + team4_score == 1)
1974         {
1975                 float t, i;
1976                 if(team1_score)
1977                         t = NUM_TEAM_1;
1978                 else if(team2_score)
1979                         t = NUM_TEAM_2;
1980                 else if(team3_score)
1981                         t = NUM_TEAM_3;
1982                 else // if(team4_score)
1983                         t = NUM_TEAM_4;
1984                 CheckAllowedTeams(world);
1985                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1986                 {
1987                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
1988                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
1989                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
1990                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
1991                 }
1992
1993                 AddWinners(team, t);
1994                 return WINNING_YES;
1995         }
1996         else
1997                 return WINNING_NO;
1998 }
1999
2000 /*
2001 ============
2002 CheckRules_World
2003
2004 Exit deathmatch games upon conditions
2005 ============
2006 */
2007 void ReadyRestart();
2008 void CheckRules_World()
2009 {
2010         float timelimit;
2011         float fraglimit;
2012         float leadlimit;
2013
2014         VoteThink();
2015         MapVote_Think();
2016
2017         SetDefaultAlpha();
2018
2019         if (gameover)   // someone else quit the game already
2020         {
2021                 if(player_count == 0) // Nobody there? Then let's go to the next map
2022                         MapVote_Start();
2023                         // this will actually check the player count in the next frame
2024                         // again, but this shouldn't hurt
2025                 return;
2026         }
2027
2028         timelimit = autocvar_timelimit * 60;
2029         fraglimit = autocvar_fraglimit;
2030         leadlimit = autocvar_leadlimit;
2031
2032         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2033         {
2034                 if(timelimit > 0)
2035                         timelimit = 0; // timelimit is not made for warmup
2036                 if(fraglimit > 0)
2037                         fraglimit = 0; // no fraglimit for now
2038                 leadlimit = 0; // no leadlimit for now
2039         }
2040
2041         if(timelimit > 0)
2042         {
2043                 timelimit += game_starttime;
2044         }
2045         else if (timelimit < 0)
2046         {
2047                 // endmatch
2048                 NextLevel();
2049                 return;
2050         }
2051
2052         if(g_onslaught)
2053                 timelimit = 0; // ONS has its own overtime rule
2054
2055         float wantovertime;
2056         wantovertime = 0;
2057
2058         if(timelimit > game_starttime)
2059                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2060         else
2061                 game_completion_ratio = 0;
2062
2063         if(checkrules_suddendeathend)
2064         {
2065                 if(!checkrules_suddendeathwarning)
2066                 {
2067                         checkrules_suddendeathwarning = TRUE;
2068                         if(g_race && !g_race_qualifying)
2069                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_RACE_FINISHLAP);
2070                         else
2071                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_FRAG);
2072                 }
2073         }
2074         else
2075         {
2076                 if (timelimit && time >= timelimit)
2077                 {
2078                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2079                         {
2080                                 float totalplayers;
2081                                 float playerswithlaps;
2082                                 float readyplayers;
2083                                 entity head;
2084                                 totalplayers = playerswithlaps = readyplayers = 0;
2085                                 FOR_EACH_PLAYER(head)
2086                                 {
2087                                         ++totalplayers;
2088                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2089                                                 ++playerswithlaps;
2090                                         if(head.ready)
2091                                                 ++readyplayers;
2092                                 }
2093
2094                                 // at least 2 of the players have completed a lap: start the RACE
2095                                 // otherwise, the players should end the qualifying on their own
2096                                 if(readyplayers || playerswithlaps >= 2)
2097                                 {
2098                                         checkrules_suddendeathend = 0;
2099                                         ReadyRestart(); // go to race
2100                                         return;
2101                                 }
2102                                 else
2103                                         wantovertime |= InitiateSuddenDeath();
2104                         }
2105                         else
2106                                 wantovertime |= InitiateSuddenDeath();
2107                 }
2108         }
2109
2110         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2111         {
2112                 NextLevel();
2113                 return;
2114         }
2115
2116         float checkrules_status;
2117         checkrules_status = WinningCondition_RanOutOfSpawns();
2118         if(checkrules_status == WINNING_YES)
2119         {
2120                 bprint("Hey! Someone ran out of spawns!\n");
2121         }
2122         else if(g_race && !g_race_qualifying && timelimit >= 0)
2123         {
2124                 checkrules_status = WinningCondition_Race(fraglimit);
2125                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2126         }
2127         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2128         {
2129                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2130                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2131         }
2132         else if(g_assault)
2133         {
2134                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2135         }
2136         else if(g_lms)
2137         {
2138                 checkrules_status = WinningCondition_LMS();
2139         }
2140         else if (g_onslaught)
2141         {
2142                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2143         }
2144         else
2145         {
2146                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2147                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2148         }
2149
2150         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2151         {
2152                 checkrules_status = WINNING_NEVER;
2153                 checkrules_overtimesadded = -1;
2154                 wantovertime |= InitiateSuddenDeath();
2155         }
2156
2157         if(checkrules_status == WINNING_NEVER)
2158                 // equality cases! Nobody wins if the overtime ends in a draw.
2159                 ClearWinners();
2160
2161         if(wantovertime)
2162         {
2163                 if(checkrules_status == WINNING_NEVER)
2164                         InitiateOvertime();
2165                 else
2166                         checkrules_status = WINNING_YES;
2167         }
2168
2169         if(checkrules_suddendeathend)
2170                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2171                         checkrules_status = WINNING_YES;
2172
2173         if(checkrules_status == WINNING_YES)
2174         {
2175                 //print("WINNING\n");
2176                 NextLevel();
2177         }
2178 }
2179
2180 string GotoMap(string m)
2181 {
2182         m = GameTypeVote_MapInfo_FixName(m);
2183         if (!m)
2184                 return "The map you suggested is not available on this server.";
2185         if (!autocvar_sv_vote_gametype)
2186         if(!MapInfo_CheckMap(m))
2187                 return "The map you suggested does not support the current game mode.";
2188         cvar_set("nextmap", m);
2189         cvar_set("timelimit", "-1");
2190         if(mapvote_initialized || alreadychangedlevel)
2191         {
2192                 if(DoNextMapOverride(0))
2193                         return "Map switch initiated.";
2194                 else
2195                         return "Hm... no. For some reason I like THIS map more.";
2196         }
2197         else
2198                 return "Map switch will happen after scoreboard.";
2199 }
2200
2201
2202 void EndFrame()
2203 {
2204         anticheat_endframe();
2205
2206         float altime;
2207         FOR_EACH_REALCLIENT(self)
2208         {
2209                 entity e = IS_SPEC(self) ? self.enemy : self;
2210                 if(e.typehitsound)
2211                         self.typehit_time = time;
2212                 else if(e.damage_dealt)
2213                 {
2214                         self.hit_time = time;
2215                         self.damage_dealt_total += ceil(e.damage_dealt);
2216                 }
2217         }
2218         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2219         // add 1 frametime because after this, engine SV_Physics
2220         // increases time by a frametime and then networks the frame
2221         // add another frametime because client shows everything with
2222         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2223         // needed!
2224         FOR_EACH_CLIENT(self)
2225         {
2226                 self.typehitsound = FALSE;
2227                 self.damage_dealt = 0;
2228                 antilag_record(self, altime);
2229         }
2230         FOR_EACH_MONSTER(self)
2231                 antilag_record(self, altime);
2232 }
2233
2234
2235 /*
2236  * RedirectionThink:
2237  * returns TRUE if redirecting
2238  */
2239 float redirection_timeout;
2240 float redirection_nextthink;
2241 float RedirectionThink()
2242 {
2243         float clients_found;
2244
2245         if(redirection_target == "")
2246                 return FALSE;
2247
2248         if(!redirection_timeout)
2249         {
2250                 cvar_set("sv_public", "-2");
2251                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2252                 if(redirection_target == "self")
2253                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2254                 else
2255                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2256         }
2257
2258         if(time < redirection_nextthink)
2259                 return TRUE;
2260
2261         redirection_nextthink = time + 1;
2262
2263         clients_found = 0;
2264         FOR_EACH_REALCLIENT(self)
2265         {
2266                 // TODO add timer
2267                 print("Redirecting: sending connect command to ", self.netname, "\n");
2268                 if(redirection_target == "self")
2269                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2270                 else
2271                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2272                 ++clients_found;
2273         }
2274
2275         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2276
2277         if(time > redirection_timeout || clients_found == 0)
2278                 localcmd("\nwait; wait; wait; quit\n");
2279
2280         return TRUE;
2281 }
2282
2283 void TargetMusic_RestoreGame();
2284 void RestoreGame()
2285 {
2286         // Loaded from a save game
2287         // some things then break, so let's work around them...
2288
2289         // Progs DB (capture records)
2290         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2291
2292         // Mapinfo
2293         MapInfo_Shutdown();
2294         MapInfo_Enumerate();
2295         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2296         WeaponStats_Init();
2297
2298         TargetMusic_RestoreGame();
2299 }
2300
2301 void Shutdown()
2302 {
2303         gameover = 2;
2304
2305         if(world_initialized > 0)
2306         {
2307                 world_initialized = 0;
2308                 print("Saving persistent data...\n");
2309                 Ban_SaveBans();
2310
2311                 // playerstats with unfinished match
2312                 PlayerStats_GameReport(FALSE);
2313
2314                 if(!cheatcount_total)
2315                 {
2316                         if(autocvar_sv_db_saveasdump)
2317                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2318                         else
2319                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2320                 }
2321                 if(autocvar_developer)
2322                 {
2323                         if(autocvar_sv_db_saveasdump)
2324                                 db_dump(TemporaryDB, "server-temp.db");
2325                         else
2326                                 db_save(TemporaryDB, "server-temp.db");
2327                 }
2328                 CheatShutdown(); // must be after cheatcount check
2329                 db_close(ServerProgsDB);
2330                 db_close(TemporaryDB);
2331                 print("done!\n");
2332                 // tell the bot system the game is ending now
2333                 bot_endgame();
2334
2335                 WeaponStats_Shutdown();
2336                 MapInfo_Shutdown();
2337         }
2338         else if(world_initialized == 0)
2339         {
2340                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2341         }
2342 }