]> git.xonotic.org Git - xonotic/darkplaces.git/blob - sv_main.c
netconn: Move the timeout checks to new function SV_CheckTimeouts
[xonotic/darkplaces.git] / sv_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sv_main.c -- server main program
21
22 #include "quakedef.h"
23 #include "sv_demo.h"
24 #include "libcurl.h"
25 #include "csprogs.h"
26 #include "thread.h"
27
28 // current client
29 client_t *host_client;
30
31 static void SV_SaveEntFile_f(cmd_state_t *cmd);
32 static void SV_StartDownload_f(cmd_state_t *cmd);
33 static void SV_Download_f(cmd_state_t *cmd);
34 static void SV_VM_Setup(void);
35 extern cvar_t net_connecttimeout;
36
37 cvar_t sv_worldmessage = {CF_SERVER | CF_READONLY, "sv_worldmessage", "", "title of current level"};
38 cvar_t sv_worldname = {CF_SERVER | CF_READONLY, "sv_worldname", "", "name of current worldmodel"};
39 cvar_t sv_worldnamenoextension = {CF_SERVER | CF_READONLY, "sv_worldnamenoextension", "", "name of current worldmodel without extension"};
40 cvar_t sv_worldbasename = {CF_SERVER | CF_READONLY, "sv_worldbasename", "", "name of current worldmodel without maps/ prefix or extension"};
41
42 cvar_t sv_disablenotify = {CF_SERVER, "sv_disablenotify", "0", "suppress broadcast prints when certain cvars are changed (CF_NOTIFY flag in engine code)"};
43 cvar_t coop = {CF_SERVER, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
44 cvar_t deathmatch = {CF_SERVER, "deathmatch","0", "deathmatch mode, values depend on mod but typically 0 = no deathmatch, 1 = normal deathmatch with respawning weapons, 2 = weapons stay (players can only pick up new weapons)"};
45 cvar_t fraglimit = {CF_SERVER | CF_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
46 cvar_t gamecfg = {CF_SERVER, "gamecfg", "0", "unused cvar in quake, can be used by mods"};
47 cvar_t noexit = {CF_SERVER | CF_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
48 cvar_t nomonsters = {CF_SERVER, "nomonsters", "0", "unused cvar in quake, can be used by mods"};
49 cvar_t pausable = {CF_SERVER, "pausable","1", "allow players to pause or not (otherwise, only the server admin can)"};
50 cvar_t pr_checkextension = {CF_SERVER | CF_READONLY, "pr_checkextension", "1", "indicates to QuakeC that the standard quakec extensions system is available (if 0, quakec should not attempt to use extensions)"};
51 cvar_t samelevel = {CF_SERVER | CF_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
52 cvar_t skill = {CF_SERVER, "skill","1", "difficulty level of game, affects monster layouts in levels, 0 = easy, 1 = normal, 2 = hard, 3 = nightmare (same layout as hard but monsters fire twice)"};
53 cvar_t host_timescale = {CF_CLIENT | CF_SERVER, "host_timescale", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
54
55 cvar_t sv_accelerate = {CF_SERVER, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
56 cvar_t sv_aim = {CF_SERVER | CF_ARCHIVE, "sv_aim", "2", "maximum cosine angle for quake's vertical autoaim, a value above 1 completely disables the autoaim, quake used 0.93"};
57 cvar_t sv_airaccel_qw = {CF_SERVER, "sv_airaccel_qw", "1", "ratio of QW-style air control as opposed to simple acceleration; when < 0, the speed is clamped against the maximum allowed forward speed after the move"};
58 cvar_t sv_airaccel_qw_stretchfactor = {CF_SERVER, "sv_airaccel_qw_stretchfactor", "0", "when set, the maximum acceleration increase the player may get compared to forward-acceleration when strafejumping"};
59 cvar_t sv_airaccel_sideways_friction = {CF_SERVER, "sv_airaccel_sideways_friction", "", "anti-sideways movement stabilization (reduces speed gain when zigzagging); when < 0, only so much friction is applied that braking (by accelerating backwards) cannot be stronger"};
60 cvar_t sv_airaccelerate = {CF_SERVER, "sv_airaccelerate", "-1", "rate at which a player accelerates to sv_maxairspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
61 cvar_t sv_airstopaccelerate = {CF_SERVER, "sv_airstopaccelerate", "0", "when set, replacement for sv_airaccelerate when moving backwards"};
62 cvar_t sv_airspeedlimit_nonqw = {CF_SERVER, "sv_airspeedlimit_nonqw", "0", "when set, this is a soft speed limit while in air when using airaccel_qw not equal to 1"};
63 cvar_t sv_airstrafeaccelerate = {CF_SERVER, "sv_airstrafeaccelerate", "0", "when set, replacement for sv_airaccelerate when just strafing"};
64 cvar_t sv_maxairstrafespeed = {CF_SERVER, "sv_maxairstrafespeed", "0", "when set, replacement for sv_maxairspeed when just strafing"};
65 cvar_t sv_airstrafeaccel_qw = {CF_SERVER, "sv_airstrafeaccel_qw", "0", "when set, replacement for sv_airaccel_qw when just strafing"};
66 cvar_t sv_aircontrol = {CF_SERVER, "sv_aircontrol", "0", "CPMA-style air control"};
67 cvar_t sv_aircontrol_power = {CF_SERVER, "sv_aircontrol_power", "2", "CPMA-style air control exponent"};
68 cvar_t sv_aircontrol_penalty = {CF_SERVER, "sv_aircontrol_penalty", "0", "deceleration while using CPMA-style air control"};
69 cvar_t sv_allowdownloads = {CF_SERVER, "sv_allowdownloads", "1", "whether to allow clients to download files from the server (does not affect http downloads)"};
70 cvar_t sv_allowdownloads_archive = {CF_SERVER, "sv_allowdownloads_archive", "0", "whether to allow downloads of archives (pak/pk3)"};
71 cvar_t sv_allowdownloads_config = {CF_SERVER, "sv_allowdownloads_config", "0", "whether to allow downloads of config files (cfg)"};
72 cvar_t sv_allowdownloads_dlcache = {CF_SERVER, "sv_allowdownloads_dlcache", "0", "whether to allow downloads of dlcache files (dlcache/)"};
73 cvar_t sv_allowdownloads_inarchive = {CF_SERVER, "sv_allowdownloads_inarchive", "0", "whether to allow downloads from archives (pak/pk3)"};
74 cvar_t sv_areagrid_mingridsize = {CF_SERVER | CF_NOTIFY, "sv_areagrid_mingridsize", "128", "minimum areagrid cell size, smaller values work better for lots of small objects, higher values for large objects"};
75 cvar_t sv_checkforpacketsduringsleep = {CF_SERVER, "sv_checkforpacketsduringsleep", "0", "uses select() function to wait between frames which can be interrupted by packets being received, instead of Sleep()/usleep()/SDL_Sleep() functions which do not check for packets"};
76 cvar_t sv_clmovement_enable = {CF_SERVER, "sv_clmovement_enable", "1", "whether to allow clients to use cl_movement prediction, which can cause choppy movement on the server which may annoy other players"};
77 cvar_t sv_clmovement_minping = {CF_SERVER, "sv_clmovement_minping", "0", "if client ping is below this time in milliseconds, then their ability to use cl_movement prediction is disabled for a while (as they don't need it)"};
78 cvar_t sv_clmovement_minping_disabletime = {CF_SERVER, "sv_clmovement_minping_disabletime", "1000", "when client falls below minping, disable their prediction for this many milliseconds (should be at least 1000 or else their prediction may turn on/off frequently)"};
79 cvar_t sv_clmovement_inputtimeout = {CF_SERVER, "sv_clmovement_inputtimeout", "0.2", "when a client does not send input for this many seconds, force them to move anyway (unlike QuakeWorld)"};
80 cvar_t sv_cullentities_nevercullbmodels = {CF_SERVER, "sv_cullentities_nevercullbmodels", "0", "if enabled the clients are always notified of moving doors and lifts and other submodels of world (warning: eats a lot of network bandwidth on some levels!)"};
81 cvar_t sv_cullentities_pvs = {CF_SERVER, "sv_cullentities_pvs", "1", "fast but loose culling of hidden entities"};
82 cvar_t sv_cullentities_stats = {CF_SERVER, "sv_cullentities_stats", "0", "displays stats on network entities culled by various methods for each client"};
83 cvar_t sv_cullentities_trace = {CF_SERVER, "sv_cullentities_trace", "0", "somewhat slow but very tight culling of hidden entities, minimizes network traffic and makes wallhack cheats useless"};
84 cvar_t sv_cullentities_trace_delay = {CF_SERVER, "sv_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
85 cvar_t sv_cullentities_trace_delay_players = {CF_SERVER, "sv_cullentities_trace_delay_players", "0.2", "number of seconds until the entity gets actually culled if it is a player entity"};
86 cvar_t sv_cullentities_trace_enlarge = {CF_SERVER, "sv_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
87 cvar_t sv_cullentities_trace_expand = {CF_SERVER, "sv_cullentities_trace_expand", "0", "box is expanded by this many units for entity culling"};
88 cvar_t sv_cullentities_trace_eyejitter = {CF_SERVER, "sv_cullentities_trace_eyejitter", "16", "jitter the eye by this much for each trace"};
89 cvar_t sv_cullentities_trace_prediction = {CF_SERVER, "sv_cullentities_trace_prediction", "1", "also trace from the predicted player position"};
90 cvar_t sv_cullentities_trace_prediction_time = {CF_SERVER, "sv_cullentities_trace_prediction_time", "0.2", "how many seconds of prediction to use"};
91 cvar_t sv_cullentities_trace_entityocclusion = {CF_SERVER, "sv_cullentities_trace_entityocclusion", "0", "also check if doors and other bsp models are in the way"};
92 cvar_t sv_cullentities_trace_samples = {CF_SERVER, "sv_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
93 cvar_t sv_cullentities_trace_samples_extra = {CF_SERVER, "sv_cullentities_trace_samples_extra", "2", "number of samples to test for entity culling when the entity affects its surroundings by e.g. dlight"};
94 cvar_t sv_cullentities_trace_samples_players = {CF_SERVER, "sv_cullentities_trace_samples_players", "8", "number of samples to test for entity culling when the entity is a player entity"};
95 cvar_t sv_debugmove = {CF_SERVER | CF_NOTIFY, "sv_debugmove", "0", "disables collision detection optimizations for debugging purposes"};
96 cvar_t sv_echobprint = {CF_SERVER | CF_ARCHIVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
97 cvar_t sv_edgefriction = {CF_SERVER, "edgefriction", "1", "how much you slow down when nearing a ledge you might fall off, multiplier of sv_friction (Quake used 2, QuakeWorld used 1 due to a bug in physics code)"};
98 cvar_t sv_entpatch = {CF_SERVER, "sv_entpatch", "1", "enables loading of .ent files to override entities in the bsp (for example Threewave CTF server pack contains .ent patch files enabling play of CTF on id1 maps)"};
99 cvar_t sv_freezenonclients = {CF_SERVER | CF_NOTIFY, "sv_freezenonclients", "0", "freezes time, except for players, allowing you to walk around and take screenshots of explosions"};
100 cvar_t sv_friction = {CF_SERVER | CF_NOTIFY, "sv_friction","4", "how fast you slow down"};
101 cvar_t sv_gameplayfix_blowupfallenzombies = {CF_SERVER, "sv_gameplayfix_blowupfallenzombies", "1", "causes findradius to detect SOLID_NOT entities such as zombies and corpses on the floor, allowing splash damage to apply to them"};
102 cvar_t sv_gameplayfix_consistentplayerprethink = {CF_SERVER, "sv_gameplayfix_consistentplayerprethink", "0", "improves fairness in multiplayer by running all PlayerPreThink functions (which fire weapons) before performing physics, then running all PlayerPostThink functions"};
103 cvar_t sv_gameplayfix_delayprojectiles = {CF_SERVER, "sv_gameplayfix_delayprojectiles", "1", "causes entities to not move on the same frame they are spawned, meaning that projectiles wait until the next frame to perform their first move, giving proper interpolation and rocket trails, but making weapons harder to use at low framerates"};
104 cvar_t sv_gameplayfix_droptofloorstartsolid = {CF_SERVER, "sv_gameplayfix_droptofloorstartsolid", "1", "prevents items and monsters that start in a solid area from falling out of the level (makes droptofloor treat trace_startsolid as an acceptable outcome)"};
105 cvar_t sv_gameplayfix_droptofloorstartsolid_nudgetocorrect = {CF_SERVER, "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect", "1", "tries to nudge stuck items and monsters out of walls before droptofloor is performed"};
106 cvar_t sv_gameplayfix_easierwaterjump = {CF_SERVER, "sv_gameplayfix_easierwaterjump", "1", "changes water jumping to make it easier to get out of water (exactly like in QuakeWorld)"};
107 cvar_t sv_gameplayfix_findradiusdistancetobox = {CF_SERVER, "sv_gameplayfix_findradiusdistancetobox", "1", "causes findradius to check the distance to the corner of a box rather than the center of the box, makes findradius detect bmodels such as very large doors that would otherwise be unaffected by splash damage"};
108 cvar_t sv_gameplayfix_gravityunaffectedbyticrate = {CF_SERVER, "sv_gameplayfix_gravityunaffectedbyticrate", "0", "fix some ticrate issues in physics."};
109 cvar_t sv_gameplayfix_grenadebouncedownslopes = {CF_SERVER, "sv_gameplayfix_grenadebouncedownslopes", "1", "prevents MOVETYPE_BOUNCE (grenades) from getting stuck when fired down a downward sloping surface"};
110 cvar_t sv_gameplayfix_multiplethinksperframe = {CF_SERVER, "sv_gameplayfix_multiplethinksperframe", "1", "allows entities to think more often than the server framerate, primarily useful for very high fire rate weapons"};
111 cvar_t sv_gameplayfix_noairborncorpse = {CF_SERVER, "sv_gameplayfix_noairborncorpse", "1", "causes entities (corpses, items, etc) sitting ontop of moving entities (players) to fall when the moving entity (player) is no longer supporting them"};
112 cvar_t sv_gameplayfix_noairborncorpse_allowsuspendeditems = {CF_SERVER, "sv_gameplayfix_noairborncorpse_allowsuspendeditems", "1", "causes entities sitting ontop of objects that are instantaneously remove to float in midair (special hack to allow a common level design trick for floating items)"};
113 cvar_t sv_gameplayfix_nudgeoutofsolid = {CF_SERVER, "sv_gameplayfix_nudgeoutofsolid", "0", "attempts to fix physics errors (where an object ended up in solid for some reason)"};
114 cvar_t sv_gameplayfix_nudgeoutofsolid_separation = {CF_SERVER, "sv_gameplayfix_nudgeoutofsolid_separation", "0.03125", "keep objects this distance apart to prevent collision issues on seams"};
115 cvar_t sv_gameplayfix_q2airaccelerate = {CF_SERVER, "sv_gameplayfix_q2airaccelerate", "0", "Quake2-style air acceleration"};
116 cvar_t sv_gameplayfix_nogravityonground = {CF_SERVER, "sv_gameplayfix_nogravityonground", "0", "turn off gravity when on ground (to get rid of sliding)"};
117 cvar_t sv_gameplayfix_setmodelrealbox = {CF_SERVER, "sv_gameplayfix_setmodelrealbox", "1", "fixes a bug in Quake that made setmodel always set the entity box to ('-16 -16 -16', '16 16 16') rather than properly checking the model box, breaks some poorly coded mods"};
118 cvar_t sv_gameplayfix_slidemoveprojectiles = {CF_SERVER, "sv_gameplayfix_slidemoveprojectiles", "1", "allows MOVETYPE_FLY/FLYMISSILE/TOSS/BOUNCE/BOUNCEMISSILE entities to finish their move in a frame even if they hit something, fixes 'gravity accumulation' bug for grenades on steep slopes"};
119 cvar_t sv_gameplayfix_stepdown = {CF_SERVER, "sv_gameplayfix_stepdown", "0", "attempts to step down stairs, not just up them (prevents the familiar thud..thud..thud.. when running down stairs and slopes)"};
120 cvar_t sv_gameplayfix_stepmultipletimes = {CF_SERVER, "sv_gameplayfix_stepmultipletimes", "0", "applies step-up onto a ledge more than once in a single frame, when running quickly up stairs"};
121 cvar_t sv_gameplayfix_nostepmoveonsteepslopes = {CF_SERVER, "sv_gameplayfix_nostepmoveonsteepslopes", "0", "crude fix which prevents MOVETYPE_STEP (not swimming or flying) to move on slopes whose angle is bigger than 45 degree"};
122 cvar_t sv_gameplayfix_swiminbmodels = {CF_SERVER, "sv_gameplayfix_swiminbmodels", "1", "causes pointcontents (used to determine if you are in a liquid) to check bmodel entities as well as the world model, so you can swim around in (possibly moving) water bmodel entities"};
123 cvar_t sv_gameplayfix_upwardvelocityclearsongroundflag = {CF_SERVER, "sv_gameplayfix_upwardvelocityclearsongroundflag", "1", "prevents monsters, items, and most other objects from being stuck to the floor when pushed around by damage, and other situations in mods"};
124 cvar_t sv_gameplayfix_downtracesupportsongroundflag = {CF_SERVER, "sv_gameplayfix_downtracesupportsongroundflag", "1", "prevents very short moves from clearing onground (which may make the player stick to the floor at high netfps)"};
125 cvar_t sv_gameplayfix_q1bsptracelinereportstexture = {CF_SERVER, "sv_gameplayfix_q1bsptracelinereportstexture", "1", "enables mods to get accurate trace_texture results on q1bsp by using a surface-hitting traceline implementation rather than the standard solidbsp method, q3bsp always reports texture accurately"};
126 cvar_t sv_gameplayfix_unstickplayers = {CF_SERVER, "sv_gameplayfix_unstickplayers", "1", "big hack to try and fix the rare case of MOVETYPE_WALK entities getting stuck in the world clipping hull."};
127 cvar_t sv_gameplayfix_unstickentities = {CF_SERVER, "sv_gameplayfix_unstickentities", "1", "hack to check if entities are crossing world collision hull and try to move them to the right position"};
128 cvar_t sv_gameplayfix_fixedcheckwatertransition = {CF_SERVER, "sv_gameplayfix_fixedcheckwatertransition", "1", "fix two very stupid bugs in SV_CheckWaterTransition when watertype is CONTENTS_EMPTY (the bugs causes waterlevel to be 1 on first frame, -1 on second frame - the fix makes it 0 on both frames)"};
129 cvar_t sv_gameplayfix_customstats = {CF_SERVER, "sv_gameplayfix_customstats", "0", "Disable stats higher than 220, for use by certain games such as Xonotic"};
130 cvar_t sv_gravity = {CF_SERVER | CF_NOTIFY, "sv_gravity","800", "how fast you fall (512 = roughly earth gravity)"};
131 cvar_t sv_init_frame_count = {CF_SERVER, "sv_init_frame_count", "2", "number of frames to run to allow everything to settle before letting clients connect"};
132 cvar_t sv_idealpitchscale = {CF_SERVER, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
133 cvar_t sv_jumpstep = {CF_SERVER | CF_NOTIFY, "sv_jumpstep", "0", "whether you can step up while jumping"};
134 cvar_t sv_jumpvelocity = {CF_SERVER, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
135 cvar_t sv_maxairspeed = {CF_SERVER, "sv_maxairspeed", "30", "maximum speed a player can accelerate to when airborn (note that it is possible to completely stop by moving the opposite direction)"};
136 cvar_t sv_maxrate = {CF_SERVER | CF_ARCHIVE | CF_NOTIFY, "sv_maxrate", "1000000", "upper limit on client rate cvar, should reflect your network connection quality"};
137 cvar_t sv_maxspeed = {CF_SERVER | CF_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
138 cvar_t sv_maxvelocity = {CF_SERVER | CF_NOTIFY, "sv_maxvelocity","2000", "universal speed limit on all entities"};
139 cvar_t sv_nostep = {CF_SERVER | CF_NOTIFY, "sv_nostep","0", "prevents MOVETYPE_STEP entities (monsters) from moving"};
140 cvar_t sv_playerphysicsqc = {CF_SERVER | CF_NOTIFY, "sv_playerphysicsqc", "1", "enables QuakeC function to override player physics"};
141 cvar_t sv_progs = {CF_SERVER, "sv_progs", "progs.dat", "selects which quakec progs.dat file to run" };
142 cvar_t sv_protocolname = {CF_SERVER, "sv_protocolname", "DP7", "selects network protocol to host for (values include QUAKE, QUAKEDP, NEHAHRAMOVIE, DP1 and up)"};
143 cvar_t sv_random_seed = {CF_SERVER, "sv_random_seed", "", "random seed; when set, on every map start this random seed is used to initialize the random number generator. Don't touch it unless for benchmarking or debugging"};
144 cvar_t host_limitlocal = {CF_SERVER, "host_limitlocal", "0", "whether to apply rate limiting to the local player in a listen server (only useful for testing)"};
145 cvar_t sv_sound_land = {CF_SERVER, "sv_sound_land", "demon/dland2.wav", "sound to play when MOVETYPE_STEP entity hits the ground at high speed (empty cvar disables the sound)"};
146 cvar_t sv_sound_watersplash = {CF_SERVER, "sv_sound_watersplash", "misc/h2ohit1.wav", "sound to play when MOVETYPE_FLY/TOSS/BOUNCE/STEP entity enters or leaves water (empty cvar disables the sound)"};
147 cvar_t sv_stepheight = {CF_SERVER | CF_NOTIFY, "sv_stepheight", "18", "how high you can step up (TW_SV_STEPCONTROL extension)"};
148 cvar_t sv_stopspeed = {CF_SERVER | CF_NOTIFY, "sv_stopspeed","100", "how fast you come to a complete stop"};
149 cvar_t sv_wallfriction = {CF_SERVER | CF_NOTIFY, "sv_wallfriction", "1", "how much you slow down when sliding along a wall"};
150 cvar_t sv_wateraccelerate = {CF_SERVER, "sv_wateraccelerate", "-1", "rate at which a player accelerates to sv_maxspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
151 cvar_t sv_waterfriction = {CF_SERVER | CF_NOTIFY, "sv_waterfriction","-1", "how fast you slow down, if less than 0 the sv_friction variable is used instead"};
152 cvar_t sv_warsowbunny_airforwardaccel = {CF_SERVER, "sv_warsowbunny_airforwardaccel", "1.00001", "how fast you accelerate until you reach sv_maxspeed"};
153 cvar_t sv_warsowbunny_accel = {CF_SERVER, "sv_warsowbunny_accel", "0.1585", "how fast you accelerate until after reaching sv_maxspeed (it gets harder as you near sv_warsowbunny_topspeed)"};
154 cvar_t sv_warsowbunny_topspeed = {CF_SERVER, "sv_warsowbunny_topspeed", "925", "soft speed limit (can get faster with rjs and on ramps)"};
155 cvar_t sv_warsowbunny_turnaccel = {CF_SERVER, "sv_warsowbunny_turnaccel", "0", "max sharpness of turns (also master switch for the sv_warsowbunny_* mode; set this to 9 to enable)"};
156 cvar_t sv_warsowbunny_backtosideratio = {CF_SERVER, "sv_warsowbunny_backtosideratio", "0.8", "lower values make it easier to change direction without losing speed; the drawback is \"understeering\" in sharp turns"};
157 cvar_t sv_onlycsqcnetworking = {CF_SERVER, "sv_onlycsqcnetworking", "0", "disables legacy entity networking code for higher performance (except on clients, which can still be legacy)"};
158 cvar_t sv_areadebug = {CF_SERVER, "sv_areadebug", "0", "disables physics culling for debugging purposes (only for development)"};
159 cvar_t sys_ticrate = {CF_SERVER | CF_ARCHIVE, "sys_ticrate","0.0138889", "how long a server frame is in seconds, 0.05 is 20fps server rate, 0.1 is 10fps (can not be set higher than 0.1), 0 runs as many server frames as possible (makes games against bots a little smoother, overwhelms network players), 0.0138889 matches QuakeWorld physics"};
160 cvar_t teamplay = {CF_SERVER | CF_NOTIFY, "teamplay","0", "teamplay mode, values depend on mod but typically 0 = no teams, 1 = no team damage no self damage, 2 = team damage and self damage, some mods support 3 = no team damage but can damage self"};
161 cvar_t timelimit = {CF_SERVER | CF_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
162 cvar_t sv_threaded = {CF_SERVER, "sv_threaded", "0", "enables a separate thread for server code, improving performance, especially when hosting a game while playing, EXPERIMENTAL, may be crashy"};
163
164 cvar_t sv_rollspeed = {CF_CLIENT, "sv_rollspeed", "200", "how much strafing is necessary to tilt the view"};
165 cvar_t sv_rollangle = {CF_CLIENT, "sv_rollangle", "2.0", "how much to tilt the view when strafing"};
166
167 cvar_t saved1 = {CF_SERVER | CF_ARCHIVE, "saved1", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
168 cvar_t saved2 = {CF_SERVER | CF_ARCHIVE, "saved2", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
169 cvar_t saved3 = {CF_SERVER | CF_ARCHIVE, "saved3", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
170 cvar_t saved4 = {CF_SERVER | CF_ARCHIVE, "saved4", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
171 cvar_t savedgamecfg = {CF_SERVER | CF_ARCHIVE, "savedgamecfg", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
172 cvar_t scratch1 = {CF_SERVER, "scratch1", "0", "unused cvar in quake, can be used by mods"};
173 cvar_t scratch2 = {CF_SERVER,"scratch2", "0", "unused cvar in quake, can be used by mods"};
174 cvar_t scratch3 = {CF_SERVER, "scratch3", "0", "unused cvar in quake, can be used by mods"};
175 cvar_t scratch4 = {CF_SERVER, "scratch4", "0", "unused cvar in quake, can be used by mods"};
176 cvar_t temp1 = {CF_SERVER, "temp1","0", "general cvar for mods to use, in stock id1 this selects which death animation to use on players (0 = random death, other values select specific death scenes)"};
177
178 cvar_t nehx00 = {CF_SERVER, "nehx00", "0", "nehahra data storage cvar (used in singleplayer)"};
179 cvar_t nehx01 = {CF_SERVER, "nehx01", "0", "nehahra data storage cvar (used in singleplayer)"};
180 cvar_t nehx02 = {CF_SERVER, "nehx02", "0", "nehahra data storage cvar (used in singleplayer)"};
181 cvar_t nehx03 = {CF_SERVER, "nehx03", "0", "nehahra data storage cvar (used in singleplayer)"};
182 cvar_t nehx04 = {CF_SERVER, "nehx04", "0", "nehahra data storage cvar (used in singleplayer)"};
183 cvar_t nehx05 = {CF_SERVER, "nehx05", "0", "nehahra data storage cvar (used in singleplayer)"};
184 cvar_t nehx06 = {CF_SERVER, "nehx06", "0", "nehahra data storage cvar (used in singleplayer)"};
185 cvar_t nehx07 = {CF_SERVER, "nehx07", "0", "nehahra data storage cvar (used in singleplayer)"};
186 cvar_t nehx08 = {CF_SERVER, "nehx08", "0", "nehahra data storage cvar (used in singleplayer)"};
187 cvar_t nehx09 = {CF_SERVER, "nehx09", "0", "nehahra data storage cvar (used in singleplayer)"};
188 cvar_t nehx10 = {CF_SERVER, "nehx10", "0", "nehahra data storage cvar (used in singleplayer)"};
189 cvar_t nehx11 = {CF_SERVER, "nehx11", "0", "nehahra data storage cvar (used in singleplayer)"};
190 cvar_t nehx12 = {CF_SERVER, "nehx12", "0", "nehahra data storage cvar (used in singleplayer)"};
191 cvar_t nehx13 = {CF_SERVER, "nehx13", "0", "nehahra data storage cvar (used in singleplayer)"};
192 cvar_t nehx14 = {CF_SERVER, "nehx14", "0", "nehahra data storage cvar (used in singleplayer)"};
193 cvar_t nehx15 = {CF_SERVER, "nehx15", "0", "nehahra data storage cvar (used in singleplayer)"};
194 cvar_t nehx16 = {CF_SERVER, "nehx16", "0", "nehahra data storage cvar (used in singleplayer)"};
195 cvar_t nehx17 = {CF_SERVER, "nehx17", "0", "nehahra data storage cvar (used in singleplayer)"};
196 cvar_t nehx18 = {CF_SERVER, "nehx18", "0", "nehahra data storage cvar (used in singleplayer)"};
197 cvar_t nehx19 = {CF_SERVER, "nehx19", "0", "nehahra data storage cvar (used in singleplayer)"};
198 cvar_t cutscene = {CF_SERVER, "cutscene", "1", "enables cutscenes in nehahra, can be used by other mods"};
199
200 cvar_t sv_autodemo_perclient = {CF_SERVER | CF_ARCHIVE, "sv_autodemo_perclient", "0", "set to 1 to enable autorecorded per-client demos (they'll start to record at the beginning of a match); set it to 2 to also record client->server packets (for debugging)"};
201 cvar_t sv_autodemo_perclient_nameformat = {CF_SERVER | CF_ARCHIVE, "sv_autodemo_perclient_nameformat", "sv_autodemos/%Y-%m-%d_%H-%M", "The format of the sv_autodemo_perclient filename, followed by the map name, the client number and the IP address + port number, separated by underscores (the date is encoded using strftime escapes)" };
202 cvar_t sv_autodemo_perclient_discardable = {CF_SERVER | CF_ARCHIVE, "sv_autodemo_perclient_discardable", "0", "Allow game code to decide whether a demo should be kept or discarded."};
203
204 cvar_t halflifebsp = {CF_SERVER, "halflifebsp", "0", "indicates the current map is hlbsp format (useful to know because of different bounding box sizes)"};
205 cvar_t sv_mapformat_is_quake2 = {CF_SERVER, "sv_mapformat_is_quake2", "0", "indicates the current map is q2bsp format (useful to know because of different entity behaviors, .frame on submodels and other things)"};
206 cvar_t sv_mapformat_is_quake3 = {CF_SERVER, "sv_mapformat_is_quake3", "0", "indicates the current map is q2bsp format (useful to know because of different entity behaviors)"};
207
208 server_t sv;
209 server_static_t svs;
210
211 mempool_t *sv_mempool = NULL;
212
213 extern cvar_t host_timescale;
214 extern float            scr_centertime_off;
215
216 // MUST match effectnameindex_t in client.h
217 static const char *standardeffectnames[EFFECT_TOTAL] =
218 {
219         "",
220         "TE_GUNSHOT",
221         "TE_GUNSHOTQUAD",
222         "TE_SPIKE",
223         "TE_SPIKEQUAD",
224         "TE_SUPERSPIKE",
225         "TE_SUPERSPIKEQUAD",
226         "TE_WIZSPIKE",
227         "TE_KNIGHTSPIKE",
228         "TE_EXPLOSION",
229         "TE_EXPLOSIONQUAD",
230         "TE_TAREXPLOSION",
231         "TE_TELEPORT",
232         "TE_LAVASPLASH",
233         "TE_SMALLFLASH",
234         "TE_FLAMEJET",
235         "EF_FLAME",
236         "TE_BLOOD",
237         "TE_SPARK",
238         "TE_PLASMABURN",
239         "TE_TEI_G3",
240         "TE_TEI_SMOKE",
241         "TE_TEI_BIGEXPLOSION",
242         "TE_TEI_PLASMAHIT",
243         "EF_STARDUST",
244         "TR_ROCKET",
245         "TR_GRENADE",
246         "TR_BLOOD",
247         "TR_WIZSPIKE",
248         "TR_SLIGHTBLOOD",
249         "TR_KNIGHTSPIKE",
250         "TR_VORESPIKE",
251         "TR_NEHAHRASMOKE",
252         "TR_NEXUIZPLASMA",
253         "TR_GLOWTRAIL",
254         "SVC_PARTICLE"
255 };
256
257 #define SV_REQFUNCS 0
258 #define sv_reqfuncs NULL
259
260 //#define SV_REQFUNCS (sizeof(sv_reqfuncs) / sizeof(const char *))
261 //static const char *sv_reqfuncs[] = {
262 //};
263
264 #define SV_REQFIELDS (sizeof(sv_reqfields) / sizeof(prvm_required_field_t))
265
266 prvm_required_field_t sv_reqfields[] =
267 {
268 #define PRVM_DECLARE_serverglobalfloat(x)
269 #define PRVM_DECLARE_serverglobalvector(x)
270 #define PRVM_DECLARE_serverglobalstring(x)
271 #define PRVM_DECLARE_serverglobaledict(x)
272 #define PRVM_DECLARE_serverglobalfunction(x)
273 #define PRVM_DECLARE_clientglobalfloat(x)
274 #define PRVM_DECLARE_clientglobalvector(x)
275 #define PRVM_DECLARE_clientglobalstring(x)
276 #define PRVM_DECLARE_clientglobaledict(x)
277 #define PRVM_DECLARE_clientglobalfunction(x)
278 #define PRVM_DECLARE_menuglobalfloat(x)
279 #define PRVM_DECLARE_menuglobalvector(x)
280 #define PRVM_DECLARE_menuglobalstring(x)
281 #define PRVM_DECLARE_menuglobaledict(x)
282 #define PRVM_DECLARE_menuglobalfunction(x)
283 #define PRVM_DECLARE_serverfieldfloat(x) {ev_float, #x},
284 #define PRVM_DECLARE_serverfieldvector(x) {ev_vector, #x},
285 #define PRVM_DECLARE_serverfieldstring(x) {ev_string, #x},
286 #define PRVM_DECLARE_serverfieldedict(x) {ev_entity, #x},
287 #define PRVM_DECLARE_serverfieldfunction(x) {ev_function, #x},
288 #define PRVM_DECLARE_clientfieldfloat(x)
289 #define PRVM_DECLARE_clientfieldvector(x)
290 #define PRVM_DECLARE_clientfieldstring(x)
291 #define PRVM_DECLARE_clientfieldedict(x)
292 #define PRVM_DECLARE_clientfieldfunction(x)
293 #define PRVM_DECLARE_menufieldfloat(x)
294 #define PRVM_DECLARE_menufieldvector(x)
295 #define PRVM_DECLARE_menufieldstring(x)
296 #define PRVM_DECLARE_menufieldedict(x)
297 #define PRVM_DECLARE_menufieldfunction(x)
298 #define PRVM_DECLARE_serverfunction(x)
299 #define PRVM_DECLARE_clientfunction(x)
300 #define PRVM_DECLARE_menufunction(x)
301 #define PRVM_DECLARE_field(x)
302 #define PRVM_DECLARE_global(x)
303 #define PRVM_DECLARE_function(x)
304 #include "prvm_offsets.h"
305 #undef PRVM_DECLARE_serverglobalfloat
306 #undef PRVM_DECLARE_serverglobalvector
307 #undef PRVM_DECLARE_serverglobalstring
308 #undef PRVM_DECLARE_serverglobaledict
309 #undef PRVM_DECLARE_serverglobalfunction
310 #undef PRVM_DECLARE_clientglobalfloat
311 #undef PRVM_DECLARE_clientglobalvector
312 #undef PRVM_DECLARE_clientglobalstring
313 #undef PRVM_DECLARE_clientglobaledict
314 #undef PRVM_DECLARE_clientglobalfunction
315 #undef PRVM_DECLARE_menuglobalfloat
316 #undef PRVM_DECLARE_menuglobalvector
317 #undef PRVM_DECLARE_menuglobalstring
318 #undef PRVM_DECLARE_menuglobaledict
319 #undef PRVM_DECLARE_menuglobalfunction
320 #undef PRVM_DECLARE_serverfieldfloat
321 #undef PRVM_DECLARE_serverfieldvector
322 #undef PRVM_DECLARE_serverfieldstring
323 #undef PRVM_DECLARE_serverfieldedict
324 #undef PRVM_DECLARE_serverfieldfunction
325 #undef PRVM_DECLARE_clientfieldfloat
326 #undef PRVM_DECLARE_clientfieldvector
327 #undef PRVM_DECLARE_clientfieldstring
328 #undef PRVM_DECLARE_clientfieldedict
329 #undef PRVM_DECLARE_clientfieldfunction
330 #undef PRVM_DECLARE_menufieldfloat
331 #undef PRVM_DECLARE_menufieldvector
332 #undef PRVM_DECLARE_menufieldstring
333 #undef PRVM_DECLARE_menufieldedict
334 #undef PRVM_DECLARE_menufieldfunction
335 #undef PRVM_DECLARE_serverfunction
336 #undef PRVM_DECLARE_clientfunction
337 #undef PRVM_DECLARE_menufunction
338 #undef PRVM_DECLARE_field
339 #undef PRVM_DECLARE_global
340 #undef PRVM_DECLARE_function
341 };
342
343 #define SV_REQGLOBALS (sizeof(sv_reqglobals) / sizeof(prvm_required_field_t))
344
345 prvm_required_field_t sv_reqglobals[] =
346 {
347 #define PRVM_DECLARE_serverglobalfloat(x) {ev_float, #x},
348 #define PRVM_DECLARE_serverglobalvector(x) {ev_vector, #x},
349 #define PRVM_DECLARE_serverglobalstring(x) {ev_string, #x},
350 #define PRVM_DECLARE_serverglobaledict(x) {ev_entity, #x},
351 #define PRVM_DECLARE_serverglobalfunction(x) {ev_function, #x},
352 #define PRVM_DECLARE_clientglobalfloat(x)
353 #define PRVM_DECLARE_clientglobalvector(x)
354 #define PRVM_DECLARE_clientglobalstring(x)
355 #define PRVM_DECLARE_clientglobaledict(x)
356 #define PRVM_DECLARE_clientglobalfunction(x)
357 #define PRVM_DECLARE_menuglobalfloat(x)
358 #define PRVM_DECLARE_menuglobalvector(x)
359 #define PRVM_DECLARE_menuglobalstring(x)
360 #define PRVM_DECLARE_menuglobaledict(x)
361 #define PRVM_DECLARE_menuglobalfunction(x)
362 #define PRVM_DECLARE_serverfieldfloat(x)
363 #define PRVM_DECLARE_serverfieldvector(x)
364 #define PRVM_DECLARE_serverfieldstring(x)
365 #define PRVM_DECLARE_serverfieldedict(x)
366 #define PRVM_DECLARE_serverfieldfunction(x)
367 #define PRVM_DECLARE_clientfieldfloat(x)
368 #define PRVM_DECLARE_clientfieldvector(x)
369 #define PRVM_DECLARE_clientfieldstring(x)
370 #define PRVM_DECLARE_clientfieldedict(x)
371 #define PRVM_DECLARE_clientfieldfunction(x)
372 #define PRVM_DECLARE_menufieldfloat(x)
373 #define PRVM_DECLARE_menufieldvector(x)
374 #define PRVM_DECLARE_menufieldstring(x)
375 #define PRVM_DECLARE_menufieldedict(x)
376 #define PRVM_DECLARE_menufieldfunction(x)
377 #define PRVM_DECLARE_serverfunction(x)
378 #define PRVM_DECLARE_clientfunction(x)
379 #define PRVM_DECLARE_menufunction(x)
380 #define PRVM_DECLARE_field(x)
381 #define PRVM_DECLARE_global(x)
382 #define PRVM_DECLARE_function(x)
383 #include "prvm_offsets.h"
384 #undef PRVM_DECLARE_serverglobalfloat
385 #undef PRVM_DECLARE_serverglobalvector
386 #undef PRVM_DECLARE_serverglobalstring
387 #undef PRVM_DECLARE_serverglobaledict
388 #undef PRVM_DECLARE_serverglobalfunction
389 #undef PRVM_DECLARE_clientglobalfloat
390 #undef PRVM_DECLARE_clientglobalvector
391 #undef PRVM_DECLARE_clientglobalstring
392 #undef PRVM_DECLARE_clientglobaledict
393 #undef PRVM_DECLARE_clientglobalfunction
394 #undef PRVM_DECLARE_menuglobalfloat
395 #undef PRVM_DECLARE_menuglobalvector
396 #undef PRVM_DECLARE_menuglobalstring
397 #undef PRVM_DECLARE_menuglobaledict
398 #undef PRVM_DECLARE_menuglobalfunction
399 #undef PRVM_DECLARE_serverfieldfloat
400 #undef PRVM_DECLARE_serverfieldvector
401 #undef PRVM_DECLARE_serverfieldstring
402 #undef PRVM_DECLARE_serverfieldedict
403 #undef PRVM_DECLARE_serverfieldfunction
404 #undef PRVM_DECLARE_clientfieldfloat
405 #undef PRVM_DECLARE_clientfieldvector
406 #undef PRVM_DECLARE_clientfieldstring
407 #undef PRVM_DECLARE_clientfieldedict
408 #undef PRVM_DECLARE_clientfieldfunction
409 #undef PRVM_DECLARE_menufieldfloat
410 #undef PRVM_DECLARE_menufieldvector
411 #undef PRVM_DECLARE_menufieldstring
412 #undef PRVM_DECLARE_menufieldedict
413 #undef PRVM_DECLARE_menufieldfunction
414 #undef PRVM_DECLARE_serverfunction
415 #undef PRVM_DECLARE_clientfunction
416 #undef PRVM_DECLARE_menufunction
417 #undef PRVM_DECLARE_field
418 #undef PRVM_DECLARE_global
419 #undef PRVM_DECLARE_function
420 };
421
422 static void Host_Timescale_c(cvar_t *var)
423 {
424         if(var->value < 0.00001 && var->value != 0)
425                 Cvar_SetValueQuick(var, 0);
426 }
427
428 //============================================================================
429
430 static void SV_AreaStats_f(cmd_state_t *cmd)
431 {
432         World_PrintAreaStats(&sv.world, "server");
433 }
434
435 static qbool SV_CanSave(void)
436 {
437         prvm_prog_t *prog = SVVM_prog;
438         if(SV_IsLocalServer() == 1)
439         {
440                 // singleplayer checks
441                 if ((svs.clients[0].active && PRVM_serveredictfloat(svs.clients[0].edict, deadflag)))
442                 {
443                         Con_Print("Can't savegame with a dead player\n");
444                         return false;
445                 }
446
447                 if(host.hook.CL_Intermission && host.hook.CL_Intermission())
448                 {
449                         Con_Print("Can't save in intermission.\n");
450                         return false;
451                 }
452         }
453         else
454                 Con_Print(CON_WARN "Warning: saving a multiplayer game may have strange results when restored (to properly resume, all players must join in the same player slots and then the game can be reloaded).\n");
455         return true;
456         
457 }
458
459 /*
460 ===============
461 SV_Init
462 ===============
463 */
464 void SV_Init (void)
465 {
466         // init the csqc progs cvars, since they are updated/used by the server code
467         // TODO: fix this since this is a quick hack to make some of [515]'s broken code run ;) [9/13/2006 Black]
468         extern cvar_t csqc_progname;    //[515]: csqc crc check and right csprogs name according to progs.dat
469         extern cvar_t csqc_progcrc;
470         extern cvar_t csqc_progsize;
471         extern cvar_t csqc_usedemoprogs;
472
473         Cvar_RegisterVariable(&sv_worldmessage);
474         Cvar_RegisterVariable(&sv_worldname);
475         Cvar_RegisterVariable(&sv_worldnamenoextension);
476         Cvar_RegisterVariable(&sv_worldbasename);
477
478         Cvar_RegisterVariable (&csqc_progname);
479         Cvar_RegisterVariable (&csqc_progcrc);
480         Cvar_RegisterVariable (&csqc_progsize);
481         Cvar_RegisterVariable (&csqc_usedemoprogs);
482
483         Cmd_AddCommand(CF_SHARED, "sv_saveentfile", SV_SaveEntFile_f, "save map entities to .ent file (to allow external editing)");
484         Cmd_AddCommand(CF_SHARED, "sv_areastats", SV_AreaStats_f, "prints statistics on entity culling during collision traces");
485         Cmd_AddCommand(CF_CLIENT | CF_SERVER_FROM_CLIENT, "sv_startdownload", SV_StartDownload_f, "begins sending a file to the client (network protocol use only)");
486         Cmd_AddCommand(CF_CLIENT | CF_SERVER_FROM_CLIENT, "download", SV_Download_f, "downloads a specified file from the server");
487
488         Cvar_RegisterVariable (&sv_disablenotify);
489         Cvar_RegisterVariable (&coop);
490         Cvar_RegisterVariable (&deathmatch);
491         Cvar_RegisterVariable (&fraglimit);
492         Cvar_RegisterVariable (&gamecfg);
493         Cvar_RegisterVariable (&noexit);
494         Cvar_RegisterVariable (&nomonsters);
495         Cvar_RegisterVariable (&pausable);
496         Cvar_RegisterVariable (&pr_checkextension);
497         Cvar_RegisterVariable (&samelevel);
498         Cvar_RegisterVariable (&skill);
499         Cvar_RegisterVariable (&host_timescale);
500         Cvar_RegisterCallback (&host_timescale, Host_Timescale_c);
501         Cvar_RegisterAlias (&host_timescale, "slowmo");
502         Cvar_RegisterAlias (&host_timescale, "timescale");
503         Cvar_RegisterVariable (&sv_accelerate);
504         Cvar_RegisterVariable (&sv_aim);
505         Cvar_RegisterVariable (&sv_airaccel_qw);
506         Cvar_RegisterVariable (&sv_airaccel_qw_stretchfactor);
507         Cvar_RegisterVariable (&sv_airaccel_sideways_friction);
508         Cvar_RegisterVariable (&sv_airaccelerate);
509         Cvar_RegisterVariable (&sv_airstopaccelerate);
510         Cvar_RegisterVariable (&sv_airstrafeaccelerate);
511         Cvar_RegisterVariable (&sv_maxairstrafespeed);
512         Cvar_RegisterVariable (&sv_airstrafeaccel_qw);
513         Cvar_RegisterVariable (&sv_airspeedlimit_nonqw);
514         Cvar_RegisterVariable (&sv_aircontrol);
515         Cvar_RegisterVariable (&sv_aircontrol_power);
516         Cvar_RegisterVariable (&sv_aircontrol_penalty);
517         Cvar_RegisterVariable (&sv_allowdownloads);
518         Cvar_RegisterVariable (&sv_allowdownloads_archive);
519         Cvar_RegisterVariable (&sv_allowdownloads_config);
520         Cvar_RegisterVariable (&sv_allowdownloads_dlcache);
521         Cvar_RegisterVariable (&sv_allowdownloads_inarchive);
522         Cvar_RegisterVariable (&sv_areagrid_mingridsize);
523         Cvar_RegisterVariable (&sv_checkforpacketsduringsleep);
524         Cvar_RegisterVariable (&sv_clmovement_enable);
525         Cvar_RegisterVariable (&sv_clmovement_minping);
526         Cvar_RegisterVariable (&sv_clmovement_minping_disabletime);
527         Cvar_RegisterVariable (&sv_clmovement_inputtimeout);
528         Cvar_RegisterVariable (&sv_cullentities_nevercullbmodels);
529         Cvar_RegisterVariable (&sv_cullentities_pvs);
530         Cvar_RegisterVariable (&sv_cullentities_stats);
531         Cvar_RegisterVariable (&sv_cullentities_trace);
532         Cvar_RegisterVariable (&sv_cullentities_trace_delay);
533         Cvar_RegisterVariable (&sv_cullentities_trace_delay_players);
534         Cvar_RegisterVariable (&sv_cullentities_trace_enlarge);
535         Cvar_RegisterVariable (&sv_cullentities_trace_expand);
536         Cvar_RegisterVariable (&sv_cullentities_trace_eyejitter);
537         Cvar_RegisterVariable (&sv_cullentities_trace_entityocclusion);
538         Cvar_RegisterVariable (&sv_cullentities_trace_prediction);
539         Cvar_RegisterVariable (&sv_cullentities_trace_prediction_time);
540         Cvar_RegisterVariable (&sv_cullentities_trace_samples);
541         Cvar_RegisterVariable (&sv_cullentities_trace_samples_extra);
542         Cvar_RegisterVariable (&sv_cullentities_trace_samples_players);
543         Cvar_RegisterVariable (&sv_debugmove);
544         Cvar_RegisterVariable (&sv_echobprint);
545         Cvar_RegisterVariable (&sv_edgefriction);
546         Cvar_RegisterVariable (&sv_entpatch);
547         Cvar_RegisterVariable (&sv_freezenonclients);
548         Cvar_RegisterVariable (&sv_friction);
549         Cvar_RegisterVariable (&sv_gameplayfix_blowupfallenzombies);
550         Cvar_RegisterVariable (&sv_gameplayfix_consistentplayerprethink);
551         Cvar_RegisterVariable (&sv_gameplayfix_delayprojectiles);
552         Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid);
553         Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid_nudgetocorrect);
554         Cvar_RegisterVariable (&sv_gameplayfix_easierwaterjump);
555         Cvar_RegisterVariable (&sv_gameplayfix_findradiusdistancetobox);
556         Cvar_RegisterVariable (&sv_gameplayfix_gravityunaffectedbyticrate);
557         Cvar_RegisterVariable (&sv_gameplayfix_grenadebouncedownslopes);
558         Cvar_RegisterVariable (&sv_gameplayfix_multiplethinksperframe);
559         Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
560         Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse_allowsuspendeditems);
561         Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid);
562         Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid_separation);
563         Cvar_RegisterVariable (&sv_gameplayfix_q2airaccelerate);
564         Cvar_RegisterVariable (&sv_gameplayfix_nogravityonground);
565         Cvar_RegisterVariable (&sv_gameplayfix_setmodelrealbox);
566         Cvar_RegisterVariable (&sv_gameplayfix_slidemoveprojectiles);
567         Cvar_RegisterVariable (&sv_gameplayfix_stepdown);
568         Cvar_RegisterVariable (&sv_gameplayfix_stepmultipletimes);
569         Cvar_RegisterVariable (&sv_gameplayfix_nostepmoveonsteepslopes);
570         Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
571         Cvar_RegisterVariable (&sv_gameplayfix_upwardvelocityclearsongroundflag);
572         Cvar_RegisterVariable (&sv_gameplayfix_downtracesupportsongroundflag);
573         Cvar_RegisterVariable (&sv_gameplayfix_q1bsptracelinereportstexture);
574         Cvar_RegisterVariable (&sv_gameplayfix_unstickplayers);
575         Cvar_RegisterVariable (&sv_gameplayfix_unstickentities);
576         Cvar_RegisterVariable (&sv_gameplayfix_fixedcheckwatertransition);
577         Cvar_RegisterVariable (&sv_gameplayfix_customstats);
578         Cvar_RegisterVariable (&sv_gravity);
579         Cvar_RegisterVariable (&sv_init_frame_count);
580         Cvar_RegisterVariable (&sv_idealpitchscale);
581         Cvar_RegisterVariable (&sv_jumpstep);
582         Cvar_RegisterVariable (&sv_jumpvelocity);
583         Cvar_RegisterVariable (&sv_maxairspeed);
584         Cvar_RegisterVariable (&sv_maxrate);
585         Cvar_RegisterVariable (&sv_maxspeed);
586         Cvar_RegisterVariable (&sv_maxvelocity);
587         Cvar_RegisterVariable (&sv_nostep);
588         Cvar_RegisterVariable (&sv_playerphysicsqc);
589         Cvar_RegisterVariable (&sv_progs);
590         Cvar_RegisterVariable (&sv_protocolname);
591         Cvar_RegisterVariable (&sv_random_seed);
592         Cvar_RegisterVariable (&host_limitlocal);
593         Cvar_RegisterAlias(&host_limitlocal, "sv_ratelimitlocalplayer");
594         Cvar_RegisterVariable (&sv_sound_land);
595         Cvar_RegisterVariable (&sv_sound_watersplash);
596         Cvar_RegisterVariable (&sv_stepheight);
597         Cvar_RegisterVariable (&sv_stopspeed);
598         Cvar_RegisterVariable (&sv_wallfriction);
599         Cvar_RegisterVariable (&sv_wateraccelerate);
600         Cvar_RegisterVariable (&sv_waterfriction);
601         Cvar_RegisterVariable (&sv_warsowbunny_airforwardaccel);
602         Cvar_RegisterVariable (&sv_warsowbunny_accel);
603         Cvar_RegisterVariable (&sv_warsowbunny_topspeed);
604         Cvar_RegisterVariable (&sv_warsowbunny_turnaccel);
605         Cvar_RegisterVariable (&sv_warsowbunny_backtosideratio);
606         Cvar_RegisterVariable (&sv_onlycsqcnetworking);
607         Cvar_RegisterVariable (&sv_areadebug);
608         Cvar_RegisterVariable (&sys_ticrate);
609         Cvar_RegisterVariable (&teamplay);
610         Cvar_RegisterVariable (&timelimit);
611         Cvar_RegisterVariable (&sv_threaded);
612
613         Cvar_RegisterVariable (&sv_rollangle);
614         Cvar_RegisterVariable (&sv_rollspeed);
615
616         Cvar_RegisterVariable (&saved1);
617         Cvar_RegisterVariable (&saved2);
618         Cvar_RegisterVariable (&saved3);
619         Cvar_RegisterVariable (&saved4);
620         Cvar_RegisterVariable (&savedgamecfg);
621         Cvar_RegisterVariable (&scratch1);
622         Cvar_RegisterVariable (&scratch2);
623         Cvar_RegisterVariable (&scratch3);
624         Cvar_RegisterVariable (&scratch4);
625         Cvar_RegisterVariable (&temp1);
626
627         // LadyHavoc: Nehahra uses these to pass data around cutscene demos
628         Cvar_RegisterVariable (&nehx00);
629         Cvar_RegisterVariable (&nehx01);
630         Cvar_RegisterVariable (&nehx02);
631         Cvar_RegisterVariable (&nehx03);
632         Cvar_RegisterVariable (&nehx04);
633         Cvar_RegisterVariable (&nehx05);
634         Cvar_RegisterVariable (&nehx06);
635         Cvar_RegisterVariable (&nehx07);
636         Cvar_RegisterVariable (&nehx08);
637         Cvar_RegisterVariable (&nehx09);
638         Cvar_RegisterVariable (&nehx10);
639         Cvar_RegisterVariable (&nehx11);
640         Cvar_RegisterVariable (&nehx12);
641         Cvar_RegisterVariable (&nehx13);
642         Cvar_RegisterVariable (&nehx14);
643         Cvar_RegisterVariable (&nehx15);
644         Cvar_RegisterVariable (&nehx16);
645         Cvar_RegisterVariable (&nehx17);
646         Cvar_RegisterVariable (&nehx18);
647         Cvar_RegisterVariable (&nehx19);
648         Cvar_RegisterVariable (&cutscene); // for Nehahra but useful to other mods as well
649
650         Cvar_RegisterVariable (&sv_autodemo_perclient);
651         Cvar_RegisterVariable (&sv_autodemo_perclient_nameformat);
652         Cvar_RegisterVariable (&sv_autodemo_perclient_discardable);
653
654         Cvar_RegisterVariable (&halflifebsp);
655         Cvar_RegisterVariable (&sv_mapformat_is_quake2);
656         Cvar_RegisterVariable (&sv_mapformat_is_quake3);
657
658         SV_InitOperatorCommands();
659         host.hook.SV_CanSave = SV_CanSave;
660
661         sv_mempool = Mem_AllocPool("server", 0, NULL);
662 }
663
664 static void SV_SaveEntFile_f(cmd_state_t *cmd)
665 {
666         char vabuf[1024];
667         if (!sv.active || !sv.worldmodel)
668         {
669                 Con_Print("Not running a server\n");
670                 return;
671         }
672         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), sv.worldmodel->brush.entities, (fs_offset_t)strlen(sv.worldmodel->brush.entities));
673 }
674
675 /*
676 ==============================================================================
677
678 CLIENT SPAWNING
679
680 ==============================================================================
681 */
682
683 /*
684 ================
685 SV_SendServerinfo
686
687 Sends the first message from the server to a connected client.
688 This will be sent on the initial connection and upon each server load.
689 ================
690 */
691 void SV_SendServerinfo (client_t *client)
692 {
693         prvm_prog_t *prog = SVVM_prog;
694         int i;
695         char message[128];
696         char vabuf[1024];
697
698         // we know that this client has a netconnection and thus is not a bot
699
700         // edicts get reallocated on level changes, so we need to update it here
701         client->edict = PRVM_EDICT_NUM((client - svs.clients) + 1);
702
703         // clear cached stuff that depends on the level
704         client->weaponmodel[0] = 0;
705         client->weaponmodelindex = 0;
706
707         // LadyHavoc: clear entityframe tracking
708         client->latestframenum = 0;
709
710         // initialize the movetime, so a speedhack can't make use of the time before this client joined
711         client->cmd.time = sv.time;
712
713         if (client->entitydatabase)
714                 EntityFrame_FreeDatabase(client->entitydatabase);
715         if (client->entitydatabase4)
716                 EntityFrame4_FreeDatabase(client->entitydatabase4);
717         if (client->entitydatabase5)
718                 EntityFrame5_FreeDatabase(client->entitydatabase5);
719
720         memset(client->stats, 0, sizeof(client->stats));
721         memset(client->statsdeltabits, 0, sizeof(client->statsdeltabits));
722
723         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3)
724         {
725                 if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
726                         client->entitydatabase = EntityFrame_AllocDatabase(sv_mempool);
727                 else if (sv.protocol == PROTOCOL_DARKPLACES4)
728                         client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_mempool);
729                 else
730                         client->entitydatabase5 = EntityFrame5_AllocDatabase(sv_mempool);
731         }
732
733         // reset csqc entity versions
734         for (i = 0;i < prog->max_edicts;i++)
735         {
736                 client->csqcentityscope[i] = 0;
737                 client->csqcentitysendflags[i] = 0xFFFFFF;
738         }
739         for (i = 0;i < NUM_CSQCENTITYDB_FRAMES;i++)
740         {
741                 client->csqcentityframehistory[i].num = 0;
742                 client->csqcentityframehistory[i].framenum = -1;
743         }
744         client->csqcnumedicts = 0;
745         client->csqcentityframehistory_next = 0;
746
747         SZ_Clear (&client->netconnection->message);
748         MSG_WriteByte (&client->netconnection->message, svc_print);
749         dpsnprintf (message, sizeof (message), "\nServer: %s build %s (progs %i crc)\n", gamename, buildstring, prog->filecrc);
750         MSG_WriteString (&client->netconnection->message,message);
751
752         SV_StopDemoRecording(client); // to split up demos into different files
753         if(sv_autodemo_perclient.integer)
754         {
755                 char demofile[MAX_OSPATH];
756                 char ipaddress[MAX_QPATH];
757                 size_t j;
758
759                 // start a new demo file
760                 LHNETADDRESS_ToString(&(client->netconnection->peeraddress), ipaddress, sizeof(ipaddress), true);
761                 for(j = 0; ipaddress[j]; ++j)
762                         if(!isalnum(ipaddress[j]))
763                                 ipaddress[j] = '-';
764                 dpsnprintf (demofile, sizeof(demofile), "%s_%s_%d_%s.dem", Sys_TimeString (sv_autodemo_perclient_nameformat.string), sv.worldbasename, PRVM_NUM_FOR_EDICT(client->edict), ipaddress);
765
766                 SV_StartDemoRecording(client, demofile, -1);
767         }
768
769         //[515]: init csprogs according to version of svprogs, check the crc, etc.
770         if (sv.csqc_progname[0])
771         {
772                 Con_DPrintf("sending csqc info to client (\"%s\" with size %i and crc %i)\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
773                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
774                 MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progname %s\n", sv.csqc_progname));
775                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
776                 MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progsize %i\n", sv.csqc_progsize));
777                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
778                 MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progcrc %i\n", sv.csqc_progcrc));
779
780                 if(client->sv_demo_file != NULL)
781                 {
782                         int k;
783                         static char buf[NET_MAXMESSAGE];
784                         sizebuf_t sb;
785
786                         sb.data = (unsigned char *) buf;
787                         sb.maxsize = sizeof(buf);
788                         k = 0;
789                         while(MakeDownloadPacket(sv.csqc_progname, svs.csqc_progdata, sv.csqc_progsize, sv.csqc_progcrc, k++, &sb, sv.protocol))
790                                 SV_WriteDemoMessage(client, &sb, false);
791                 }
792
793                 //[515]: init stufftext string (it is sent before svc_serverinfo)
794                 if (PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd)))
795                 {
796                         MSG_WriteByte (&client->netconnection->message, svc_stufftext);
797                         MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "%s\n", PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd))));
798                 }
799         }
800
801         //if (sv_allowdownloads.integer)
802         // always send the info that the server supports the protocol, even if downloads are forbidden
803         // only because of that, the CSQC exception can work
804         {
805                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
806                 MSG_WriteString (&client->netconnection->message, "cl_serverextension_download 2\n");
807         }
808
809         // send at this time so it's guaranteed to get executed at the right time
810         {
811                 client_t *save;
812                 save = host_client;
813                 host_client = client;
814                 Curl_SendRequirements();
815                 host_client = save;
816         }
817
818         MSG_WriteByte (&client->netconnection->message, svc_serverinfo);
819         MSG_WriteLong (&client->netconnection->message, Protocol_NumberForEnum(sv.protocol));
820         MSG_WriteByte (&client->netconnection->message, svs.maxclients);
821
822         if (!coop.integer && deathmatch.integer)
823                 MSG_WriteByte (&client->netconnection->message, GAME_DEATHMATCH);
824         else
825                 MSG_WriteByte (&client->netconnection->message, GAME_COOP);
826
827         MSG_WriteString (&client->netconnection->message,PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)));
828
829         for (i = 1;i < MAX_MODELS && sv.model_precache[i][0];i++)
830                 MSG_WriteString (&client->netconnection->message, sv.model_precache[i]);
831         MSG_WriteByte (&client->netconnection->message, 0);
832
833         for (i = 1;i < MAX_SOUNDS && sv.sound_precache[i][0];i++)
834                 MSG_WriteString (&client->netconnection->message, sv.sound_precache[i]);
835         MSG_WriteByte (&client->netconnection->message, 0);
836
837 // send music
838         MSG_WriteByte (&client->netconnection->message, svc_cdtrack);
839         MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));
840         MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));
841
842 // set view
843 // store this in clientcamera, too
844         client->clientcamera = PRVM_NUM_FOR_EDICT(client->edict);
845         MSG_WriteByte (&client->netconnection->message, svc_setview);
846         MSG_WriteShort (&client->netconnection->message, client->clientcamera);
847
848         MSG_WriteByte (&client->netconnection->message, svc_signonnum);
849         MSG_WriteByte (&client->netconnection->message, 1);
850
851         client->prespawned = false;             // need prespawn, spawn, etc
852         client->spawned = false;                // need prespawn, spawn, etc
853         client->begun = false;                  // need prespawn, spawn, etc
854         client->sendsignon = 1;                 // send this message, and increment to 2, 2 will be set to 0 by the prespawn command
855
856         // clear movement info until client enters the new level properly
857         memset(&client->cmd, 0, sizeof(client->cmd));
858         client->movesequence = 0;
859         client->movement_highestsequence_seen = 0;
860         memset(&client->movement_count, 0, sizeof(client->movement_count));
861 #ifdef NUM_PING_TIMES
862         for (i = 0;i < NUM_PING_TIMES;i++)
863                 client->ping_times[i] = 0;
864         client->num_pings = 0;
865 #endif
866         client->ping = 0;
867
868         // allow the client some time to send his keepalives, even if map loading took ages
869         client->netconnection->timeout = host.realtime + net_connecttimeout.value;
870 }
871
872 /*
873 ================
874 SV_ConnectClient
875
876 Initializes a client_t for a new net connection.  This will only be called
877 once for a player each game, not once for each level change.
878 ================
879 */
880 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
881 {
882         prvm_prog_t *prog = SVVM_prog;
883         client_t                *client;
884         int                             i;
885
886         client = svs.clients + clientnum;
887
888 // set up the client_t
889         if (sv.loadgame)
890         {
891                 float backupparms[NUM_SPAWN_PARMS];
892                 memcpy(backupparms, client->spawn_parms, sizeof(backupparms));
893                 memset(client, 0, sizeof(*client));
894                 memcpy(client->spawn_parms, backupparms, sizeof(backupparms));
895         }
896         else
897                 memset(client, 0, sizeof(*client));
898         client->active = true;
899         client->netconnection = netconnection;
900
901         Con_DPrintf("Client %s connected\n", client->netconnection ? client->netconnection->address : "botclient");
902
903         if(client->netconnection && client->netconnection->crypto.authenticated)
904         {
905                 Con_Printf("%s connection to %s has been established: client is %s@%s%.*s, I am %.*s@%s%.*s\n",
906                                 client->netconnection->crypto.use_aes ? "Encrypted" : "Authenticated",
907                                 client->netconnection->address,
908                                 client->netconnection->crypto.client_idfp[0] ? client->netconnection->crypto.client_idfp : "-",
909                                 (client->netconnection->crypto.client_issigned || !client->netconnection->crypto.client_keyfp[0]) ? "" : "~",
910                                 crypto_keyfp_recommended_length, client->netconnection->crypto.client_keyfp[0] ? client->netconnection->crypto.client_keyfp : "-",
911                                 crypto_keyfp_recommended_length, client->netconnection->crypto.server_idfp[0] ? client->netconnection->crypto.server_idfp : "-",
912                                 (client->netconnection->crypto.server_issigned || !client->netconnection->crypto.server_keyfp[0]) ? "" : "~",
913                                 crypto_keyfp_recommended_length, client->netconnection->crypto.server_keyfp[0] ? client->netconnection->crypto.server_keyfp : "-"
914                                 );
915         }
916
917         strlcpy(client->name, "unconnected", sizeof(client->name));
918         strlcpy(client->old_name, "unconnected", sizeof(client->old_name));
919         client->prespawned = false;
920         client->spawned = false;
921         client->begun = false;
922         client->edict = PRVM_EDICT_NUM(clientnum+1);
923         if (client->netconnection)
924                 client->netconnection->message.allowoverflow = true;            // we can catch it
925         // prepare the unreliable message buffer
926         client->unreliablemsg.data = client->unreliablemsg_data;
927         client->unreliablemsg.maxsize = sizeof(client->unreliablemsg_data);
928         // updated by receiving "rate" command from client, this is also the default if not using a DP client
929         client->rate = 1000000000;
930         client->connecttime = host.realtime;
931
932         if (!sv.loadgame)
933         {
934                 // call the progs to get default spawn parms for the new client
935                 // set self to world to intentionally cause errors with broken SetNewParms code in some mods
936                 PRVM_serverglobalfloat(time) = sv.time;
937                 PRVM_serverglobaledict(self) = 0;
938                 prog->ExecuteProgram(prog, PRVM_serverfunction(SetNewParms), "QC function SetNewParms is missing");
939                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
940                         client->spawn_parms[i] = (&PRVM_serverglobalfloat(parm1))[i];
941
942                 // set up the entity for this client (including .colormap, .team, etc)
943                 PRVM_ED_ClearEdict(prog, client->edict);
944         }
945
946         // don't call SendServerinfo for a fresh botclient because its fields have
947         // not been set up by the qc yet
948         if (client->netconnection)
949                 SV_SendServerinfo (client);
950         else
951                 client->prespawned = client->spawned = client->begun = true;
952 }
953
954 /*
955 =====================
956 SV_DropClient
957
958 Called when the player is getting totally kicked off the host
959 if (crash = true), don't bother sending signofs
960 =====================
961 */
962 void SV_DropClient(qbool crash)
963 {
964         prvm_prog_t *prog = SVVM_prog;
965         int i;
966         Con_Printf("Client \"%s\" dropped\n", host_client->name);
967
968         SV_StopDemoRecording(host_client);
969
970         // make sure edict is not corrupt (from a level change for example)
971         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
972
973         if (host_client->netconnection)
974         {
975                 // tell the client to be gone
976                 if (!crash)
977                 {
978                         // LadyHavoc: no opportunity for resending, so use unreliable 3 times
979                         unsigned char bufdata[8];
980                         sizebuf_t buf;
981                         memset(&buf, 0, sizeof(buf));
982                         buf.data = bufdata;
983                         buf.maxsize = sizeof(bufdata);
984                         MSG_WriteByte(&buf, svc_disconnect);
985                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
986                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
987                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
988                 }
989         }
990
991         // call qc ClientDisconnect function
992         // LadyHavoc: don't call QC if server is dead (avoids recursive
993         // Host_Error in some mods when they run out of edicts)
994         if (host_client->clientconnectcalled && sv.active && host_client->edict)
995         {
996                 // call the prog function for removing a client
997                 // this will set the body to a dead frame, among other things
998                 int saveSelf = PRVM_serverglobaledict(self);
999                 host_client->clientconnectcalled = false;
1000                 PRVM_serverglobalfloat(time) = sv.time;
1001                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
1002                 prog->ExecuteProgram(prog, PRVM_serverfunction(ClientDisconnect), "QC function ClientDisconnect is missing");
1003                 PRVM_serverglobaledict(self) = saveSelf;
1004         }
1005
1006         if (host_client->netconnection)
1007         {
1008                 // break the net connection
1009                 NetConn_Close(host_client->netconnection);
1010                 host_client->netconnection = NULL;
1011         }
1012
1013         // if a download is active, close it
1014         if (host_client->download_file)
1015         {
1016                 Con_DPrintf("Download of %s aborted when %s dropped\n", host_client->download_name, host_client->name);
1017                 FS_Close(host_client->download_file);
1018                 host_client->download_file = NULL;
1019                 host_client->download_name[0] = 0;
1020                 host_client->download_expectedposition = 0;
1021                 host_client->download_started = false;
1022         }
1023
1024         // remove leaving player from scoreboard
1025         host_client->name[0] = 0;
1026         host_client->colors = 0;
1027         host_client->frags = 0;
1028         // send notification to all clients
1029         // get number of client manually just to make sure we get it right...
1030         i = host_client - svs.clients;
1031         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
1032         MSG_WriteByte (&sv.reliable_datagram, i);
1033         MSG_WriteString (&sv.reliable_datagram, host_client->name);
1034         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
1035         MSG_WriteByte (&sv.reliable_datagram, i);
1036         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
1037         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
1038         MSG_WriteByte (&sv.reliable_datagram, i);
1039         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
1040
1041         // free the client now
1042         if (host_client->entitydatabase)
1043                 EntityFrame_FreeDatabase(host_client->entitydatabase);
1044         if (host_client->entitydatabase4)
1045                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
1046         if (host_client->entitydatabase5)
1047                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
1048
1049         if (sv.active)
1050         {
1051                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
1052                 PRVM_ED_ClearEdict(prog, host_client->edict);
1053         }
1054
1055         // clear the client struct (this sets active to false)
1056         memset(host_client, 0, sizeof(*host_client));
1057
1058         // update server listing on the master because player count changed
1059         // (which the master uses for filtering empty/full servers)
1060         NetConn_Heartbeat(1);
1061
1062         if (sv.loadgame)
1063         {
1064                 for (i = 0;i < svs.maxclients;i++)
1065                         if (svs.clients[i].active && !svs.clients[i].spawned)
1066                                 break;
1067                 if (i == svs.maxclients)
1068                 {
1069                         Con_Printf("Loaded game, everyone rejoined - unpausing\n");
1070                         sv.paused = sv.loadgame = false; // we're basically done with loading now
1071                 }
1072         }
1073 }
1074
1075 static void SV_StartDownload_f(cmd_state_t *cmd)
1076 {
1077         if (host_client->download_file)
1078                 host_client->download_started = true;
1079 }
1080
1081 /*
1082  * Compression extension negotiation:
1083  *
1084  * Server to client:
1085  *   cl_serverextension_download 2
1086  *
1087  * Client to server:
1088  *   download <filename> <list of zero or more suppported compressions in order of preference>
1089  * e.g.
1090  *   download maps/map1.bsp lzo deflate huffman
1091  *
1092  * Server to client:
1093  *   cl_downloadbegin <compressed size> <filename> <compression method actually used>
1094  * e.g.
1095  *   cl_downloadbegin 123456 maps/map1.bsp deflate
1096  *
1097  * The server may choose not to compress the file by sending no compression name, like:
1098  *   cl_downloadbegin 345678 maps/map1.bsp
1099  *
1100  * NOTE: the "download" command may only specify compression algorithms if
1101  *       cl_serverextension_download is 2!
1102  *       If cl_serverextension_download has a different value, the client must
1103  *       assume this extension is not supported!
1104  */
1105
1106 static void Download_CheckExtensions(cmd_state_t *cmd)
1107 {
1108         int i;
1109         int argc = Cmd_Argc(cmd);
1110
1111         // first reset them all
1112         host_client->download_deflate = false;
1113         
1114         for(i = 2; i < argc; ++i)
1115         {
1116                 if(!strcmp(Cmd_Argv(cmd, i), "deflate"))
1117                 {
1118                         host_client->download_deflate = true;
1119                         break;
1120                 }
1121         }
1122 }
1123
1124 static void SV_Download_f(cmd_state_t *cmd)
1125 {
1126         const char *whichpack, *whichpack2, *extension;
1127         qbool is_csqc; // so we need to check only once
1128
1129         if (Cmd_Argc(cmd) < 2)
1130         {
1131                 SV_ClientPrintf("usage: download <filename> {<extensions>}*\n");
1132                 SV_ClientPrintf("       supported extensions: deflate\n");
1133                 return;
1134         }
1135
1136         if (FS_CheckNastyPath(Cmd_Argv(cmd, 1), false))
1137         {
1138                 SV_ClientPrintf("Download rejected: nasty filename \"%s\"\n", Cmd_Argv(cmd, 1));
1139                 return;
1140         }
1141
1142         if (host_client->download_file)
1143         {
1144                 // at this point we'll assume the previous download should be aborted
1145                 Con_DPrintf("Download of %s aborted by %s starting a new download\n", host_client->download_name, host_client->name);
1146                 SV_ClientCommands("\nstopdownload\n");
1147
1148                 // close the file and reset variables
1149                 FS_Close(host_client->download_file);
1150                 host_client->download_file = NULL;
1151                 host_client->download_name[0] = 0;
1152                 host_client->download_expectedposition = 0;
1153                 host_client->download_started = false;
1154         }
1155
1156         is_csqc = (sv.csqc_progname[0] && strcmp(Cmd_Argv(cmd, 1), sv.csqc_progname) == 0);
1157         
1158         if (!sv_allowdownloads.integer && !is_csqc)
1159         {
1160                 SV_ClientPrintf("Downloads are disabled on this server\n");
1161                 SV_ClientCommands("\nstopdownload\n");
1162                 return;
1163         }
1164
1165         Download_CheckExtensions(cmd);
1166
1167         strlcpy(host_client->download_name, Cmd_Argv(cmd, 1), sizeof(host_client->download_name));
1168         extension = FS_FileExtension(host_client->download_name);
1169
1170         // host_client is asking to download a specified file
1171         if (developer_extra.integer)
1172                 Con_DPrintf("Download request for %s by %s\n", host_client->download_name, host_client->name);
1173
1174         if(is_csqc)
1175         {
1176                 char extensions[MAX_QPATH]; // make sure this can hold all extensions
1177                 extensions[0] = '\0';
1178                 
1179                 if(host_client->download_deflate)
1180                         strlcat(extensions, " deflate", sizeof(extensions));
1181                 
1182                 Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);
1183
1184                 if(host_client->download_deflate && svs.csqc_progdata_deflated)
1185                         host_client->download_file = FS_FileFromData(svs.csqc_progdata_deflated, svs.csqc_progsize_deflated, true);
1186                 else
1187                         host_client->download_file = FS_FileFromData(svs.csqc_progdata, sv.csqc_progsize, true);
1188                 
1189                 // no, no space is needed between %s and %s :P
1190                 SV_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
1191
1192                 host_client->download_expectedposition = 0;
1193                 host_client->download_started = false;
1194                 host_client->sendsignon = true; // make sure this message is sent
1195                 return;
1196         }
1197
1198         if (!FS_FileExists(host_client->download_name))
1199         {
1200                 SV_ClientPrintf("Download rejected: server does not have the file \"%s\"\nYou may need to separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1201                 SV_ClientCommands("\nstopdownload\n");
1202                 return;
1203         }
1204
1205         // check if the user is trying to download part of registered Quake(r)
1206         whichpack = FS_WhichPack(host_client->download_name);
1207         whichpack2 = FS_WhichPack("gfx/pop.lmp");
1208         if ((whichpack && whichpack2 && !strcasecmp(whichpack, whichpack2)) || FS_IsRegisteredQuakePack(host_client->download_name))
1209         {
1210                 SV_ClientPrintf("Download rejected: file \"%s\" is part of registered Quake(r)\nYou must purchase Quake(r) from id Software or a retailer to get this file\nPlease go to http://www.idsoftware.com/games/quake/quake/index.php?game_section=buy\n", host_client->download_name);
1211                 SV_ClientCommands("\nstopdownload\n");
1212                 return;
1213         }
1214
1215         // check if the server has forbidden archive downloads entirely
1216         if (!sv_allowdownloads_inarchive.integer)
1217         {
1218                 whichpack = FS_WhichPack(host_client->download_name);
1219                 if (whichpack)
1220                 {
1221                         SV_ClientPrintf("Download rejected: file \"%s\" is in an archive (\"%s\")\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name, whichpack);
1222                         SV_ClientCommands("\nstopdownload\n");
1223                         return;
1224                 }
1225         }
1226
1227         if (!sv_allowdownloads_config.integer)
1228         {
1229                 if (!strcasecmp(extension, "cfg"))
1230                 {
1231                         SV_ClientPrintf("Download rejected: file \"%s\" is a .cfg file which is forbidden for security reasons\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1232                         SV_ClientCommands("\nstopdownload\n");
1233                         return;
1234                 }
1235         }
1236
1237         if (!sv_allowdownloads_dlcache.integer)
1238         {
1239                 if (!strncasecmp(host_client->download_name, "dlcache/", 8))
1240                 {
1241                         SV_ClientPrintf("Download rejected: file \"%s\" is in the dlcache/ directory which is forbidden for security reasons\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1242                         SV_ClientCommands("\nstopdownload\n");
1243                         return;
1244                 }
1245         }
1246
1247         if (!sv_allowdownloads_archive.integer)
1248         {
1249                 if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3"))
1250                 {
1251                         SV_ClientPrintf("Download rejected: file \"%s\" is an archive\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1252                         SV_ClientCommands("\nstopdownload\n");
1253                         return;
1254                 }
1255         }
1256
1257         host_client->download_file = FS_OpenVirtualFile(host_client->download_name, true);
1258         if (!host_client->download_file)
1259         {
1260                 SV_ClientPrintf("Download rejected: server could not open the file \"%s\"\n", host_client->download_name);
1261                 SV_ClientCommands("\nstopdownload\n");
1262                 return;
1263         }
1264
1265         if (FS_FileSize(host_client->download_file) > 1<<30)
1266         {
1267                 SV_ClientPrintf("Download rejected: file \"%s\" is very large\n", host_client->download_name);
1268                 SV_ClientCommands("\nstopdownload\n");
1269                 FS_Close(host_client->download_file);
1270                 host_client->download_file = NULL;
1271                 return;
1272         }
1273
1274         if (FS_FileSize(host_client->download_file) < 0)
1275         {
1276                 SV_ClientPrintf("Download rejected: file \"%s\" is not a regular file\n", host_client->download_name);
1277                 SV_ClientCommands("\nstopdownload\n");
1278                 FS_Close(host_client->download_file);
1279                 host_client->download_file = NULL;
1280                 return;
1281         }
1282
1283         Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);
1284
1285         /*
1286          * we can only do this if we would actually deflate on the fly
1287          * which we do not (yet)!
1288         {
1289                 char extensions[MAX_QPATH]; // make sure this can hold all extensions
1290                 extensions[0] = '\0';
1291                 
1292                 if(host_client->download_deflate)
1293                         strlcat(extensions, " deflate", sizeof(extensions));
1294
1295                 // no, no space is needed between %s and %s :P
1296                 SV_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
1297         }
1298         */
1299         SV_ClientCommands("\ncl_downloadbegin %i %s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name);
1300
1301         host_client->download_expectedposition = 0;
1302         host_client->download_started = false;
1303         host_client->sendsignon = true; // make sure this message is sent
1304
1305         // the rest of the download process is handled in SV_SendClientDatagram
1306         // and other code dealing with svc_downloaddata and clc_ackdownloaddata
1307         //
1308         // no svc_downloaddata messages will be sent until sv_startdownload is
1309         // sent by the client
1310 }
1311
1312 /*
1313 ==============================================================================
1314
1315 SERVER SPAWNING
1316
1317 ==============================================================================
1318 */
1319
1320 /*
1321 ================
1322 SV_ModelIndex
1323
1324 ================
1325 */
1326 int SV_ModelIndex(const char *s, int precachemode)
1327 {
1328         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3) ? 256 : MAX_MODELS);
1329         char filename[MAX_QPATH];
1330         if (!s || !*s)
1331                 return 0;
1332         // testing
1333         //if (precachemode == 2)
1334         //      return 0;
1335         strlcpy(filename, s, sizeof(filename));
1336         for (i = 2;i < limit;i++)
1337         {
1338                 if (!sv.model_precache[i][0])
1339                 {
1340                         if (precachemode)
1341                         {
1342                                 if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
1343                                 {
1344                                         Con_Printf("SV_ModelIndex(\"%s\"): precache_model can only be done in spawn functions\n", filename);
1345                                         return 0;
1346                                 }
1347                                 if (precachemode == 1)
1348                                         Con_Printf("SV_ModelIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
1349                                 strlcpy(sv.model_precache[i], filename, sizeof(sv.model_precache[i]));
1350                                 if (sv.state == ss_loading)
1351                                 {
1352                                         // running from SV_SpawnServer which is launched from the client console command interpreter
1353                                         sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
1354                                 }
1355                                 else
1356                                 {
1357                                         if (svs.threaded)
1358                                         {
1359                                                 // this is running on the server thread, we can't load a model here (it would crash on renderer calls), so only look it up, the svc_precache will cause it to be loaded when it reaches the client
1360                                                 sv.models[i] = Mod_FindName (sv.model_precache[i], s[0] == '*' ? sv.worldname : NULL);
1361                                         }
1362                                         else
1363                                         {
1364                                                 // running single threaded, so we can load the model here
1365                                                 sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
1366                                         }
1367                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
1368                                         MSG_WriteShort(&sv.reliable_datagram, i);
1369                                         MSG_WriteString(&sv.reliable_datagram, filename);
1370                                 }
1371                                 return i;
1372                         }
1373                         Con_Printf("SV_ModelIndex(\"%s\"): not precached\n", filename);
1374                         return 0;
1375                 }
1376                 if (!strcmp(sv.model_precache[i], filename))
1377                         return i;
1378         }
1379         Con_Printf("SV_ModelIndex(\"%s\"): i (%i) == MAX_MODELS (%i)\n", filename, i, MAX_MODELS);
1380         return 0;
1381 }
1382
1383 /*
1384 ================
1385 SV_SoundIndex
1386
1387 ================
1388 */
1389 int SV_SoundIndex(const char *s, int precachemode)
1390 {
1391         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3) ? 256 : MAX_SOUNDS);
1392         char filename[MAX_QPATH];
1393         if (!s || !*s)
1394                 return 0;
1395         // testing
1396         //if (precachemode == 2)
1397         //      return 0;
1398         strlcpy(filename, s, sizeof(filename));
1399         for (i = 1;i < limit;i++)
1400         {
1401                 if (!sv.sound_precache[i][0])
1402                 {
1403                         if (precachemode)
1404                         {
1405                                 if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
1406                                 {
1407                                         Con_Printf("SV_SoundIndex(\"%s\"): precache_sound can only be done in spawn functions\n", filename);
1408                                         return 0;
1409                                 }
1410                                 if (precachemode == 1)
1411                                         Con_Printf("SV_SoundIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
1412                                 strlcpy(sv.sound_precache[i], filename, sizeof(sv.sound_precache[i]));
1413                                 if (sv.state != ss_loading)
1414                                 {
1415                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
1416                                         MSG_WriteShort(&sv.reliable_datagram, i + 32768);
1417                                         MSG_WriteString(&sv.reliable_datagram, filename);
1418                                 }
1419                                 return i;
1420                         }
1421                         Con_Printf("SV_SoundIndex(\"%s\"): not precached\n", filename);
1422                         return 0;
1423                 }
1424                 if (!strcmp(sv.sound_precache[i], filename))
1425                         return i;
1426         }
1427         Con_Printf("SV_SoundIndex(\"%s\"): i (%i) == MAX_SOUNDS (%i)\n", filename, i, MAX_SOUNDS);
1428         return 0;
1429 }
1430
1431 /*
1432 ================
1433 SV_ParticleEffectIndex
1434
1435 ================
1436 */
1437 int SV_ParticleEffectIndex(const char *name)
1438 {
1439         int i, argc, linenumber, effectnameindex;
1440         int filepass;
1441         fs_offset_t filesize;
1442         unsigned char *filedata;
1443         const char *text;
1444         const char *textstart;
1445         //const char *textend;
1446         char argv[16][1024];
1447         char filename[MAX_QPATH];
1448         if (!sv.particleeffectnamesloaded)
1449         {
1450                 sv.particleeffectnamesloaded = true;
1451                 memset(sv.particleeffectname, 0, sizeof(sv.particleeffectname));
1452                 for (i = 0;i < EFFECT_TOTAL;i++)
1453                         strlcpy(sv.particleeffectname[i], standardeffectnames[i], sizeof(sv.particleeffectname[i]));
1454                 for (filepass = 0;;filepass++)
1455                 {
1456                         if (filepass == 0)
1457                                 dpsnprintf(filename, sizeof(filename), "effectinfo.txt");
1458                         else if (filepass == 1)
1459                                 dpsnprintf(filename, sizeof(filename), "%s_effectinfo.txt", sv.worldnamenoextension);
1460                         else
1461                                 break;
1462                         filedata = FS_LoadFile(filename, tempmempool, true, &filesize);
1463                         if (!filedata)
1464                                 continue;
1465                         textstart = (const char *)filedata;
1466                         //textend = (const char *)filedata + filesize;
1467                         text = textstart;
1468                         for (linenumber = 1;;linenumber++)
1469                         {
1470                                 argc = 0;
1471                                 for (;;)
1472                                 {
1473                                         if (!COM_ParseToken_Simple(&text, true, false, true) || !strcmp(com_token, "\n"))
1474                                                 break;
1475                                         if (argc < 16)
1476                                         {
1477                                                 strlcpy(argv[argc], com_token, sizeof(argv[argc]));
1478                                                 argc++;
1479                                         }
1480                                 }
1481                                 if (com_token[0] == 0)
1482                                         break; // if the loop exited and it's not a \n, it's EOF
1483                                 if (argc < 1)
1484                                         continue;
1485                                 if (!strcmp(argv[0], "effect"))
1486                                 {
1487                                         if (argc == 2)
1488                                         {
1489                                                 for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME;effectnameindex++)
1490                                                 {
1491                                                         if (sv.particleeffectname[effectnameindex][0])
1492                                                         {
1493                                                                 if (!strcmp(sv.particleeffectname[effectnameindex], argv[1]))
1494                                                                         break;
1495                                                         }
1496                                                         else
1497                                                         {
1498                                                                 strlcpy(sv.particleeffectname[effectnameindex], argv[1], sizeof(sv.particleeffectname[effectnameindex]));
1499                                                                 break;
1500                                                         }
1501                                                 }
1502                                                 // if we run out of names, abort
1503                                                 if (effectnameindex == MAX_PARTICLEEFFECTNAME)
1504                                                 {
1505                                                         Con_Printf("%s:%i: too many effects!\n", filename, linenumber);
1506                                                         break;
1507                                                 }
1508                                         }
1509                                 }
1510                         }
1511                         Mem_Free(filedata);
1512                 }
1513         }
1514         // search for the name
1515         for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME && sv.particleeffectname[effectnameindex][0];effectnameindex++)
1516                 if (!strcmp(sv.particleeffectname[effectnameindex], name))
1517                         return effectnameindex;
1518         // return 0 if we couldn't find it
1519         return 0;
1520 }
1521
1522 model_t *SV_GetModelByIndex(int modelindex)
1523 {
1524         return (modelindex > 0 && modelindex < MAX_MODELS) ? sv.models[modelindex] : NULL;
1525 }
1526
1527 model_t *SV_GetModelFromEdict(prvm_edict_t *ed)
1528 {
1529         prvm_prog_t *prog = SVVM_prog;
1530         int modelindex;
1531         if (!ed || ed->priv.server->free)
1532                 return NULL;
1533         modelindex = (int)PRVM_serveredictfloat(ed, modelindex);
1534         return (modelindex > 0 && modelindex < MAX_MODELS) ? sv.models[modelindex] : NULL;
1535 }
1536
1537 /*
1538 ================
1539 SV_CreateBaseline
1540
1541 ================
1542 */
1543 static void SV_CreateBaseline (void)
1544 {
1545         prvm_prog_t *prog = SVVM_prog;
1546         int i, entnum, large;
1547         prvm_edict_t *svent;
1548
1549         // LadyHavoc: clear *all* baselines (not just active ones)
1550         for (entnum = 0;entnum < prog->max_edicts;entnum++)
1551         {
1552                 // get the current server version
1553                 svent = PRVM_EDICT_NUM(entnum);
1554
1555                 // LadyHavoc: always clear state values, whether the entity is in use or not
1556                 svent->priv.server->baseline = defaultstate;
1557
1558                 if (svent->priv.server->free)
1559                         continue;
1560                 if (entnum > svs.maxclients && !PRVM_serveredictfloat(svent, modelindex))
1561                         continue;
1562
1563                 // create entity baseline
1564                 VectorCopy (PRVM_serveredictvector(svent, origin), svent->priv.server->baseline.origin);
1565                 VectorCopy (PRVM_serveredictvector(svent, angles), svent->priv.server->baseline.angles);
1566                 svent->priv.server->baseline.frame = (int)PRVM_serveredictfloat(svent, frame);
1567                 svent->priv.server->baseline.skin = (int)PRVM_serveredictfloat(svent, skin);
1568                 if (entnum > 0 && entnum <= svs.maxclients)
1569                 {
1570                         svent->priv.server->baseline.colormap = entnum;
1571                         svent->priv.server->baseline.modelindex = SV_ModelIndex("progs/player.mdl", 1);
1572                 }
1573                 else
1574                 {
1575                         svent->priv.server->baseline.colormap = 0;
1576                         svent->priv.server->baseline.modelindex = (int)PRVM_serveredictfloat(svent, modelindex);
1577                 }
1578
1579                 large = false;
1580                 if (svent->priv.server->baseline.modelindex & 0xFF00 || svent->priv.server->baseline.frame & 0xFF00)
1581                 {
1582                         large = true;
1583                         if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1584                                 large = false;
1585                 }
1586
1587                 // add to the message
1588                 if (large)
1589                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1590                 else
1591                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1592                 MSG_WriteShort (&sv.signon, entnum);
1593
1594                 if (large)
1595                 {
1596                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
1597                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.frame);
1598                 }
1599                 else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1600                 {
1601                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
1602                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
1603                 }
1604                 else
1605                 {
1606                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.modelindex);
1607                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
1608                 }
1609                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.colormap);
1610                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.skin);
1611                 for (i=0 ; i<3 ; i++)
1612                 {
1613                         MSG_WriteCoord(&sv.signon, svent->priv.server->baseline.origin[i], sv.protocol);
1614                         MSG_WriteAngle(&sv.signon, svent->priv.server->baseline.angles[i], sv.protocol);
1615                 }
1616         }
1617 }
1618
1619 /*
1620 ================
1621 SV_Prepare_CSQC
1622
1623 Load csprogs.dat and comperss it so it doesn't need to be
1624 reloaded on request.
1625 ================
1626 */
1627 static void SV_Prepare_CSQC(void)
1628 {
1629         fs_offset_t progsize;
1630
1631         if(svs.csqc_progdata)
1632         {
1633                 Con_DPrintf("Unloading old CSQC data.\n");
1634                 Mem_Free(svs.csqc_progdata);
1635                 if(svs.csqc_progdata_deflated)
1636                         Mem_Free(svs.csqc_progdata_deflated);
1637         }
1638
1639         svs.csqc_progdata = NULL;
1640         svs.csqc_progdata_deflated = NULL;
1641         
1642         sv.csqc_progname[0] = 0;
1643         svs.csqc_progdata = FS_LoadFile(csqc_progname.string, sv_mempool, false, &progsize);
1644
1645         if(progsize > 0)
1646         {
1647                 size_t deflated_size;
1648
1649                 sv.csqc_progsize = (int)progsize;
1650                 sv.csqc_progcrc = CRC_Block(svs.csqc_progdata, progsize);
1651                 strlcpy(sv.csqc_progname, csqc_progname.string, sizeof(sv.csqc_progname));
1652                 Con_DPrintf("server detected csqc progs file \"%s\" with size %i and crc %i\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
1653
1654                 Con_DPrint("Compressing csprogs.dat\n");
1655                 //unsigned char *FS_Deflate(const unsigned char *data, size_t size, size_t *deflated_size, int level, mempool_t *mempool);
1656                 svs.csqc_progdata_deflated = FS_Deflate(svs.csqc_progdata, progsize, &deflated_size, -1, sv_mempool);
1657                 svs.csqc_progsize_deflated = (int)deflated_size;
1658                 if(svs.csqc_progdata_deflated)
1659                 {
1660                         Con_DPrintf("Deflated: %g%%\n", 100.0 - 100.0 * (deflated_size / (float)progsize));
1661                         Con_DPrintf("Uncompressed: %u\nCompressed:   %u\n", (unsigned)sv.csqc_progsize, (unsigned)svs.csqc_progsize_deflated);
1662                 }
1663                 else
1664                         Con_DPrintf("Cannot compress - need zlib for this. Using uncompressed progs only.\n");
1665         }
1666 }
1667
1668 /*
1669 ================
1670 SV_SaveSpawnparms
1671
1672 Grabs the current state of each client for saving across the
1673 transition to another level
1674 ================
1675 */
1676 void SV_SaveSpawnparms (void)
1677 {
1678         prvm_prog_t *prog = SVVM_prog;
1679         int             i, j;
1680
1681         svs.serverflags = (int)PRVM_serverglobalfloat(serverflags);
1682
1683         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1684         {
1685                 if (!host_client->active)
1686                         continue;
1687
1688         // call the progs to get default spawn parms for the new client
1689                 PRVM_serverglobalfloat(time) = sv.time;
1690                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
1691                 prog->ExecuteProgram(prog, PRVM_serverfunction(SetChangeParms), "QC function SetChangeParms is missing");
1692                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1693                         host_client->spawn_parms[j] = (&PRVM_serverglobalfloat(parm1))[j];
1694         }
1695 }
1696
1697 // Returns 1 if we're singleplayer, > 1 if we're a listen server
1698 int SV_IsLocalServer(void)
1699 {
1700         return (host_isclient.integer && sv.active ? svs.maxclients : 0);
1701 }
1702
1703 /*
1704 ================
1705 SV_SpawnServer
1706
1707 This is called at the start of each level
1708 ================
1709 */
1710
1711 void SV_SpawnServer (const char *map)
1712 {
1713         prvm_prog_t *prog = SVVM_prog;
1714         prvm_edict_t *ent;
1715         int i;
1716         char *entities;
1717         model_t *worldmodel;
1718         char modelname[sizeof(sv.worldname)];
1719         char vabuf[1024];
1720
1721         Con_Printf("SpawnServer: %s\n", map);
1722
1723         dpsnprintf (modelname, sizeof(modelname), "maps/%s.bsp", map);
1724
1725         if (!FS_FileExists(modelname))
1726         {
1727                 dpsnprintf (modelname, sizeof(modelname), "maps/%s", map);
1728                 if (!FS_FileExists(modelname))
1729                 {
1730                         Con_Printf("SpawnServer: no map file named %s\n", modelname);
1731                         return;
1732                 }
1733         }
1734
1735 //      SV_LockThreadMutex();
1736
1737         if(!host_isclient.integer)
1738                 Sys_MakeProcessNice();
1739         else
1740         {
1741                 SCR_BeginLoadingPlaque(false);
1742                 S_StopAllSounds();
1743         }
1744
1745         if(sv.active)
1746         {
1747                 client_t *client;
1748                 for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
1749                 {
1750                         if (client->netconnection)
1751                         {
1752                                 MSG_WriteByte(&client->netconnection->message, svc_stufftext);
1753                                 MSG_WriteString(&client->netconnection->message, "reconnect\n");
1754                         }
1755                 }
1756                 World_End(&sv.world);
1757                 if(PRVM_serverfunction(SV_Shutdown))
1758                 {
1759                         func_t s = PRVM_serverfunction(SV_Shutdown);
1760                         PRVM_serverglobalfloat(time) = sv.time;
1761                         PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
1762                         prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
1763                 }
1764         }
1765
1766         // free q3 shaders so that any newly downloaded shaders will be active
1767         Mod_FreeQ3Shaders();
1768
1769         worldmodel = Mod_ForName(modelname, false, developer.integer > 0, NULL);
1770         if (!worldmodel || !worldmodel->TraceBox)
1771         {
1772                 Con_Printf("Couldn't load map %s\n", modelname);
1773
1774                 if(!host_isclient.integer)
1775                         Sys_MakeProcessMean();
1776
1777 //              SV_UnlockThreadMutex();
1778
1779                 return;
1780         }
1781
1782         Collision_Cache_Reset(true);
1783
1784         // let's not have any servers with no name
1785         if (hostname.string[0] == 0)
1786                 Cvar_SetQuick(&hostname, "UNNAMED");
1787         scr_centertime_off = 0;
1788
1789         svs.changelevel_issued = false;         // now safe to issue another
1790
1791         // make the map a required file for clients
1792         Curl_ClearRequirements();
1793         Curl_RequireFile(modelname);
1794
1795 //
1796 // tell all connected clients that we are going to a new level
1797 //
1798         if (!sv.active)
1799                 NetConn_OpenServerPorts(true);
1800
1801 //
1802 // make cvars consistant
1803 //
1804         if (coop.integer)
1805                 Cvar_SetValueQuick(&deathmatch, 0);
1806         // LadyHavoc: it can be useful to have skills outside the range 0-3...
1807         //current_skill = bound(0, (int)(skill.value + 0.5), 3);
1808         //Cvar_SetValue ("skill", (float)current_skill);
1809         current_skill = (int)(skill.value + 0.5);
1810
1811 //
1812 // set up the new server
1813 //
1814         memset (&sv, 0, sizeof(sv));
1815         // if running a local client, make sure it doesn't try to access the last
1816         // level's data which is no longer valiud
1817         cls.signon = 0;
1818
1819         Cvar_SetValueQuick(&halflifebsp, worldmodel->brush.ishlbsp);
1820         Cvar_SetValueQuick(&sv_mapformat_is_quake2, worldmodel->brush.isq2bsp);
1821         Cvar_SetValueQuick(&sv_mapformat_is_quake3, worldmodel->brush.isq3bsp);
1822
1823         if(*sv_random_seed.string)
1824         {
1825                 srand(sv_random_seed.integer);
1826                 Con_Printf(CON_WARN "NOTE: random seed is %d; use for debugging/benchmarking only!\nUnset sv_random_seed to get real random numbers again.\n", sv_random_seed.integer);
1827         }
1828
1829         SV_VM_Setup();
1830
1831         sv.active = true;
1832
1833         // set level base name variables for later use
1834         strlcpy (sv.name, map, sizeof (sv.name));
1835         strlcpy(sv.worldname, modelname, sizeof(sv.worldname));
1836         FS_StripExtension(sv.worldname, sv.worldnamenoextension, sizeof(sv.worldnamenoextension));
1837         strlcpy(sv.worldbasename, !strncmp(sv.worldnamenoextension, "maps/", 5) ? sv.worldnamenoextension + 5 : sv.worldnamenoextension, sizeof(sv.worldbasename));
1838         //Cvar_SetQuick(&sv_worldmessage, sv.worldmessage); // set later after QC is spawned
1839         Cvar_SetQuick(&sv_worldname, sv.worldname);
1840         Cvar_SetQuick(&sv_worldnamenoextension, sv.worldnamenoextension);
1841         Cvar_SetQuick(&sv_worldbasename, sv.worldbasename);
1842
1843         sv.protocol = Protocol_EnumForName(sv_protocolname.string);
1844         if (sv.protocol == PROTOCOL_UNKNOWN)
1845         {
1846                 char buffer[1024];
1847                 Protocol_Names(buffer, sizeof(buffer));
1848                 Con_Printf(CON_ERROR "Unknown sv_protocolname \"%s\", valid values are:\n%s\n", sv_protocolname.string, buffer);
1849                 sv.protocol = PROTOCOL_QUAKE;
1850         }
1851
1852 // load progs to get entity field count
1853         //PR_LoadProgs ( sv_progs.string );
1854
1855         sv.datagram.maxsize = sizeof(sv.datagram_buf);
1856         sv.datagram.cursize = 0;
1857         sv.datagram.data = sv.datagram_buf;
1858
1859         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1860         sv.reliable_datagram.cursize = 0;
1861         sv.reliable_datagram.data = sv.reliable_datagram_buf;
1862
1863         sv.signon.maxsize = sizeof(sv.signon_buf);
1864         sv.signon.cursize = 0;
1865         sv.signon.data = sv.signon_buf;
1866
1867 // leave slots at start for clients only
1868         //prog->num_edicts = svs.maxclients+1;
1869
1870         sv.state = ss_loading;
1871         prog->allowworldwrites = true;
1872         sv.paused = false;
1873
1874         sv.time = 1.0;
1875
1876         Mod_ClearUsed();
1877         worldmodel->used = true;
1878
1879         sv.worldmodel = worldmodel;
1880         sv.models[1] = sv.worldmodel;
1881
1882 //
1883 // clear world interaction links
1884 //
1885         World_SetSize(&sv.world, sv.worldname, sv.worldmodel->normalmins, sv.worldmodel->normalmaxs, prog);
1886         World_Start(&sv.world);
1887
1888         strlcpy(sv.sound_precache[0], "", sizeof(sv.sound_precache[0]));
1889
1890         strlcpy(sv.model_precache[0], "", sizeof(sv.model_precache[0]));
1891         strlcpy(sv.model_precache[1], sv.worldname, sizeof(sv.model_precache[1]));
1892         for (i = 1;i < sv.worldmodel->brush.numsubmodels && i+1 < MAX_MODELS;i++)
1893         {
1894                 dpsnprintf(sv.model_precache[i+1], sizeof(sv.model_precache[i+1]), "*%i", i);
1895                 sv.models[i+1] = Mod_ForName (sv.model_precache[i+1], false, false, sv.worldname);
1896         }
1897         if(i < sv.worldmodel->brush.numsubmodels)
1898                 Con_Printf("Too many submodels (MAX_MODELS is %i)\n", MAX_MODELS);
1899
1900 //
1901 // load the rest of the entities
1902 //
1903         // AK possible hack since num_edicts is still 0
1904         ent = PRVM_EDICT_NUM(0);
1905         memset (ent->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
1906         ent->priv.server->free = false;
1907         PRVM_serveredictstring(ent, model) = PRVM_SetEngineString(prog, sv.worldname);
1908         PRVM_serveredictfloat(ent, modelindex) = 1;             // world model
1909         PRVM_serveredictfloat(ent, solid) = SOLID_BSP;
1910         PRVM_serveredictfloat(ent, movetype) = MOVETYPE_PUSH;
1911         VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, mins));
1912         VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, maxs));
1913         VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, absmin));
1914         VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, absmax));
1915
1916         if (coop.value)
1917                 PRVM_serverglobalfloat(coop) = coop.integer;
1918         else
1919                 PRVM_serverglobalfloat(deathmatch) = deathmatch.integer;
1920
1921         PRVM_serverglobalstring(mapname) = PRVM_SetEngineString(prog, sv.name);
1922
1923 // serverflags are for cross level information (sigils)
1924         PRVM_serverglobalfloat(serverflags) = svs.serverflags;
1925
1926         // we need to reset the spawned flag on all connected clients here so that
1927         // their thinks don't run during startup (before PutClientInServer)
1928         // we also need to set up the client entities now
1929         // and we need to set the ->edict pointers to point into the progs edicts
1930         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1931         {
1932                 host_client->begun = false;
1933                 host_client->edict = PRVM_EDICT_NUM(i + 1);
1934                 PRVM_ED_ClearEdict(prog, host_client->edict);
1935         }
1936
1937         // load replacement entity file if found
1938         if (sv_entpatch.integer && (entities = (char *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), tempmempool, true, NULL)))
1939         {
1940                 Con_Printf("Loaded %s.ent\n", sv.worldnamenoextension);
1941                 PRVM_ED_LoadFromFile(prog, entities);
1942                 Mem_Free(entities);
1943         }
1944         else
1945                 PRVM_ED_LoadFromFile(prog, sv.worldmodel->brush.entities);
1946
1947
1948         // LadyHavoc: clear world angles (to fix e3m3.bsp)
1949         VectorClear(PRVM_serveredictvector(prog->edicts, angles));
1950
1951 // all setup is completed, any further precache statements are errors
1952 //      sv.state = ss_active; // LadyHavoc: workaround for svc_precache bug
1953         prog->allowworldwrites = false;
1954
1955 // run two frames to allow everything to settle
1956         sv.time = 1.0001;
1957         for (i = 0;i < sv_init_frame_count.integer;i++)
1958         {
1959                 sv.frametime = 0.1;
1960                 SV_Physics ();
1961         }
1962
1963         // Once all init frames have been run, we consider svqc code fully initialized.
1964         prog->inittime = host.realtime;
1965
1966         if(!host_isclient.integer)
1967                 Mod_PurgeUnused();
1968
1969 // create a baseline for more efficient communications
1970         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1971                 SV_CreateBaseline ();
1972
1973         sv.state = ss_active; // LadyHavoc: workaround for svc_precache bug
1974
1975 // send serverinfo to all connected clients, and set up botclients coming back from a level change
1976         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1977         {
1978                 host_client->clientconnectcalled = false; // do NOT call ClientDisconnect if he drops before ClientConnect!
1979                 if (!host_client->active)
1980                         continue;
1981                 if (host_client->netconnection)
1982                         SV_SendServerinfo(host_client);
1983                 else
1984                 {
1985                         int j;
1986                         // if client is a botclient coming from a level change, we need to
1987                         // set up client info that normally requires networking
1988
1989                         // copy spawn parms out of the client_t
1990                         for (j=0 ; j< NUM_SPAWN_PARMS ; j++)
1991                                 (&PRVM_serverglobalfloat(parm1))[j] = host_client->spawn_parms[j];
1992
1993                         // call the spawn function
1994                         host_client->clientconnectcalled = true;
1995                         PRVM_serverglobalfloat(time) = sv.time;
1996                         PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
1997                         prog->ExecuteProgram(prog, PRVM_serverfunction(ClientConnect), "QC function ClientConnect is missing");
1998                         prog->ExecuteProgram(prog, PRVM_serverfunction(PutClientInServer), "QC function PutClientInServer is missing");
1999                         host_client->begun = true;
2000                 }
2001         }
2002
2003         // update the map title cvar
2004         strlcpy(sv.worldmessage, PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)), sizeof(sv.worldmessage)); // map title (not related to filename)
2005         Cvar_SetQuick(&sv_worldmessage, sv.worldmessage);
2006
2007         Con_Printf("Server spawned.\n");
2008         NetConn_Heartbeat (2);
2009
2010         if(!host_isclient.integer)
2011                 Sys_MakeProcessMean();
2012
2013 //      SV_UnlockThreadMutex();
2014 }
2015
2016 /*
2017 ==================
2018 SV_Shutdown
2019
2020 This only happens at the end of a game, not between levels
2021 ==================
2022 */
2023 void SV_Shutdown(void)
2024 {
2025         prvm_prog_t *prog = SVVM_prog;
2026         int i;
2027
2028         Con_DPrintf("SV_Shutdown\n");
2029
2030         if (!sv.active)
2031                 return;
2032
2033         NetConn_Heartbeat(2);
2034         NetConn_Heartbeat(2);
2035
2036 // make sure all the clients know we're disconnecting
2037         World_End(&sv.world);
2038         if(prog->loaded)
2039         {
2040                 if(PRVM_serverfunction(SV_Shutdown))
2041                 {
2042                         func_t s = PRVM_serverfunction(SV_Shutdown);
2043                         PRVM_serverglobalfloat(time) = sv.time;
2044                         PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
2045                         prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
2046                 }
2047         }
2048         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2049                 if (host_client->active)
2050                         SV_DropClient(false); // server shutdown
2051
2052         NetConn_CloseServerPorts();
2053
2054         sv.active = false;
2055 //
2056 // clear structures
2057 //
2058         memset(&sv, 0, sizeof(sv));
2059         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
2060
2061         cl.islocalgame = false;
2062 }
2063
2064 /////////////////////////////////////////////////////
2065 // SV VM stuff
2066
2067 static void SVVM_begin_increase_edicts(prvm_prog_t *prog)
2068 {
2069         // links don't survive the transition, so unlink everything
2070         World_UnlinkAll(&sv.world);
2071 }
2072
2073 static void SVVM_end_increase_edicts(prvm_prog_t *prog)
2074 {
2075         int i;
2076         prvm_edict_t *ent;
2077
2078         // link every entity except world
2079         for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
2080                 if (!ent->priv.server->free && !VectorCompare(PRVM_serveredictvector(ent, absmin), PRVM_serveredictvector(ent, absmax)))
2081                         SV_LinkEdict(ent);
2082 }
2083
2084 static void SVVM_init_edict(prvm_prog_t *prog, prvm_edict_t *e)
2085 {
2086         // LadyHavoc: for consistency set these here
2087         int num = PRVM_NUM_FOR_EDICT(e) - 1;
2088
2089         e->priv.server->move = false; // don't move on first frame
2090
2091         if (num >= 0 && num < svs.maxclients)
2092         {
2093                 // set colormap and team on newly created player entity
2094                 PRVM_serveredictfloat(e, colormap) = num + 1;
2095                 PRVM_serveredictfloat(e, team) = (svs.clients[num].colors & 15) + 1;
2096                 // set netname/clientcolors back to client values so that
2097                 // DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS will not immediately
2098                 // reset them
2099                 PRVM_serveredictstring(e, netname) = PRVM_SetEngineString(prog, svs.clients[num].name);
2100                 PRVM_serveredictfloat(e, clientcolors) = svs.clients[num].colors;
2101                 // NEXUIZ_PLAYERMODEL and NEXUIZ_PLAYERSKIN
2102                 PRVM_serveredictstring(e, playermodel) = PRVM_SetEngineString(prog, svs.clients[num].playermodel);
2103                 PRVM_serveredictstring(e, playerskin) = PRVM_SetEngineString(prog, svs.clients[num].playerskin);
2104                 // Assign netaddress (IP Address, etc)
2105                 if(svs.clients[num].netconnection != NULL)
2106                 {
2107                         // Acquire Readable Address
2108                         LHNETADDRESS_ToString(&svs.clients[num].netconnection->peeraddress, svs.clients[num].netaddress, sizeof(svs.clients[num].netaddress), false);
2109                         PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, svs.clients[num].netaddress);
2110                 }
2111                 else
2112                         PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, "null/botclient");
2113                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_idfp[0])
2114                         PRVM_serveredictstring(e, crypto_idfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_idfp);
2115                 else
2116                         PRVM_serveredictstring(e, crypto_idfp) = 0;
2117                 PRVM_serveredictfloat(e, crypto_idfp_signed) = (svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_issigned);
2118                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_keyfp[0])
2119                         PRVM_serveredictstring(e, crypto_keyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_keyfp);
2120                 else
2121                         PRVM_serveredictstring(e, crypto_keyfp) = 0;
2122                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.server_keyfp[0])
2123                         PRVM_serveredictstring(e, crypto_mykeyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.server_keyfp);
2124                 else
2125                         PRVM_serveredictstring(e, crypto_mykeyfp) = 0;
2126                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.use_aes)
2127                         PRVM_serveredictstring(e, crypto_encryptmethod) = PRVM_SetEngineString(prog, "AES128");
2128                 else
2129                         PRVM_serveredictstring(e, crypto_encryptmethod) = 0;
2130                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated)
2131                         PRVM_serveredictstring(e, crypto_signmethod) = PRVM_SetEngineString(prog, "HMAC-SHA256");
2132                 else
2133                         PRVM_serveredictstring(e, crypto_signmethod) = 0;
2134         }
2135 }
2136
2137 static void SVVM_free_edict(prvm_prog_t *prog, prvm_edict_t *ed)
2138 {
2139         int i;
2140         int e;
2141
2142         World_UnlinkEdict(ed);          // unlink from world bsp
2143
2144         PRVM_serveredictstring(ed, model) = 0;
2145         PRVM_serveredictfloat(ed, takedamage) = 0;
2146         PRVM_serveredictfloat(ed, modelindex) = 0;
2147         PRVM_serveredictfloat(ed, colormap) = 0;
2148         PRVM_serveredictfloat(ed, skin) = 0;
2149         PRVM_serveredictfloat(ed, frame) = 0;
2150         VectorClear(PRVM_serveredictvector(ed, origin));
2151         VectorClear(PRVM_serveredictvector(ed, angles));
2152         PRVM_serveredictfloat(ed, nextthink) = -1;
2153         PRVM_serveredictfloat(ed, solid) = 0;
2154
2155         VM_RemoveEdictSkeleton(prog, ed);
2156         World_Physics_RemoveFromEntity(&sv.world, ed);
2157         World_Physics_RemoveJointFromEntity(&sv.world, ed);
2158
2159         // make sure csqc networking is aware of the removed entity
2160         e = PRVM_NUM_FOR_EDICT(ed);
2161         sv.csqcentityversion[e] = 0;
2162         for (i = 0;i < svs.maxclients;i++)
2163                 svs.clients[i].csqcentitysendflags[e] = 0xFFFFFF;
2164 }
2165
2166 static void SVVM_count_edicts(prvm_prog_t *prog)
2167 {
2168         int             i;
2169         prvm_edict_t    *ent;
2170         int             active, models, solid, step;
2171
2172         active = models = solid = step = 0;
2173         for (i=0 ; i<prog->num_edicts ; i++)
2174         {
2175                 ent = PRVM_EDICT_NUM(i);
2176                 if (ent->priv.server->free)
2177                         continue;
2178                 active++;
2179                 if (PRVM_serveredictfloat(ent, solid))
2180                         solid++;
2181                 if (PRVM_serveredictstring(ent, model))
2182                         models++;
2183                 if (PRVM_serveredictfloat(ent, movetype) == MOVETYPE_STEP)
2184                         step++;
2185         }
2186
2187         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
2188         Con_Printf("active    :%3i\n", active);
2189         Con_Printf("view      :%3i\n", models);
2190         Con_Printf("touch     :%3i\n", solid);
2191         Con_Printf("step      :%3i\n", step);
2192 }
2193
2194 static qbool SVVM_load_edict(prvm_prog_t *prog, prvm_edict_t *ent)
2195 {
2196         // remove things from different skill levels or deathmatch
2197         if (gamemode != GAME_TRANSFUSION) //Transfusion does this in QC
2198         {
2199                 if (deathmatch.integer)
2200                 {
2201                         if (((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_DEATHMATCH))
2202                         {
2203                                 return false;
2204                         }
2205                 }
2206                 else if ((current_skill <= 0 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_EASY  ))
2207                         || (current_skill == 1 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_MEDIUM))
2208                         || (current_skill >= 2 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_HARD  )))
2209                 {
2210                         return false;
2211                 }
2212         }
2213         return true;
2214 }
2215
2216 static void SV_VM_Setup(void)
2217 {
2218         prvm_prog_t *prog = SVVM_prog;
2219         PRVM_Prog_Init(prog, &cmd_server);
2220
2221         // allocate the mempools
2222         // TODO: move the magic numbers/constants into #defines [9/13/2006 Black]
2223         prog->progs_mempool = Mem_AllocPool("Server Progs", 0, NULL);
2224         prog->builtins = vm_sv_builtins;
2225         prog->numbuiltins = vm_sv_numbuiltins;
2226         prog->max_edicts = 512;
2227         if (sv.protocol == PROTOCOL_QUAKE)
2228                 prog->limit_edicts = 640; // before quake mission pack 1 this was 512
2229         else if (sv.protocol == PROTOCOL_QUAKEDP)
2230                 prog->limit_edicts = 2048; // guessing
2231         else if (sv.protocol == PROTOCOL_NEHAHRAMOVIE)
2232                 prog->limit_edicts = 2048; // guessing!
2233         else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
2234                 prog->limit_edicts = 4096; // guessing!
2235         else
2236                 prog->limit_edicts = MAX_EDICTS;
2237         prog->reserved_edicts = svs.maxclients;
2238         prog->edictprivate_size = sizeof(edict_engineprivate_t);
2239         prog->name = "server";
2240         prog->extensionstring = vm_sv_extensions;
2241         prog->loadintoworld = true;
2242
2243         // all callbacks must be defined (pointers are not checked before calling)
2244         prog->begin_increase_edicts = SVVM_begin_increase_edicts;
2245         prog->end_increase_edicts   = SVVM_end_increase_edicts;
2246         prog->init_edict            = SVVM_init_edict;
2247         prog->free_edict            = SVVM_free_edict;
2248         prog->count_edicts          = SVVM_count_edicts;
2249         prog->load_edict            = SVVM_load_edict;
2250         prog->init_cmd              = SVVM_init_cmd;
2251         prog->reset_cmd             = SVVM_reset_cmd;
2252         prog->error_cmd             = Host_Error;
2253         prog->ExecuteProgram        = SVVM_ExecuteProgram;
2254
2255         PRVM_Prog_Load(prog, sv_progs.string, NULL, 0, SV_REQFUNCS, sv_reqfuncs, SV_REQFIELDS, sv_reqfields, SV_REQGLOBALS, sv_reqglobals);
2256
2257         // some mods compiled with scrambling compilers lack certain critical
2258         // global names and field names such as "self" and "time" and "nextthink"
2259         // so we have to set these offsets manually, matching the entvars_t
2260         // but we only do this if the prog header crc matches, otherwise it's totally freeform
2261         if (prog->progs_crc == PROGHEADER_CRC || prog->progs_crc == PROGHEADER_CRC_TENEBRAE)
2262         {
2263                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, modelindex);
2264                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmin);
2265                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmax);
2266                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ltime);
2267                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movetype);
2268                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, solid);
2269                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, origin);
2270                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, oldorigin);
2271                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, velocity);
2272                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, angles);
2273                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, avelocity);
2274                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, punchangle);
2275                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, classname);
2276                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, model);
2277                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frame);
2278                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, skin);
2279                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, effects);
2280                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, mins);
2281                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, maxs);
2282                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, size);
2283                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, touch);
2284                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, use);
2285                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, think);
2286                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, blocked);
2287                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, nextthink);
2288                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, groundentity);
2289                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, health);
2290                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frags);
2291                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weapon);
2292                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponmodel);
2293                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponframe);
2294                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, currentammo);
2295                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_shells);
2296                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_nails);
2297                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_rockets);
2298                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_cells);
2299                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, items);
2300                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, takedamage);
2301                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, chain);
2302                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, deadflag);
2303                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, view_ofs);
2304                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button0);
2305                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button1);
2306                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button2);
2307                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, impulse);
2308                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, fixangle);
2309                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, v_angle);
2310                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, idealpitch);
2311                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, netname);
2312                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, enemy);
2313                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, flags);
2314                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, colormap);
2315                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, team);
2316                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, max_health);
2317                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, teleport_time);
2318                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armortype);
2319                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armorvalue);
2320                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, waterlevel);
2321                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, watertype);
2322                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ideal_yaw);
2323                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, yaw_speed);
2324                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, aiment);
2325                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, goalentity);
2326                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, spawnflags);
2327                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, target);
2328                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, targetname);
2329                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_take);
2330                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_save);
2331                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_inflictor);
2332                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, owner);
2333                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movedir);
2334                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, message);
2335                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, sounds);
2336                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise);
2337                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise1);
2338                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise2);
2339                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise3);
2340                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, self);
2341                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, other);
2342                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, world);
2343                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, time);
2344                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, frametime);
2345                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, force_retouch);
2346                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, mapname);
2347                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, deathmatch);
2348                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, coop);
2349                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, teamplay);
2350                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, serverflags);
2351                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_secrets);
2352                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_monsters);
2353                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, found_secrets);
2354                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, killed_monsters);
2355                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm1);
2356                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm2);
2357                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm3);
2358                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm4);
2359                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm5);
2360                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm6);
2361                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm7);
2362                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm8);
2363                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm9);
2364                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm10);
2365                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm11);
2366                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm12);
2367                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm13);
2368                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm14);
2369                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm15);
2370                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm16);
2371                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_forward);
2372                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_up);
2373                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_right);
2374                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_allsolid);
2375                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_startsolid);
2376                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_fraction);
2377                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_endpos);
2378                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_normal);
2379                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_dist);
2380                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_ent);
2381                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inopen);
2382                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inwater);
2383                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, msg_entity);
2384 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, main);
2385 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, StartFrame);
2386 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPreThink);
2387 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPostThink);
2388 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientKill);
2389 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientConnect);
2390 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PutClientInServer);
2391 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientDisconnect);
2392 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetNewParms);
2393 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetChangeParms);
2394         }
2395         else
2396                 Con_DPrintf("%s: %s system vars have been modified (CRC %i != engine %i), will not load in other engines\n", prog->name, sv_progs.string, prog->progs_crc, PROGHEADER_CRC);
2397
2398         // OP_STATE is always supported on server because we add fields/globals for it
2399         prog->flag |= PRVM_OP_STATE;
2400
2401         VM_CustomStats_Clear();//[515]: csqc
2402
2403         SV_Prepare_CSQC();
2404 }
2405
2406 static void SV_CheckTimeouts(void)
2407 {
2408         int i;
2409
2410         // never timeout loopback connections
2411         for (i = (host_isclient.integer ? 1 : 0), host_client = &svs.clients[i]; i < svs.maxclients; i++, host_client++)
2412         {
2413                 if (host_client->netconnection && host.realtime > host_client->netconnection->timeout)
2414                 {
2415                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2416                         SV_DropClient(false);
2417                 }
2418         }
2419 }
2420
2421 extern cvar_t host_maxwait;
2422 extern cvar_t host_framerate;
2423 extern cvar_t cl_maxphysicsframesperserverframe;
2424 double SV_Frame(double time)
2425 {
2426         static double sv_timer;
2427         int i;
2428         char vabuf[1024];
2429         qbool playing = false;
2430
2431         if (!svs.threaded)
2432         {
2433                 svs.perf_acc_sleeptime = host.sleeptime;
2434                 svs.perf_acc_realtime += time;
2435
2436                 // Look for clients who have spawned
2437                 for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++)
2438                         if(host_client->begun && host_client->netconnection)
2439                                 playing = true;
2440
2441                 if(svs.perf_acc_realtime > 5)
2442                 {
2443                         svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
2444                         svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
2445
2446                         if(svs.perf_acc_offset_samples > 0)
2447                         {
2448                                 svs.perf_offset_max = svs.perf_acc_offset_max;
2449                                 svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
2450                                 svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
2451                         }
2452
2453                         if(svs.perf_lost > 0 && developer_extra.integer && playing) // only complain if anyone is looking
2454                                 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
2455                 }
2456
2457                 if(svs.perf_acc_realtime > 5 || sv.time < 10)
2458                 {
2459                         /*
2460                          * Don't accumulate time for the first 10 seconds of a match
2461                          * so things can settle
2462                          */
2463                         svs.perf_acc_realtime = svs.perf_acc_sleeptime =
2464                         svs.perf_acc_lost = svs.perf_acc_offset =
2465                         svs.perf_acc_offset_squared = svs.perf_acc_offset_max =
2466                         svs.perf_acc_offset_samples = host.sleeptime = 0;
2467                 }
2468
2469                 /*
2470                  * Receive packets on each main loop iteration, as the main loop may
2471                  * be undersleeping due to select() detecting a new packet
2472                  */
2473                 if (sv.active)
2474                 {
2475                         NetConn_ServerFrame();
2476                         SV_CheckTimeouts();
2477                 }
2478         }
2479
2480         /*
2481          * If the accumulator hasn't become positive, don't
2482          * run the frame. Everything that happens before this
2483          * point will happen even if we're sleeping this frame.
2484          */
2485         if((sv_timer += time) < 0)
2486                 return sv_timer;
2487
2488         // limit the frametime steps to no more than 100ms each
2489         if (sv_timer > 0.1)
2490         {
2491                 if (!svs.threaded)
2492                         svs.perf_acc_lost += (sv_timer - 0.1);
2493                 sv_timer = 0.1;
2494         }
2495
2496         if (sv.active && sv_timer > 0 && !svs.threaded)
2497         {
2498                 /*
2499                  * Execute one or more server frames, with an upper limit on how much
2500                  * execution time to spend on server frames to avoid freezing the game if
2501                  * the server is overloaded. This execution time limit means the game will
2502                  * slow down if the server is taking too long.
2503                  */
2504                 int framecount, framelimit = 1;
2505                 double advancetime, aborttime = 0;
2506                 float offset;
2507                 prvm_prog_t *prog = SVVM_prog;
2508
2509                 // run the world state
2510                 // don't allow simulation to run too fast or too slow or logic glitches can occur
2511
2512                 // stop running server frames if the wall time reaches this value
2513                 if (sys_ticrate.value <= 0)
2514                         advancetime = sv_timer;
2515                 else
2516                 {
2517                         advancetime = sys_ticrate.value;
2518                         // listen servers can run multiple server frames per client frame
2519                         framelimit = cl_maxphysicsframesperserverframe.integer;
2520                         aborttime = Sys_DirtyTime() + 0.1;
2521                 }
2522
2523                 if(host_timescale.value > 0 && host_timescale.value < 1)
2524                         advancetime = min(advancetime, 0.1 / host_timescale.value);
2525                 else
2526                         advancetime = min(advancetime, 0.1);
2527
2528                 if(advancetime > 0)
2529                 {
2530                         offset = Sys_DirtyTime() - host.dirtytime;
2531                         if (offset < 0 || offset >= 1800)
2532                                 offset = 0;
2533
2534                         offset += sv_timer;
2535                         ++svs.perf_acc_offset_samples;
2536                         svs.perf_acc_offset += offset;
2537                         svs.perf_acc_offset_squared += offset * offset;
2538                         
2539                         if(svs.perf_acc_offset_max < offset)
2540                                 svs.perf_acc_offset_max = offset;
2541                 }
2542
2543                 // only advance time if not paused
2544                 // the game also pauses in singleplayer when menu or console is used
2545                 sv.frametime = advancetime * host_timescale.value;
2546                 if (host_framerate.value)
2547                         sv.frametime = host_framerate.value;
2548                 if (sv.paused || host.paused)
2549                         sv.frametime = 0;
2550
2551                 for (framecount = 0; framecount < framelimit && sv_timer > 0; framecount++)
2552                 {
2553                         sv_timer -= advancetime;
2554
2555                         // move things around and think unless paused
2556                         if (sv.frametime)
2557                                 SV_Physics();
2558
2559                         // if this server frame took too long, break out of the loop
2560                         if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
2561                                 break;
2562                 }
2563
2564                 R_TimeReport("serverphysics");
2565
2566                 // send all messages to the clients
2567                 SV_SendClientMessages();
2568
2569                 if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
2570                         prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
2571                         PRVM_serverglobalfloat(time) = sv.time;
2572                         prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
2573                 }
2574
2575                 // send an heartbeat if enough time has passed since the last one
2576                 NetConn_Heartbeat(0);
2577                 R_TimeReport("servernetwork");
2578         }
2579         else
2580         {
2581                 // don't let r_speeds display jump around
2582                 R_TimeReport("serverphysics");
2583                 R_TimeReport("servernetwork");
2584         }
2585
2586         // if there is some time remaining from this frame, reset the timer
2587         if (sv_timer >= 0)
2588         {
2589                 if (!svs.threaded)
2590                         svs.perf_acc_lost += sv_timer;
2591                 sv_timer = 0;
2592         }
2593
2594         return sv_timer;
2595 }
2596
2597 static int SV_ThreadFunc(void *voiddata)
2598 {
2599         prvm_prog_t *prog = SVVM_prog;
2600         qbool playing = false;
2601         double sv_timer = 0;
2602         double sv_deltarealtime, sv_oldrealtime, sv_realtime;
2603         double wait;
2604         int i;
2605         char vabuf[1024];
2606         sv_realtime = Sys_DirtyTime();
2607         while (!svs.threadstop)
2608         {
2609                 // FIXME: we need to handle Host_Error in the server thread somehow
2610 //              if (setjmp(sv_abortframe))
2611 //                      continue;                       // something bad happened in the server game
2612
2613                 sv_oldrealtime = sv_realtime;
2614                 sv_realtime = Sys_DirtyTime();
2615                 sv_deltarealtime = sv_realtime - sv_oldrealtime;
2616                 if (sv_deltarealtime < 0 || sv_deltarealtime >= 1800) sv_deltarealtime = 0;
2617
2618                 sv_timer += sv_deltarealtime;
2619
2620                 svs.perf_acc_realtime += sv_deltarealtime;
2621
2622                 // at this point we start doing real server work, and must block on any client activity pertaining to the server (such as executing SV_SpawnServer)
2623                 SV_LockThreadMutex();
2624
2625                 // Look for clients who have spawned
2626                 playing = false;
2627                 if (sv.active)
2628                         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2629                                 if(host_client->begun)
2630                                         if(host_client->netconnection)
2631                                                 playing = true;
2632                 if(sv.time < 10)
2633                 {
2634                         // don't accumulate time for the first 10 seconds of a match
2635                         // so things can settle
2636                         svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
2637                 }
2638                 else if(svs.perf_acc_realtime > 5)
2639                 {
2640                         svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
2641                         svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
2642                         if(svs.perf_acc_offset_samples > 0)
2643                         {
2644                                 svs.perf_offset_max = svs.perf_acc_offset_max;
2645                                 svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
2646                                 svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
2647                         }
2648                         if(svs.perf_lost > 0 && developer_extra.integer)
2649                                 if(playing)
2650                                         Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
2651                         svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
2652                 }
2653
2654                 // get new packets
2655                 if (sv.active)
2656                 {
2657                         NetConn_ServerFrame();
2658                         SV_CheckTimeouts();
2659                 }
2660
2661                 // if the accumulators haven't become positive yet, wait a while
2662                 wait = sv_timer * -1000000.0;
2663                 if (wait >= 1)
2664                 {
2665                         double time0, delta;
2666                         SV_UnlockThreadMutex(); // don't keep mutex locked while sleeping
2667                         if (host_maxwait.value <= 0)
2668                                 wait = min(wait, 1000000.0);
2669                         else
2670                                 wait = min(wait, host_maxwait.value * 1000.0);
2671                         if(wait < 1)
2672                                 wait = 1; // because we cast to int
2673                         time0 = Sys_DirtyTime();
2674                         Sys_Sleep((int)wait);
2675                         delta = Sys_DirtyTime() - time0;if (delta < 0 || delta >= 1800) delta = 0;
2676                         svs.perf_acc_sleeptime += delta;
2677                         continue;
2678                 }
2679
2680                 if (sv.active && sv_timer > 0)
2681                 {
2682                         // execute one server frame
2683                         double advancetime;
2684                         float offset;
2685
2686                         if (sys_ticrate.value <= 0)
2687                                 advancetime = min(sv_timer, 0.1); // don't step more than 100ms
2688                         else
2689                                 advancetime = sys_ticrate.value;
2690
2691                         if(advancetime > 0)
2692                         {
2693                                 offset = sv_timer + (Sys_DirtyTime() - sv_realtime); // LadyHavoc: FIXME: I don't understand this line
2694                                 ++svs.perf_acc_offset_samples;
2695                                 svs.perf_acc_offset += offset;
2696                                 svs.perf_acc_offset_squared += offset * offset;
2697                                 if(svs.perf_acc_offset_max < offset)
2698                                         svs.perf_acc_offset_max = offset;
2699                         }
2700
2701                         // only advance time if not paused
2702                         // the game also pauses in singleplayer when menu or console is used
2703                         sv.frametime = advancetime * host_timescale.value;
2704                         if (host_framerate.value)
2705                                 sv.frametime = host_framerate.value;
2706                         if (sv.paused || host.paused)
2707                                 sv.frametime = 0;
2708
2709                         sv_timer -= advancetime;
2710
2711                         // move things around and think unless paused
2712                         if (sv.frametime)
2713                                 SV_Physics();
2714
2715                         // send all messages to the clients
2716                         SV_SendClientMessages();
2717
2718                         if (sv.paused == 1 && sv_realtime > sv.pausedstart && sv.pausedstart > 0)
2719                         {
2720                                 PRVM_serverglobalfloat(time) = sv.time;
2721                                 prog->globals.fp[OFS_PARM0] = sv_realtime - sv.pausedstart;
2722                                 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
2723                         }
2724
2725                         // send an heartbeat if enough time has passed since the last one
2726                         NetConn_Heartbeat(0);
2727
2728                 }
2729
2730                 // we're back to safe code now
2731                 SV_UnlockThreadMutex();
2732
2733                 // if there is some time remaining from this frame, reset the timers
2734                 if (sv_timer >= 0)
2735                 {
2736                         svs.perf_acc_lost += sv_timer;
2737                         sv_timer = 0;
2738                 }
2739         }
2740         return 0;
2741 }
2742
2743 void SV_StartThread(void)
2744 {
2745         if (!sv_threaded.integer || !Thread_HasThreads())
2746                 return;
2747         svs.threaded = true;
2748         svs.threadstop = false;
2749         svs.threadmutex = Thread_CreateMutex();
2750         svs.thread = Thread_CreateThread(SV_ThreadFunc, NULL);
2751 }
2752
2753 void SV_StopThread(void)
2754 {
2755         if (!svs.threaded)
2756                 return;
2757         svs.threadstop = true;
2758         Thread_WaitThread(svs.thread, 0);
2759         Thread_DestroyMutex(svs.threadmutex);
2760         svs.threaded = false;
2761 }