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