]> git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - sv_main.c
Convert \ to / when loading texture from Q3 shader
[xonotic/darkplaces.git] / sv_main.c
index 05e6db009279b65a42c57ece9cf5f1413cdf201b..f89c307314260af5083f2abd27a6bc5104d16c1d 100644 (file)
--- a/sv_main.c
+++ b/sv_main.c
@@ -23,179 +23,189 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "sv_demo.h"
 #include "libcurl.h"
 #include "csprogs.h"
+#include "thread.h"
 
-static void SV_SaveEntFile_f(void);
-static void SV_StartDownload_f(void);
-static void SV_Download_f(void);
+static void SV_SaveEntFile_f(cmd_state_t *cmd);
+static void SV_StartDownload_f(cmd_state_t *cmd);
+static void SV_Download_f(cmd_state_t *cmd);
 static void SV_VM_Setup(void);
 extern cvar_t net_connecttimeout;
 
-void VM_CustomStats_Clear (void);
-void VM_SV_UpdateCustomStats (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats);
-
-cvar_t sv_worldmessage = {CVAR_READONLY, "sv_worldmessage", "", "title of current level"};
-cvar_t sv_worldname = {CVAR_READONLY, "sv_worldname", "", "name of current worldmodel"};
-cvar_t sv_worldnamenoextension = {CVAR_READONLY, "sv_worldnamenoextension", "", "name of current worldmodel without extension"};
-cvar_t sv_worldbasename = {CVAR_READONLY, "sv_worldbasename", "", "name of current worldmodel without maps/ prefix or extension"};
-
-cvar_t coop = {0, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
-cvar_t deathmatch = {0, "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)"};
-cvar_t fraglimit = {CVAR_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
-cvar_t gamecfg = {0, "gamecfg", "0", "unused cvar in quake, can be used by mods"};
-cvar_t noexit = {CVAR_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
-cvar_t nomonsters = {0, "nomonsters", "0", "unused cvar in quake, can be used by mods"};
-cvar_t pausable = {0, "pausable","1", "allow players to pause or not"};
-cvar_t pr_checkextension = {CVAR_READONLY, "pr_checkextension", "1", "indicates to QuakeC that the standard quakec extensions system is available (if 0, quakec should not attempt to use extensions)"};
-cvar_t samelevel = {CVAR_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
-cvar_t skill = {0, "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)"};
-cvar_t slowmo = {0, "slowmo", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
-
-cvar_t sv_accelerate = {0, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
-cvar_t sv_aim = {CVAR_SAVE, "sv_aim", "2", "maximum cosine angle for quake's vertical autoaim, a value above 1 completely disables the autoaim, quake used 0.93"};
-cvar_t sv_airaccel_qw = {0, "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"};
-cvar_t sv_airaccel_qw_stretchfactor = {0, "sv_airaccel_qw_stretchfactor", "0", "when set, the maximum acceleration increase the player may get compared to forward-acceleration when strafejumping"};
-cvar_t sv_airaccel_sideways_friction = {0, "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"};
-cvar_t sv_airaccelerate = {0, "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"};
-cvar_t sv_airstopaccelerate = {0, "sv_airstopaccelerate", "0", "when set, replacement for sv_airaccelerate when moving backwards"};
-cvar_t sv_airspeedlimit_nonqw = {0, "sv_airspeedlimit_nonqw", "0", "when set, this is a soft speed limit while in air when using airaccel_qw not equal to 1"};
-cvar_t sv_airstrafeaccelerate = {0, "sv_airstrafeaccelerate", "0", "when set, replacement for sv_airaccelerate when just strafing"};
-cvar_t sv_maxairstrafespeed = {0, "sv_maxairstrafespeed", "0", "when set, replacement for sv_maxairspeed when just strafing"};
-cvar_t sv_airstrafeaccel_qw = {0, "sv_airstrafeaccel_qw", "0", "when set, replacement for sv_airaccel_qw when just strafing"};
-cvar_t sv_aircontrol = {0, "sv_aircontrol", "0", "CPMA-style air control"};
-cvar_t sv_aircontrol_power = {0, "sv_aircontrol_power", "2", "CPMA-style air control exponent"};
-cvar_t sv_aircontrol_penalty = {0, "sv_aircontrol_penalty", "0", "deceleration while using CPMA-style air control"};
-cvar_t sv_allowdownloads = {0, "sv_allowdownloads", "1", "whether to allow clients to download files from the server (does not affect http downloads)"};
-cvar_t sv_allowdownloads_archive = {0, "sv_allowdownloads_archive", "0", "whether to allow downloads of archives (pak/pk3)"};
-cvar_t sv_allowdownloads_config = {0, "sv_allowdownloads_config", "0", "whether to allow downloads of config files (cfg)"};
-cvar_t sv_allowdownloads_dlcache = {0, "sv_allowdownloads_dlcache", "0", "whether to allow downloads of dlcache files (dlcache/)"};
-cvar_t sv_allowdownloads_inarchive = {0, "sv_allowdownloads_inarchive", "0", "whether to allow downloads from archives (pak/pk3)"};
-cvar_t sv_areagrid_mingridsize = {CVAR_NOTIFY, "sv_areagrid_mingridsize", "128", "minimum areagrid cell size, smaller values work better for lots of small objects, higher values for large objects"};
-cvar_t sv_checkforpacketsduringsleep = {0, "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"};
-cvar_t sv_clmovement_enable = {0, "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"};
-cvar_t sv_clmovement_minping = {0, "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)"};
-cvar_t sv_clmovement_minping_disabletime = {0, "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)"};
-cvar_t sv_clmovement_inputtimeout = {0, "sv_clmovement_inputtimeout", "0.2", "when a client does not send input for this many seconds, force them to move anyway (unlike QuakeWorld)"};
-cvar_t sv_cullentities_nevercullbmodels = {0, "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!)"};
-cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "1", "fast but loose culling of hidden entities"};
-cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0", "displays stats on network entities culled by various methods for each client"};
-cvar_t sv_cullentities_trace = {0, "sv_cullentities_trace", "0", "somewhat slow but very tight culling of hidden entities, minimizes network traffic and makes wallhack cheats useless"};
-cvar_t sv_cullentities_trace_delay = {0, "sv_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
-cvar_t sv_cullentities_trace_delay_players = {0, "sv_cullentities_trace_delay_players", "0.2", "number of seconds until the entity gets actually culled if it is a player entity"};
-cvar_t sv_cullentities_trace_enlarge = {0, "sv_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
-cvar_t sv_cullentities_trace_prediction = {0, "sv_cullentities_trace_prediction", "1", "also trace from the predicted player position"};
-cvar_t sv_cullentities_trace_prediction_time = {0, "sv_cullentities_trace_prediction_time", "0.2", "how many seconds of prediction to use"};
-cvar_t sv_cullentities_trace_entityocclusion = {0, "sv_cullentities_trace_entityocclusion", "0", "also check if doors and other bsp models are in the way"};
-cvar_t sv_cullentities_trace_samples = {0, "sv_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
-cvar_t sv_cullentities_trace_samples_extra = {0, "sv_cullentities_trace_samples_extra", "2", "number of samples to test for entity culling when the entity affects its surroundings by e.g. dlight"};
-cvar_t sv_cullentities_trace_samples_players = {0, "sv_cullentities_trace_samples_players", "8", "number of samples to test for entity culling when the entity is a player entity"};
-cvar_t sv_debugmove = {CVAR_NOTIFY, "sv_debugmove", "0", "disables collision detection optimizations for debugging purposes"};
-cvar_t sv_echobprint = {CVAR_SAVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
-cvar_t sv_edgefriction = {0, "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)"};
-cvar_t sv_entpatch = {0, "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)"};
-cvar_t sv_fixedframeratesingleplayer = {0, "sv_fixedframeratesingleplayer", "1", "allows you to use server-style timing system in singleplayer (don't run faster than sys_ticrate)"};
-cvar_t sv_freezenonclients = {CVAR_NOTIFY, "sv_freezenonclients", "0", "freezes time, except for players, allowing you to walk around and take screenshots of explosions"};
-cvar_t sv_friction = {CVAR_NOTIFY, "sv_friction","4", "how fast you slow down"};
-cvar_t sv_gameplayfix_blowupfallenzombies = {0, "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"};
-cvar_t sv_gameplayfix_consistentplayerprethink = {0, "sv_gameplayfix_consistentplayerprethink", "0", "improves fairness in multiplayer by running all PlayerPreThink functions (which fire weapons) before performing physics, then running all PlayerPostThink functions"};
-cvar_t sv_gameplayfix_delayprojectiles = {0, "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"};
-cvar_t sv_gameplayfix_droptofloorstartsolid = {0, "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)"};
-cvar_t sv_gameplayfix_droptofloorstartsolid_nudgetocorrect = {0, "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect", "1", "tries to nudge stuck items and monsters out of walls before droptofloor is performed"};
-cvar_t sv_gameplayfix_easierwaterjump = {0, "sv_gameplayfix_easierwaterjump", "1", "changes water jumping to make it easier to get out of water (exactly like in QuakeWorld)"};
-cvar_t sv_gameplayfix_findradiusdistancetobox = {0, "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"};
-cvar_t sv_gameplayfix_gravityunaffectedbyticrate = {0, "sv_gameplayfix_gravityunaffectedbyticrate", "0", "fix some ticrate issues in physics."};
-cvar_t sv_gameplayfix_grenadebouncedownslopes = {0, "sv_gameplayfix_grenadebouncedownslopes", "1", "prevents MOVETYPE_BOUNCE (grenades) from getting stuck when fired down a downward sloping surface"};
-cvar_t sv_gameplayfix_multiplethinksperframe = {0, "sv_gameplayfix_multiplethinksperframe", "1", "allows entities to think more often than the server framerate, primarily useful for very high fire rate weapons"};
-cvar_t sv_gameplayfix_noairborncorpse = {0, "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"};
-cvar_t sv_gameplayfix_noairborncorpse_allowsuspendeditems = {0, "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)"};
-cvar_t sv_gameplayfix_nudgeoutofsolid = {0, "sv_gameplayfix_nudgeoutofsolid", "1", "attempts to fix physics errors (where an object ended up in solid for some reason)"};
-cvar_t sv_gameplayfix_nudgeoutofsolid_bias = {0, "sv_gameplayfix_nudgeoutofsolid_bias", "0", "over-correction on nudgeoutofsolid logic, to prevent constant contact"};
-cvar_t sv_gameplayfix_q2airaccelerate = {0, "sv_gameplayfix_q2airaccelerate", "0", "Quake2-style air acceleration"};
-cvar_t sv_gameplayfix_nogravityonground = {0, "sv_gameplayfix_nogravityonground", "0", "turn off gravity when on ground (to get rid of sliding)"};
-cvar_t sv_gameplayfix_setmodelrealbox = {0, "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"};
-cvar_t sv_gameplayfix_slidemoveprojectiles = {0, "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"};
-cvar_t sv_gameplayfix_stepdown = {0, "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)"};
-cvar_t sv_gameplayfix_stepwhilejumping = {0, "sv_gameplayfix_stepwhilejumping", "1", "applies step-up onto a ledge even while airborn, useful if you would otherwise just-miss the floor when running across small areas with gaps (for instance running across the moving platforms in dm2, or jumping to the megahealth and red armor in dm2 rather than using the bridge)"};
-cvar_t sv_gameplayfix_stepmultipletimes = {0, "sv_gameplayfix_stepmultipletimes", "0", "applies step-up onto a ledge more than once in a single frame, when running quickly up stairs"};
-cvar_t sv_gameplayfix_nostepmoveonsteepslopes = {0, "sv_gameplayfix_nostepmoveonsteepslopes", "0", "grude fix which prevents MOVETYPE_STEP (not swimming or flying) to move on slopes whose angle is bigger than 45 degree"};
-cvar_t sv_gameplayfix_swiminbmodels = {0, "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"};
-cvar_t sv_gameplayfix_upwardvelocityclearsongroundflag = {0, "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"};
-cvar_t sv_gameplayfix_downtracesupportsongroundflag = {0, "sv_gameplayfix_downtracesupportsongroundflag", "1", "prevents very short moves from clearing onground (which may make the player stick to the floor at high netfps)"};
-cvar_t sv_gravity = {CVAR_NOTIFY, "sv_gravity","800", "how fast you fall (512 = roughly earth gravity)"};
-cvar_t sv_idealpitchscale = {0, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
-cvar_t sv_jumpstep = {CVAR_NOTIFY, "sv_jumpstep", "0", "whether you can step up while jumping (sv_gameplayfix_stepwhilejumping must also be 1)"};
-cvar_t sv_jumpvelocity = {0, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
-cvar_t sv_maxairspeed = {0, "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)"};
-cvar_t sv_maxrate = {CVAR_SAVE | CVAR_NOTIFY, "sv_maxrate", "1000000", "upper limit on client rate cvar, should reflect your network connection quality"};
-cvar_t sv_maxspeed = {CVAR_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
-cvar_t sv_maxvelocity = {CVAR_NOTIFY, "sv_maxvelocity","2000", "universal speed limit on all entities"};
-cvar_t sv_nostep = {CVAR_NOTIFY, "sv_nostep","0", "prevents MOVETYPE_STEP entities (monsters) from moving"};
-cvar_t sv_playerphysicsqc = {CVAR_NOTIFY, "sv_playerphysicsqc", "1", "enables QuakeC function to override player physics"};
-cvar_t sv_progs = {0, "sv_progs", "progs.dat", "selects which quakec progs.dat file to run" };
-cvar_t sv_protocolname = {0, "sv_protocolname", "DP7", "selects network protocol to host for (values include QUAKE, QUAKEDP, NEHAHRAMOVIE, DP1 and up)"};
-cvar_t sv_random_seed = {0, "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"};
-cvar_t sv_ratelimitlocalplayer = {0, "sv_ratelimitlocalplayer", "0", "whether to apply rate limiting to the local player in a listen server (only useful for testing)"};
-cvar_t sv_sound_land = {0, "sv_sound_land", "demon/dland2.wav", "sound to play when MOVETYPE_STEP entity hits the ground at high speed (empty cvar disables the sound)"};
-cvar_t sv_sound_watersplash = {0, "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)"};
-cvar_t sv_stepheight = {CVAR_NOTIFY, "sv_stepheight", "18", "how high you can step up (TW_SV_STEPCONTROL extension)"};
-cvar_t sv_stopspeed = {CVAR_NOTIFY, "sv_stopspeed","100", "how fast you come to a complete stop"};
-cvar_t sv_wallfriction = {CVAR_NOTIFY, "sv_wallfriction", "1", "how much you slow down when sliding along a wall"};
-cvar_t sv_wateraccelerate = {0, "sv_wateraccelerate", "-1", "rate at which a player accelerates to sv_maxspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
-cvar_t sv_waterfriction = {CVAR_NOTIFY, "sv_waterfriction","-1", "how fast you slow down, if less than 0 the sv_friction variable is used instead"};
-cvar_t sv_warsowbunny_airforwardaccel = {0, "sv_warsowbunny_airforwardaccel", "1.00001", "how fast you accelerate until you reach sv_maxspeed"};
-cvar_t sv_warsowbunny_accel = {0, "sv_warsowbunny_accel", "0.1585", "how fast you accelerate until after reaching sv_maxspeed (it gets harder as you near sv_warsowbunny_topspeed)"};
-cvar_t sv_warsowbunny_topspeed = {0, "sv_warsowbunny_topspeed", "925", "soft speed limit (can get faster with rjs and on ramps)"};
-cvar_t sv_warsowbunny_turnaccel = {0, "sv_warsowbunny_turnaccel", "0", "max sharpness of turns (also master switch for the sv_warsowbunny_* mode; set this to 9 to enable)"};
-cvar_t sv_warsowbunny_backtosideratio = {0, "sv_warsowbunny_backtosideratio", "0.8", "lower values make it easier to change direction without losing speed; the drawback is \"understeering\" in sharp turns"};
-cvar_t sv_onlycsqcnetworking = {0, "sv_onlycsqcnetworking", "0", "disables legacy entity networking code for higher performance (except on clients, which can still be legacy)"};
-cvar_t sys_ticrate = {CVAR_SAVE, "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"};
-cvar_t teamplay = {CVAR_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"};
-cvar_t timelimit = {CVAR_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
-
-cvar_t saved1 = {CVAR_SAVE, "saved1", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
-cvar_t saved2 = {CVAR_SAVE, "saved2", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
-cvar_t saved3 = {CVAR_SAVE, "saved3", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
-cvar_t saved4 = {CVAR_SAVE, "saved4", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
-cvar_t savedgamecfg = {CVAR_SAVE, "savedgamecfg", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
-cvar_t scratch1 = {0, "scratch1", "0", "unused cvar in quake, can be used by mods"};
-cvar_t scratch2 = {0,"scratch2", "0", "unused cvar in quake, can be used by mods"};
-cvar_t scratch3 = {0, "scratch3", "0", "unused cvar in quake, can be used by mods"};
-cvar_t scratch4 = {0, "scratch4", "0", "unused cvar in quake, can be used by mods"};
-cvar_t temp1 = {0, "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)"};
-
-cvar_t nehx00 = {0, "nehx00", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx01 = {0, "nehx01", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx02 = {0, "nehx02", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx03 = {0, "nehx03", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx04 = {0, "nehx04", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx05 = {0, "nehx05", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx06 = {0, "nehx06", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx07 = {0, "nehx07", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx08 = {0, "nehx08", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx09 = {0, "nehx09", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx10 = {0, "nehx10", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx11 = {0, "nehx11", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx12 = {0, "nehx12", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx13 = {0, "nehx13", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx14 = {0, "nehx14", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx15 = {0, "nehx15", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx16 = {0, "nehx16", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx17 = {0, "nehx17", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx18 = {0, "nehx18", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t nehx19 = {0, "nehx19", "0", "nehahra data storage cvar (used in singleplayer)"};
-cvar_t cutscene = {0, "cutscene", "1", "enables cutscenes in nehahra, can be used by other mods"};
-
-cvar_t sv_autodemo_perclient = {CVAR_SAVE, "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)"};
-cvar_t sv_autodemo_perclient_nameformat = {CVAR_SAVE, "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)" };
-cvar_t sv_autodemo_perclient_discardable = {CVAR_SAVE, "sv_autodemo_perclient_discardable", "0", "Allow game code to decide whether a demo should be kept or discarded."};
-
-cvar_t halflifebsp = {0, "halflifebsp", "0", "indicates the current map is hlbsp format (useful to know because of different bounding box sizes)"};
+cvar_t sv_worldmessage = {CVAR_SERVER | CVAR_READONLY, "sv_worldmessage", "", "title of current level"};
+cvar_t sv_worldname = {CVAR_SERVER | CVAR_READONLY, "sv_worldname", "", "name of current worldmodel"};
+cvar_t sv_worldnamenoextension = {CVAR_SERVER | CVAR_READONLY, "sv_worldnamenoextension", "", "name of current worldmodel without extension"};
+cvar_t sv_worldbasename = {CVAR_SERVER | CVAR_READONLY, "sv_worldbasename", "", "name of current worldmodel without maps/ prefix or extension"};
+
+cvar_t sv_disablenotify = {CVAR_SERVER, "sv_disablenotify", "0", "suppress broadcast prints when certain cvars are changed (CVAR_NOTIFY flag in engine code)"};
+cvar_t coop = {CVAR_SERVER, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
+cvar_t deathmatch = {CVAR_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)"};
+cvar_t fraglimit = {CVAR_SERVER | CVAR_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
+cvar_t gamecfg = {CVAR_SERVER, "gamecfg", "0", "unused cvar in quake, can be used by mods"};
+cvar_t noexit = {CVAR_SERVER | CVAR_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
+cvar_t nomonsters = {CVAR_SERVER, "nomonsters", "0", "unused cvar in quake, can be used by mods"};
+cvar_t pausable = {CVAR_SERVER, "pausable","1", "allow players to pause or not (otherwise, only the server admin can)"};
+cvar_t pr_checkextension = {CVAR_SERVER | CVAR_READONLY, "pr_checkextension", "1", "indicates to QuakeC that the standard quakec extensions system is available (if 0, quakec should not attempt to use extensions)"};
+cvar_t samelevel = {CVAR_SERVER | CVAR_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
+cvar_t skill = {CVAR_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)"};
+cvar_t host_timescale = {CVAR_CLIENT | CVAR_SERVER, "host_timescale", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
+
+cvar_t sv_accelerate = {CVAR_SERVER, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
+cvar_t sv_aim = {CVAR_SERVER | CVAR_SAVE, "sv_aim", "2", "maximum cosine angle for quake's vertical autoaim, a value above 1 completely disables the autoaim, quake used 0.93"};
+cvar_t sv_airaccel_qw = {CVAR_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"};
+cvar_t sv_airaccel_qw_stretchfactor = {CVAR_SERVER, "sv_airaccel_qw_stretchfactor", "0", "when set, the maximum acceleration increase the player may get compared to forward-acceleration when strafejumping"};
+cvar_t sv_airaccel_sideways_friction = {CVAR_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"};
+cvar_t sv_airaccelerate = {CVAR_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"};
+cvar_t sv_airstopaccelerate = {CVAR_SERVER, "sv_airstopaccelerate", "0", "when set, replacement for sv_airaccelerate when moving backwards"};
+cvar_t sv_airspeedlimit_nonqw = {CVAR_SERVER, "sv_airspeedlimit_nonqw", "0", "when set, this is a soft speed limit while in air when using airaccel_qw not equal to 1"};
+cvar_t sv_airstrafeaccelerate = {CVAR_SERVER, "sv_airstrafeaccelerate", "0", "when set, replacement for sv_airaccelerate when just strafing"};
+cvar_t sv_maxairstrafespeed = {CVAR_SERVER, "sv_maxairstrafespeed", "0", "when set, replacement for sv_maxairspeed when just strafing"};
+cvar_t sv_airstrafeaccel_qw = {CVAR_SERVER, "sv_airstrafeaccel_qw", "0", "when set, replacement for sv_airaccel_qw when just strafing"};
+cvar_t sv_aircontrol = {CVAR_SERVER, "sv_aircontrol", "0", "CPMA-style air control"};
+cvar_t sv_aircontrol_power = {CVAR_SERVER, "sv_aircontrol_power", "2", "CPMA-style air control exponent"};
+cvar_t sv_aircontrol_penalty = {CVAR_SERVER, "sv_aircontrol_penalty", "0", "deceleration while using CPMA-style air control"};
+cvar_t sv_allowdownloads = {CVAR_SERVER, "sv_allowdownloads", "1", "whether to allow clients to download files from the server (does not affect http downloads)"};
+cvar_t sv_allowdownloads_archive = {CVAR_SERVER, "sv_allowdownloads_archive", "0", "whether to allow downloads of archives (pak/pk3)"};
+cvar_t sv_allowdownloads_config = {CVAR_SERVER, "sv_allowdownloads_config", "0", "whether to allow downloads of config files (cfg)"};
+cvar_t sv_allowdownloads_dlcache = {CVAR_SERVER, "sv_allowdownloads_dlcache", "0", "whether to allow downloads of dlcache files (dlcache/)"};
+cvar_t sv_allowdownloads_inarchive = {CVAR_SERVER, "sv_allowdownloads_inarchive", "0", "whether to allow downloads from archives (pak/pk3)"};
+cvar_t sv_areagrid_mingridsize = {CVAR_SERVER | CVAR_NOTIFY, "sv_areagrid_mingridsize", "128", "minimum areagrid cell size, smaller values work better for lots of small objects, higher values for large objects"};
+cvar_t sv_checkforpacketsduringsleep = {CVAR_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"};
+cvar_t sv_clmovement_enable = {CVAR_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"};
+cvar_t sv_clmovement_minping = {CVAR_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)"};
+cvar_t sv_clmovement_minping_disabletime = {CVAR_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)"};
+cvar_t sv_clmovement_inputtimeout = {CVAR_SERVER, "sv_clmovement_inputtimeout", "0.2", "when a client does not send input for this many seconds, force them to move anyway (unlike QuakeWorld)"};
+cvar_t sv_cullentities_nevercullbmodels = {CVAR_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!)"};
+cvar_t sv_cullentities_pvs = {CVAR_SERVER, "sv_cullentities_pvs", "1", "fast but loose culling of hidden entities"};
+cvar_t sv_cullentities_stats = {CVAR_SERVER, "sv_cullentities_stats", "0", "displays stats on network entities culled by various methods for each client"};
+cvar_t sv_cullentities_trace = {CVAR_SERVER, "sv_cullentities_trace", "0", "somewhat slow but very tight culling of hidden entities, minimizes network traffic and makes wallhack cheats useless"};
+cvar_t sv_cullentities_trace_delay = {CVAR_SERVER, "sv_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
+cvar_t sv_cullentities_trace_delay_players = {CVAR_SERVER, "sv_cullentities_trace_delay_players", "0.2", "number of seconds until the entity gets actually culled if it is a player entity"};
+cvar_t sv_cullentities_trace_enlarge = {CVAR_SERVER, "sv_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
+cvar_t sv_cullentities_trace_expand = {CVAR_SERVER, "sv_cullentities_trace_expand", "0", "box is expanded by this many units for entity culling"};
+cvar_t sv_cullentities_trace_eyejitter = {CVAR_SERVER, "sv_cullentities_trace_eyejitter", "16", "jitter the eye by this much for each trace"};
+cvar_t sv_cullentities_trace_prediction = {CVAR_SERVER, "sv_cullentities_trace_prediction", "1", "also trace from the predicted player position"};
+cvar_t sv_cullentities_trace_prediction_time = {CVAR_SERVER, "sv_cullentities_trace_prediction_time", "0.2", "how many seconds of prediction to use"};
+cvar_t sv_cullentities_trace_entityocclusion = {CVAR_SERVER, "sv_cullentities_trace_entityocclusion", "0", "also check if doors and other bsp models are in the way"};
+cvar_t sv_cullentities_trace_samples = {CVAR_SERVER, "sv_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
+cvar_t sv_cullentities_trace_samples_extra = {CVAR_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"};
+cvar_t sv_cullentities_trace_samples_players = {CVAR_SERVER, "sv_cullentities_trace_samples_players", "8", "number of samples to test for entity culling when the entity is a player entity"};
+cvar_t sv_debugmove = {CVAR_SERVER | CVAR_NOTIFY, "sv_debugmove", "0", "disables collision detection optimizations for debugging purposes"};
+cvar_t sv_echobprint = {CVAR_SERVER | CVAR_SAVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
+cvar_t sv_edgefriction = {CVAR_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)"};
+cvar_t sv_entpatch = {CVAR_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)"};
+cvar_t sv_fixedframeratesingleplayer = {CVAR_SERVER, "sv_fixedframeratesingleplayer", "1", "allows you to use server-style timing system in singleplayer (don't run faster than sys_ticrate)"};
+cvar_t sv_freezenonclients = {CVAR_SERVER | CVAR_NOTIFY, "sv_freezenonclients", "0", "freezes time, except for players, allowing you to walk around and take screenshots of explosions"};
+cvar_t sv_friction = {CVAR_SERVER | CVAR_NOTIFY, "sv_friction","4", "how fast you slow down"};
+cvar_t sv_gameplayfix_blowupfallenzombies = {CVAR_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"};
+cvar_t sv_gameplayfix_consistentplayerprethink = {CVAR_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"};
+cvar_t sv_gameplayfix_delayprojectiles = {CVAR_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"};
+cvar_t sv_gameplayfix_droptofloorstartsolid = {CVAR_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)"};
+cvar_t sv_gameplayfix_droptofloorstartsolid_nudgetocorrect = {CVAR_SERVER, "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect", "1", "tries to nudge stuck items and monsters out of walls before droptofloor is performed"};
+cvar_t sv_gameplayfix_easierwaterjump = {CVAR_SERVER, "sv_gameplayfix_easierwaterjump", "1", "changes water jumping to make it easier to get out of water (exactly like in QuakeWorld)"};
+cvar_t sv_gameplayfix_findradiusdistancetobox = {CVAR_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"};
+cvar_t sv_gameplayfix_gravityunaffectedbyticrate = {CVAR_SERVER, "sv_gameplayfix_gravityunaffectedbyticrate", "0", "fix some ticrate issues in physics."};
+cvar_t sv_gameplayfix_grenadebouncedownslopes = {CVAR_SERVER, "sv_gameplayfix_grenadebouncedownslopes", "1", "prevents MOVETYPE_BOUNCE (grenades) from getting stuck when fired down a downward sloping surface"};
+cvar_t sv_gameplayfix_multiplethinksperframe = {CVAR_SERVER, "sv_gameplayfix_multiplethinksperframe", "1", "allows entities to think more often than the server framerate, primarily useful for very high fire rate weapons"};
+cvar_t sv_gameplayfix_noairborncorpse = {CVAR_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"};
+cvar_t sv_gameplayfix_noairborncorpse_allowsuspendeditems = {CVAR_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)"};
+cvar_t sv_gameplayfix_nudgeoutofsolid = {CVAR_SERVER, "sv_gameplayfix_nudgeoutofsolid", "0", "attempts to fix physics errors (where an object ended up in solid for some reason)"};
+cvar_t sv_gameplayfix_nudgeoutofsolid_separation = {CVAR_SERVER, "sv_gameplayfix_nudgeoutofsolid_separation", "0.03125", "keep objects this distance apart to prevent collision issues on seams"};
+cvar_t sv_gameplayfix_q2airaccelerate = {CVAR_SERVER, "sv_gameplayfix_q2airaccelerate", "0", "Quake2-style air acceleration"};
+cvar_t sv_gameplayfix_nogravityonground = {CVAR_SERVER, "sv_gameplayfix_nogravityonground", "0", "turn off gravity when on ground (to get rid of sliding)"};
+cvar_t sv_gameplayfix_setmodelrealbox = {CVAR_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"};
+cvar_t sv_gameplayfix_slidemoveprojectiles = {CVAR_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"};
+cvar_t sv_gameplayfix_stepdown = {CVAR_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)"};
+cvar_t sv_gameplayfix_stepmultipletimes = {CVAR_SERVER, "sv_gameplayfix_stepmultipletimes", "0", "applies step-up onto a ledge more than once in a single frame, when running quickly up stairs"};
+cvar_t sv_gameplayfix_nostepmoveonsteepslopes = {CVAR_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"};
+cvar_t sv_gameplayfix_swiminbmodels = {CVAR_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"};
+cvar_t sv_gameplayfix_upwardvelocityclearsongroundflag = {CVAR_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"};
+cvar_t sv_gameplayfix_downtracesupportsongroundflag = {CVAR_SERVER, "sv_gameplayfix_downtracesupportsongroundflag", "1", "prevents very short moves from clearing onground (which may make the player stick to the floor at high netfps)"};
+cvar_t sv_gameplayfix_q1bsptracelinereportstexture = {CVAR_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"};
+cvar_t sv_gameplayfix_unstickplayers = {CVAR_SERVER, "sv_gameplayfix_unstickplayers", "1", "big hack to try and fix the rare case of MOVETYPE_WALK entities getting stuck in the world clipping hull."};
+cvar_t sv_gameplayfix_unstickentities = {CVAR_SERVER, "sv_gameplayfix_unstickentities", "1", "hack to check if entities are crossing world collision hull and try to move them to the right position"};
+cvar_t sv_gameplayfix_fixedcheckwatertransition = {CVAR_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)"};
+cvar_t sv_gameplayfix_customstats = {CVAR_SERVER, "sv_gameplayfix_customstats", "0", "Disable stats higher than 220, for use by certain games such as Xonotic"};
+cvar_t sv_gravity = {CVAR_SERVER | CVAR_NOTIFY, "sv_gravity","800", "how fast you fall (512 = roughly earth gravity)"};
+cvar_t sv_init_frame_count = {CVAR_SERVER, "sv_init_frame_count", "2", "number of frames to run to allow everything to settle before letting clients connect"};
+cvar_t sv_idealpitchscale = {CVAR_SERVER, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
+cvar_t sv_jumpstep = {CVAR_SERVER | CVAR_NOTIFY, "sv_jumpstep", "0", "whether you can step up while jumping"};
+cvar_t sv_jumpvelocity = {CVAR_SERVER, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
+cvar_t sv_maxairspeed = {CVAR_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)"};
+cvar_t sv_maxrate = {CVAR_SERVER | CVAR_SAVE | CVAR_NOTIFY, "sv_maxrate", "1000000", "upper limit on client rate cvar, should reflect your network connection quality"};
+cvar_t sv_maxspeed = {CVAR_SERVER | CVAR_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
+cvar_t sv_maxvelocity = {CVAR_SERVER | CVAR_NOTIFY, "sv_maxvelocity","2000", "universal speed limit on all entities"};
+cvar_t sv_nostep = {CVAR_SERVER | CVAR_NOTIFY, "sv_nostep","0", "prevents MOVETYPE_STEP entities (monsters) from moving"};
+cvar_t sv_playerphysicsqc = {CVAR_SERVER | CVAR_NOTIFY, "sv_playerphysicsqc", "1", "enables QuakeC function to override player physics"};
+cvar_t sv_progs = {CVAR_SERVER, "sv_progs", "progs.dat", "selects which quakec progs.dat file to run" };
+cvar_t sv_protocolname = {CVAR_SERVER, "sv_protocolname", "DP7", "selects network protocol to host for (values include QUAKE, QUAKEDP, NEHAHRAMOVIE, DP1 and up)"};
+cvar_t sv_random_seed = {CVAR_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"};
+cvar_t sv_ratelimitlocalplayer = {CVAR_SERVER, "sv_ratelimitlocalplayer", "0", "whether to apply rate limiting to the local player in a listen server (only useful for testing)"};
+cvar_t sv_sound_land = {CVAR_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)"};
+cvar_t sv_sound_watersplash = {CVAR_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)"};
+cvar_t sv_stepheight = {CVAR_SERVER | CVAR_NOTIFY, "sv_stepheight", "18", "how high you can step up (TW_SV_STEPCONTROL extension)"};
+cvar_t sv_stopspeed = {CVAR_SERVER | CVAR_NOTIFY, "sv_stopspeed","100", "how fast you come to a complete stop"};
+cvar_t sv_wallfriction = {CVAR_SERVER | CVAR_NOTIFY, "sv_wallfriction", "1", "how much you slow down when sliding along a wall"};
+cvar_t sv_wateraccelerate = {CVAR_SERVER, "sv_wateraccelerate", "-1", "rate at which a player accelerates to sv_maxspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
+cvar_t sv_waterfriction = {CVAR_SERVER | CVAR_NOTIFY, "sv_waterfriction","-1", "how fast you slow down, if less than 0 the sv_friction variable is used instead"};
+cvar_t sv_warsowbunny_airforwardaccel = {CVAR_SERVER, "sv_warsowbunny_airforwardaccel", "1.00001", "how fast you accelerate until you reach sv_maxspeed"};
+cvar_t sv_warsowbunny_accel = {CVAR_SERVER, "sv_warsowbunny_accel", "0.1585", "how fast you accelerate until after reaching sv_maxspeed (it gets harder as you near sv_warsowbunny_topspeed)"};
+cvar_t sv_warsowbunny_topspeed = {CVAR_SERVER, "sv_warsowbunny_topspeed", "925", "soft speed limit (can get faster with rjs and on ramps)"};
+cvar_t sv_warsowbunny_turnaccel = {CVAR_SERVER, "sv_warsowbunny_turnaccel", "0", "max sharpness of turns (also master switch for the sv_warsowbunny_* mode; set this to 9 to enable)"};
+cvar_t sv_warsowbunny_backtosideratio = {CVAR_SERVER, "sv_warsowbunny_backtosideratio", "0.8", "lower values make it easier to change direction without losing speed; the drawback is \"understeering\" in sharp turns"};
+cvar_t sv_onlycsqcnetworking = {CVAR_SERVER, "sv_onlycsqcnetworking", "0", "disables legacy entity networking code for higher performance (except on clients, which can still be legacy)"};
+cvar_t sv_areadebug = {CVAR_SERVER, "sv_areadebug", "0", "disables physics culling for debugging purposes (only for development)"};
+cvar_t sys_ticrate = {CVAR_SERVER | CVAR_SAVE, "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"};
+cvar_t teamplay = {CVAR_SERVER | CVAR_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"};
+cvar_t timelimit = {CVAR_SERVER | CVAR_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
+cvar_t sv_threaded = {CVAR_SERVER, "sv_threaded", "0", "enables a separate thread for server code, improving performance, especially when hosting a game while playing, EXPERIMENTAL, may be crashy"};
+
+cvar_t saved1 = {CVAR_SERVER | CVAR_SAVE, "saved1", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
+cvar_t saved2 = {CVAR_SERVER | CVAR_SAVE, "saved2", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
+cvar_t saved3 = {CVAR_SERVER | CVAR_SAVE, "saved3", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
+cvar_t saved4 = {CVAR_SERVER | CVAR_SAVE, "saved4", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
+cvar_t savedgamecfg = {CVAR_SERVER | CVAR_SAVE, "savedgamecfg", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
+cvar_t scratch1 = {CVAR_SERVER, "scratch1", "0", "unused cvar in quake, can be used by mods"};
+cvar_t scratch2 = {CVAR_SERVER,"scratch2", "0", "unused cvar in quake, can be used by mods"};
+cvar_t scratch3 = {CVAR_SERVER, "scratch3", "0", "unused cvar in quake, can be used by mods"};
+cvar_t scratch4 = {CVAR_SERVER, "scratch4", "0", "unused cvar in quake, can be used by mods"};
+cvar_t temp1 = {CVAR_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)"};
+
+cvar_t nehx00 = {CVAR_SERVER, "nehx00", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx01 = {CVAR_SERVER, "nehx01", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx02 = {CVAR_SERVER, "nehx02", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx03 = {CVAR_SERVER, "nehx03", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx04 = {CVAR_SERVER, "nehx04", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx05 = {CVAR_SERVER, "nehx05", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx06 = {CVAR_SERVER, "nehx06", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx07 = {CVAR_SERVER, "nehx07", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx08 = {CVAR_SERVER, "nehx08", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx09 = {CVAR_SERVER, "nehx09", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx10 = {CVAR_SERVER, "nehx10", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx11 = {CVAR_SERVER, "nehx11", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx12 = {CVAR_SERVER, "nehx12", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx13 = {CVAR_SERVER, "nehx13", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx14 = {CVAR_SERVER, "nehx14", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx15 = {CVAR_SERVER, "nehx15", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx16 = {CVAR_SERVER, "nehx16", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx17 = {CVAR_SERVER, "nehx17", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx18 = {CVAR_SERVER, "nehx18", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t nehx19 = {CVAR_SERVER, "nehx19", "0", "nehahra data storage cvar (used in singleplayer)"};
+cvar_t cutscene = {CVAR_SERVER, "cutscene", "1", "enables cutscenes in nehahra, can be used by other mods"};
+
+cvar_t sv_autodemo_perclient = {CVAR_SERVER | CVAR_SAVE, "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)"};
+cvar_t sv_autodemo_perclient_nameformat = {CVAR_SERVER | CVAR_SAVE, "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)" };
+cvar_t sv_autodemo_perclient_discardable = {CVAR_SERVER | CVAR_SAVE, "sv_autodemo_perclient_discardable", "0", "Allow game code to decide whether a demo should be kept or discarded."};
+
+cvar_t halflifebsp = {CVAR_SERVER, "halflifebsp", "0", "indicates the current map is hlbsp format (useful to know because of different bounding box sizes)"};
+cvar_t sv_mapformat_is_quake2 = {CVAR_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)"};
+cvar_t sv_mapformat_is_quake3 = {CVAR_SERVER, "sv_mapformat_is_quake3", "0", "indicates the current map is q2bsp format (useful to know because of different entity behaviors)"};
 
 server_t sv;
 server_static_t svs;
 
 mempool_t *sv_mempool = NULL;
 
-extern cvar_t slowmo;
+extern cvar_t host_timescale;
 extern float           scr_centertime_off;
 
 // MUST match effectnameindex_t in client.h
@@ -404,11 +414,15 @@ prvm_required_field_t sv_reqglobals[] =
 #undef PRVM_DECLARE_function
 };
 
-
+static void Host_Timescale_c(cvar_t *var)
+{
+       if(var->value < 0.00001 && var->value != 0)
+               Cvar_SetValueQuick(var, 0);
+}
 
 //============================================================================
 
-void SV_AreaStats_f(void)
+static void SV_AreaStats_f(cmd_state_t *cmd)
 {
        World_PrintAreaStats(&sv.world, "server");
 }
@@ -425,6 +439,7 @@ void SV_Init (void)
        extern cvar_t csqc_progname;    //[515]: csqc crc check and right csprogs name according to progs.dat
        extern cvar_t csqc_progcrc;
        extern cvar_t csqc_progsize;
+       extern cvar_t csqc_usedemoprogs;
 
        Cvar_RegisterVariable(&sv_worldmessage);
        Cvar_RegisterVariable(&sv_worldname);
@@ -434,12 +449,14 @@ void SV_Init (void)
        Cvar_RegisterVariable (&csqc_progname);
        Cvar_RegisterVariable (&csqc_progcrc);
        Cvar_RegisterVariable (&csqc_progsize);
+       Cvar_RegisterVariable (&csqc_usedemoprogs);
 
-       Cmd_AddCommand("sv_saveentfile", SV_SaveEntFile_f, "save map entities to .ent file (to allow external editing)");
-       Cmd_AddCommand("sv_areastats", SV_AreaStats_f, "prints statistics on entity culling during collision traces");
-       Cmd_AddCommand_WithClientCommand("sv_startdownload", NULL, SV_StartDownload_f, "begins sending a file to the client (network protocol use only)");
-       Cmd_AddCommand_WithClientCommand("download", NULL, SV_Download_f, "downloads a specified file from the server");
+       Cmd_AddCommand(CMD_SHARED, "sv_saveentfile", SV_SaveEntFile_f, "save map entities to .ent file (to allow external editing)");
+       Cmd_AddCommand(CMD_SHARED, "sv_areastats", SV_AreaStats_f, "prints statistics on entity culling during collision traces");
+       Cmd_AddCommand(CMD_CLIENT | CMD_SERVER_FROM_CLIENT, "sv_startdownload", SV_StartDownload_f, "begins sending a file to the client (network protocol use only)");
+       Cmd_AddCommand(CMD_CLIENT | CMD_SERVER_FROM_CLIENT, "download", SV_Download_f, "downloads a specified file from the server");
 
+       Cvar_RegisterVariable (&sv_disablenotify);
        Cvar_RegisterVariable (&coop);
        Cvar_RegisterVariable (&deathmatch);
        Cvar_RegisterVariable (&fraglimit);
@@ -450,7 +467,10 @@ void SV_Init (void)
        Cvar_RegisterVariable (&pr_checkextension);
        Cvar_RegisterVariable (&samelevel);
        Cvar_RegisterVariable (&skill);
-       Cvar_RegisterVariable (&slowmo);
+       Cvar_RegisterVariable (&host_timescale);
+       Cvar_RegisterCallback (&host_timescale, Host_Timescale_c);
+       Cvar_RegisterAlias (&host_timescale, "slowmo");
+       Cvar_RegisterAlias (&host_timescale, "timescale");
        Cvar_RegisterVariable (&sv_accelerate);
        Cvar_RegisterVariable (&sv_aim);
        Cvar_RegisterVariable (&sv_airaccel_qw);
@@ -483,6 +503,8 @@ void SV_Init (void)
        Cvar_RegisterVariable (&sv_cullentities_trace_delay);
        Cvar_RegisterVariable (&sv_cullentities_trace_delay_players);
        Cvar_RegisterVariable (&sv_cullentities_trace_enlarge);
+       Cvar_RegisterVariable (&sv_cullentities_trace_expand);
+       Cvar_RegisterVariable (&sv_cullentities_trace_eyejitter);
        Cvar_RegisterVariable (&sv_cullentities_trace_entityocclusion);
        Cvar_RegisterVariable (&sv_cullentities_trace_prediction);
        Cvar_RegisterVariable (&sv_cullentities_trace_prediction_time);
@@ -509,19 +531,24 @@ void SV_Init (void)
        Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
        Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse_allowsuspendeditems);
        Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid);
-       Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid_bias);
+       Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid_separation);
        Cvar_RegisterVariable (&sv_gameplayfix_q2airaccelerate);
        Cvar_RegisterVariable (&sv_gameplayfix_nogravityonground);
        Cvar_RegisterVariable (&sv_gameplayfix_setmodelrealbox);
        Cvar_RegisterVariable (&sv_gameplayfix_slidemoveprojectiles);
        Cvar_RegisterVariable (&sv_gameplayfix_stepdown);
-       Cvar_RegisterVariable (&sv_gameplayfix_stepwhilejumping);
        Cvar_RegisterVariable (&sv_gameplayfix_stepmultipletimes);
        Cvar_RegisterVariable (&sv_gameplayfix_nostepmoveonsteepslopes);
        Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
        Cvar_RegisterVariable (&sv_gameplayfix_upwardvelocityclearsongroundflag);
        Cvar_RegisterVariable (&sv_gameplayfix_downtracesupportsongroundflag);
+       Cvar_RegisterVariable (&sv_gameplayfix_q1bsptracelinereportstexture);
+       Cvar_RegisterVariable (&sv_gameplayfix_unstickplayers);
+       Cvar_RegisterVariable (&sv_gameplayfix_unstickentities);
+       Cvar_RegisterVariable (&sv_gameplayfix_fixedcheckwatertransition);
+       Cvar_RegisterVariable (&sv_gameplayfix_customstats);
        Cvar_RegisterVariable (&sv_gravity);
+       Cvar_RegisterVariable (&sv_init_frame_count);
        Cvar_RegisterVariable (&sv_idealpitchscale);
        Cvar_RegisterVariable (&sv_jumpstep);
        Cvar_RegisterVariable (&sv_jumpvelocity);
@@ -548,9 +575,11 @@ void SV_Init (void)
        Cvar_RegisterVariable (&sv_warsowbunny_turnaccel);
        Cvar_RegisterVariable (&sv_warsowbunny_backtosideratio);
        Cvar_RegisterVariable (&sv_onlycsqcnetworking);
+       Cvar_RegisterVariable (&sv_areadebug);
        Cvar_RegisterVariable (&sys_ticrate);
        Cvar_RegisterVariable (&teamplay);
        Cvar_RegisterVariable (&timelimit);
+       Cvar_RegisterVariable (&sv_threaded);
 
        Cvar_RegisterVariable (&saved1);
        Cvar_RegisterVariable (&saved2);
@@ -563,7 +592,7 @@ void SV_Init (void)
        Cvar_RegisterVariable (&scratch4);
        Cvar_RegisterVariable (&temp1);
 
-       // LordHavoc: Nehahra uses these to pass data around cutscene demos
+       // LadyHavoc: Nehahra uses these to pass data around cutscene demos
        Cvar_RegisterVariable (&nehx00);
        Cvar_RegisterVariable (&nehx01);
        Cvar_RegisterVariable (&nehx02);
@@ -591,18 +620,23 @@ void SV_Init (void)
        Cvar_RegisterVariable (&sv_autodemo_perclient_discardable);
 
        Cvar_RegisterVariable (&halflifebsp);
+       Cvar_RegisterVariable (&sv_mapformat_is_quake2);
+       Cvar_RegisterVariable (&sv_mapformat_is_quake3);
+
+       SV_InitOperatorCommands();
 
        sv_mempool = Mem_AllocPool("server", 0, NULL);
 }
 
-static void SV_SaveEntFile_f(void)
+static void SV_SaveEntFile_f(cmd_state_t *cmd)
 {
+       char vabuf[1024];
        if (!sv.active || !sv.worldmodel)
        {
                Con_Print("Not running a server\n");
                return;
        }
-       FS_WriteFile(va("%s.ent", sv.worldnamenoextension), sv.worldmodel->brush.entities, (fs_offset_t)strlen(sv.worldmodel->brush.entities));
+       FS_WriteFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), sv.worldmodel->brush.entities, (fs_offset_t)strlen(sv.worldmodel->brush.entities));
 }
 
 
@@ -691,13 +725,17 @@ Larger attenuations will drop off.  (max 4 attenuation)
 
 ==================
 */
-void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int volume, float attenuation)
+void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int nvolume, float attenuation, qboolean reliable, float speed)
 {
-       int sound_num, field_mask, i, ent;
+       prvm_prog_t *prog = SVVM_prog;
+       sizebuf_t *dest;
+       int sound_num, field_mask, i, ent, speed4000;
+
+       dest = (reliable ? &sv.reliable_datagram : &sv.datagram);
 
-       if (volume < 0 || volume > 255)
+       if (nvolume < 0 || nvolume > 255)
        {
-               Con_Printf ("SV_StartSound: volume = %i\n", volume);
+               Con_Printf ("SV_StartSound: volume = %i\n", nvolume);
                return;
        }
 
@@ -707,12 +745,14 @@ void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int v
                return;
        }
 
-       if (channel < 0 || channel > 7)
+       if (!IS_CHAN(channel))
        {
                Con_Printf ("SV_StartSound: channel = %i\n", channel);
                return;
        }
 
+       channel = CHAN_ENGINE2NET(channel);
+
        if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
                return;
 
@@ -723,37 +763,45 @@ void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int v
 
        ent = PRVM_NUM_FOR_EDICT(entity);
 
+       speed4000 = (int)floor(speed * 4000.0f + 0.5f);
        field_mask = 0;
-       if (volume != DEFAULT_SOUND_PACKET_VOLUME)
+       if (nvolume != DEFAULT_SOUND_PACKET_VOLUME)
                field_mask |= SND_VOLUME;
        if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
                field_mask |= SND_ATTENUATION;
-       if (ent >= 8192)
+       if (speed4000 && speed4000 != 4000)
+               field_mask |= SND_SPEEDUSHORT4000;
+       if (ent >= 8192 || channel < 0 || channel > 7)
                field_mask |= SND_LARGEENTITY;
-       if (sound_num >= 256 || channel >= 8)
+       if (sound_num >= 256)
                field_mask |= SND_LARGESOUND;
 
 // directed messages go only to the entity they are targeted on
-       MSG_WriteByte (&sv.datagram, svc_sound);
-       MSG_WriteByte (&sv.datagram, field_mask);
+       MSG_WriteByte (dest, svc_sound);
+       MSG_WriteByte (dest, field_mask);
        if (field_mask & SND_VOLUME)
-               MSG_WriteByte (&sv.datagram, volume);
+               MSG_WriteByte (dest, nvolume);
        if (field_mask & SND_ATTENUATION)
-               MSG_WriteByte (&sv.datagram, (int)(attenuation*64));
+               MSG_WriteByte (dest, (int)(attenuation*64));
+       if (field_mask & SND_SPEEDUSHORT4000)
+               MSG_WriteShort (dest, speed4000);
        if (field_mask & SND_LARGEENTITY)
        {
-               MSG_WriteShort (&sv.datagram, ent);
-               MSG_WriteByte (&sv.datagram, channel);
+               MSG_WriteShort (dest, ent);
+               MSG_WriteChar (dest, channel);
        }
        else
-               MSG_WriteShort (&sv.datagram, (ent<<3) | channel);
+               MSG_WriteShort (dest, (ent<<3) | channel);
        if ((field_mask & SND_LARGESOUND) || sv.protocol == PROTOCOL_NEHAHRABJP2)
-               MSG_WriteShort (&sv.datagram, sound_num);
+               MSG_WriteShort (dest, sound_num);
        else
-               MSG_WriteByte (&sv.datagram, sound_num);
+               MSG_WriteByte (dest, sound_num);
        for (i = 0;i < 3;i++)
-               MSG_WriteCoord (&sv.datagram, entity->fields.server->origin[i]+0.5*(entity->fields.server->mins[i]+entity->fields.server->maxs[i]), sv.protocol);
-       SV_FlushBroadcastMessages();
+               MSG_WriteCoord (dest, PRVM_serveredictvector(entity, origin)[i]+0.5*(PRVM_serveredictvector(entity, mins)[i]+PRVM_serveredictvector(entity, maxs)[i]), sv.protocol);
+
+       // TODO do we have to do anything here when dest is &sv.reliable_datagram?
+       if(!reliable)
+               SV_FlushBroadcastMessages();
 }
 
 /*
@@ -769,13 +817,13 @@ function, therefore the check for it is omitted.
 
 ==================
 */
-void SV_StartPointSound (vec3_t origin, const char *sample, int volume, float attenuation)
+void SV_StartPointSound (vec3_t origin, const char *sample, int nvolume, float attenuation, float speed)
 {
-       int sound_num, field_mask, i;
+       int sound_num, field_mask, i, speed4000;
 
-       if (volume < 0 || volume > 255)
+       if (nvolume < 0 || nvolume > 255)
        {
-               Con_Printf ("SV_StartPointSound: volume = %i\n", volume);
+               Con_Printf ("SV_StartPointSound: volume = %i\n", nvolume);
                return;
        }
 
@@ -793,21 +841,26 @@ void SV_StartPointSound (vec3_t origin, const char *sample, int volume, float at
        if (!sound_num)
                return;
 
+       speed4000 = (int)(speed * 40.0f);
        field_mask = 0;
-       if (volume != DEFAULT_SOUND_PACKET_VOLUME)
+       if (nvolume != DEFAULT_SOUND_PACKET_VOLUME)
                field_mask |= SND_VOLUME;
        if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
                field_mask |= SND_ATTENUATION;
        if (sound_num >= 256)
                field_mask |= SND_LARGESOUND;
+       if (speed4000 && speed4000 != 4000)
+               field_mask |= SND_SPEEDUSHORT4000;
 
 // directed messages go only to the entity they are targeted on
        MSG_WriteByte (&sv.datagram, svc_sound);
        MSG_WriteByte (&sv.datagram, field_mask);
        if (field_mask & SND_VOLUME)
-               MSG_WriteByte (&sv.datagram, volume);
+               MSG_WriteByte (&sv.datagram, nvolume);
        if (field_mask & SND_ATTENUATION)
                MSG_WriteByte (&sv.datagram, (int)(attenuation*64));
+       if (field_mask & SND_SPEEDUSHORT4000)
+               MSG_WriteShort (&sv.datagram, speed4000);
        // Always write entnum 0 for the world entity
        MSG_WriteShort (&sv.datagram, (0<<3) | 0);
        if (field_mask & SND_LARGESOUND)
@@ -837,8 +890,10 @@ This will be sent on the initial connection and upon each server load.
 */
 void SV_SendServerinfo (client_t *client)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int i;
        char message[128];
+       char vabuf[1024];
 
        // we know that this client has a netconnection and thus is not a bot
 
@@ -849,7 +904,7 @@ void SV_SendServerinfo (client_t *client)
        client->weaponmodel[0] = 0;
        client->weaponmodelindex = 0;
 
-       // LordHavoc: clear entityframe tracking
+       // LadyHavoc: clear entityframe tracking
        client->latestframenum = 0;
 
        // initialize the movetime, so a speedhack can't make use of the time before this client joined
@@ -880,7 +935,6 @@ void SV_SendServerinfo (client_t *client)
        {
                client->csqcentityscope[i] = 0;
                client->csqcentitysendflags[i] = 0xFFFFFF;
-               client->csqcentityglobalhistory[i] = 0;
        }
        for (i = 0;i < NUM_CSQCENTITYDB_FRAMES;i++)
        {
@@ -896,17 +950,17 @@ void SV_SendServerinfo (client_t *client)
        MSG_WriteString (&client->netconnection->message,message);
 
        SV_StopDemoRecording(client); // to split up demos into different files
-       if(sv_autodemo_perclient.integer && client->netconnection)
+       if(sv_autodemo_perclient.integer)
        {
                char demofile[MAX_OSPATH];
                char ipaddress[MAX_QPATH];
-               size_t i;
+               size_t j;
 
                // start a new demo file
                LHNETADDRESS_ToString(&(client->netconnection->peeraddress), ipaddress, sizeof(ipaddress), true);
-               for(i = 0; ipaddress[i]; ++i)
-                       if(!isalnum(ipaddress[i]))
-                               ipaddress[i] = '-';
+               for(j = 0; ipaddress[j]; ++j)
+                       if(!isalnum(ipaddress[j]))
+                               ipaddress[j] = '-';
                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);
 
                SV_StartDemoRecording(client, demofile, -1);
@@ -917,30 +971,30 @@ void SV_SendServerinfo (client_t *client)
        {
                Con_DPrintf("sending csqc info to client (\"%s\" with size %i and crc %i)\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
                MSG_WriteByte (&client->netconnection->message, svc_stufftext);
-               MSG_WriteString (&client->netconnection->message, va("csqc_progname %s\n", sv.csqc_progname));
+               MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progname %s\n", sv.csqc_progname));
                MSG_WriteByte (&client->netconnection->message, svc_stufftext);
-               MSG_WriteString (&client->netconnection->message, va("csqc_progsize %i\n", sv.csqc_progsize));
+               MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progsize %i\n", sv.csqc_progsize));
                MSG_WriteByte (&client->netconnection->message, svc_stufftext);
-               MSG_WriteString (&client->netconnection->message, va("csqc_progcrc %i\n", sv.csqc_progcrc));
+               MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progcrc %i\n", sv.csqc_progcrc));
 
                if(client->sv_demo_file != NULL)
                {
-                       int i;
+                       int k;
                        static char buf[NET_MAXMESSAGE];
                        sizebuf_t sb;
 
                        sb.data = (unsigned char *) buf;
                        sb.maxsize = sizeof(buf);
-                       i = 0;
-                       while(MakeDownloadPacket(sv.csqc_progname, svs.csqc_progdata, sv.csqc_progsize, sv.csqc_progcrc, i++, &sb, sv.protocol))
+                       k = 0;
+                       while(MakeDownloadPacket(sv.csqc_progname, svs.csqc_progdata, sv.csqc_progsize, sv.csqc_progcrc, k++, &sb, sv.protocol))
                                SV_WriteDemoMessage(client, &sb, false);
                }
 
                //[515]: init stufftext string (it is sent before svc_serverinfo)
-               if (PRVM_GetString(PRVM_serverglobalstring(SV_InitCmd)))
+               if (PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd)))
                {
                        MSG_WriteByte (&client->netconnection->message, svc_stufftext);
-                       MSG_WriteString (&client->netconnection->message, va("%s\n", PRVM_GetString(PRVM_serverglobalstring(SV_InitCmd))));
+                       MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "%s\n", PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd))));
                }
        }
 
@@ -970,7 +1024,7 @@ void SV_SendServerinfo (client_t *client)
        else
                MSG_WriteByte (&client->netconnection->message, GAME_COOP);
 
-       MSG_WriteString (&client->netconnection->message,PRVM_GetString(prog->edicts->fields.server->message));
+       MSG_WriteString (&client->netconnection->message,PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)));
 
        for (i = 1;i < MAX_MODELS && sv.model_precache[i][0];i++)
                MSG_WriteString (&client->netconnection->message, sv.model_precache[i]);
@@ -982,8 +1036,8 @@ void SV_SendServerinfo (client_t *client)
 
 // send music
        MSG_WriteByte (&client->netconnection->message, svc_cdtrack);
-       MSG_WriteByte (&client->netconnection->message, (int)prog->edicts->fields.server->sounds);
-       MSG_WriteByte (&client->netconnection->message, (int)prog->edicts->fields.server->sounds);
+       MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));
+       MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));
 
 // set view
 // store this in clientcamera, too
@@ -994,7 +1048,9 @@ void SV_SendServerinfo (client_t *client)
        MSG_WriteByte (&client->netconnection->message, svc_signonnum);
        MSG_WriteByte (&client->netconnection->message, 1);
 
+       client->prespawned = false;             // need prespawn, spawn, etc
        client->spawned = false;                // need prespawn, spawn, etc
+       client->begun = false;                  // need prespawn, spawn, etc
        client->sendsignon = 1;                 // send this message, and increment to 2, 2 will be set to 0 by the prespawn command
 
        // clear movement info until client enters the new level properly
@@ -1010,7 +1066,7 @@ void SV_SendServerinfo (client_t *client)
        client->ping = 0;
 
        // allow the client some time to send his keepalives, even if map loading took ages
-       client->netconnection->timeout = realtime + net_connecttimeout.value;
+       client->netconnection->timeout = host.realtime + net_connecttimeout.value;
 }
 
 /*
@@ -1023,6 +1079,7 @@ once for a player each game, not once for each level change.
 */
 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
 {
+       prvm_prog_t *prog = SVVM_prog;
        client_t                *client;
        int                             i;
 
@@ -1045,19 +1102,23 @@ void SV_ConnectClient (int clientnum, netconn_t *netconnection)
 
        if(client->netconnection && client->netconnection->crypto.authenticated)
        {
-               Con_Printf("%s connection to %s has been established: client is %s@%.*s, I am %.*s@%.*s\n",
+               Con_Printf("%s connection to %s has been established: client is %s@%s%.*s, I am %.*s@%s%.*s\n",
                                client->netconnection->crypto.use_aes ? "Encrypted" : "Authenticated",
                                client->netconnection->address,
                                client->netconnection->crypto.client_idfp[0] ? client->netconnection->crypto.client_idfp : "-",
+                               (client->netconnection->crypto.client_issigned || !client->netconnection->crypto.client_keyfp[0]) ? "" : "~",
                                crypto_keyfp_recommended_length, client->netconnection->crypto.client_keyfp[0] ? client->netconnection->crypto.client_keyfp : "-",
                                crypto_keyfp_recommended_length, client->netconnection->crypto.server_idfp[0] ? client->netconnection->crypto.server_idfp : "-",
+                               (client->netconnection->crypto.server_issigned || !client->netconnection->crypto.server_keyfp[0]) ? "" : "~",
                                crypto_keyfp_recommended_length, client->netconnection->crypto.server_keyfp[0] ? client->netconnection->crypto.server_keyfp : "-"
                                );
        }
 
        strlcpy(client->name, "unconnected", sizeof(client->name));
        strlcpy(client->old_name, "unconnected", sizeof(client->old_name));
+       client->prespawned = false;
        client->spawned = false;
+       client->begun = false;
        client->edict = PRVM_EDICT_NUM(clientnum+1);
        if (client->netconnection)
                client->netconnection->message.allowoverflow = true;            // we can catch it
@@ -1066,22 +1127,20 @@ void SV_ConnectClient (int clientnum, netconn_t *netconnection)
        client->unreliablemsg.maxsize = sizeof(client->unreliablemsg_data);
        // updated by receiving "rate" command from client, this is also the default if not using a DP client
        client->rate = 1000000000;
-       // no limits for local player
-       if (client->netconnection && LHNETADDRESS_GetAddressType(&client->netconnection->peeraddress) == LHNETADDRESSTYPE_LOOP)
-               client->rate = 1000000000;
-       client->connecttime = realtime;
+       client->connecttime = host.realtime;
 
        if (!sv.loadgame)
        {
                // call the progs to get default spawn parms for the new client
                // set self to world to intentionally cause errors with broken SetNewParms code in some mods
-               prog->globals.server->self = 0;
-               PRVM_ExecuteProgram (prog->globals.server->SetNewParms, "QC function SetNewParms is missing");
+               PRVM_serverglobalfloat(time) = sv.time;
+               PRVM_serverglobaledict(self) = 0;
+               prog->ExecuteProgram(prog, PRVM_serverfunction(SetNewParms), "QC function SetNewParms is missing");
                for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
-                       client->spawn_parms[i] = (&prog->globals.server->parm1)[i];
+                       client->spawn_parms[i] = (&PRVM_serverglobalfloat(parm1))[i];
 
                // set up the entity for this client (including .colormap, .team, etc)
-               PRVM_ED_ClearEdict(client->edict);
+               PRVM_ED_ClearEdict(prog, client->edict);
        }
 
        // don't call SendServerinfo for a fresh botclient because its fields have
@@ -1089,9 +1148,129 @@ void SV_ConnectClient (int clientnum, netconn_t *netconnection)
        if (client->netconnection)
                SV_SendServerinfo (client);
        else
-               client->spawned = true;
+               client->prespawned = client->spawned = client->begun = true;
 }
 
+/*
+=====================
+SV_DropClient
+
+Called when the player is getting totally kicked off the host
+if (crash = true), don't bother sending signofs
+=====================
+*/
+void SV_DropClient(qboolean crash)
+{
+       prvm_prog_t *prog = SVVM_prog;
+       int i;
+       Con_Printf("Client \"%s\" dropped\n", host_client->name);
+
+       SV_StopDemoRecording(host_client);
+
+       // make sure edict is not corrupt (from a level change for example)
+       host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
+
+       if (host_client->netconnection)
+       {
+               // tell the client to be gone
+               if (!crash)
+               {
+                       // LadyHavoc: no opportunity for resending, so use unreliable 3 times
+                       unsigned char bufdata[8];
+                       sizebuf_t buf;
+                       memset(&buf, 0, sizeof(buf));
+                       buf.data = bufdata;
+                       buf.maxsize = sizeof(bufdata);
+                       MSG_WriteByte(&buf, svc_disconnect);
+                       NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
+                       NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
+                       NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
+               }
+       }
+
+       // call qc ClientDisconnect function
+       // LadyHavoc: don't call QC if server is dead (avoids recursive
+       // Host_Error in some mods when they run out of edicts)
+       if (host_client->clientconnectcalled && sv.active && host_client->edict)
+       {
+               // call the prog function for removing a client
+               // this will set the body to a dead frame, among other things
+               int saveSelf = PRVM_serverglobaledict(self);
+               host_client->clientconnectcalled = false;
+               PRVM_serverglobalfloat(time) = sv.time;
+               PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
+               prog->ExecuteProgram(prog, PRVM_serverfunction(ClientDisconnect), "QC function ClientDisconnect is missing");
+               PRVM_serverglobaledict(self) = saveSelf;
+       }
+
+       if (host_client->netconnection)
+       {
+               // break the net connection
+               NetConn_Close(host_client->netconnection);
+               host_client->netconnection = NULL;
+       }
+
+       // if a download is active, close it
+       if (host_client->download_file)
+       {
+               Con_DPrintf("Download of %s aborted when %s dropped\n", host_client->download_name, host_client->name);
+               FS_Close(host_client->download_file);
+               host_client->download_file = NULL;
+               host_client->download_name[0] = 0;
+               host_client->download_expectedposition = 0;
+               host_client->download_started = false;
+       }
+
+       // remove leaving player from scoreboard
+       host_client->name[0] = 0;
+       host_client->colors = 0;
+       host_client->frags = 0;
+       // send notification to all clients
+       // get number of client manually just to make sure we get it right...
+       i = host_client - svs.clients;
+       MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
+       MSG_WriteByte (&sv.reliable_datagram, i);
+       MSG_WriteString (&sv.reliable_datagram, host_client->name);
+       MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
+       MSG_WriteByte (&sv.reliable_datagram, i);
+       MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
+       MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
+       MSG_WriteByte (&sv.reliable_datagram, i);
+       MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
+
+       // free the client now
+       if (host_client->entitydatabase)
+               EntityFrame_FreeDatabase(host_client->entitydatabase);
+       if (host_client->entitydatabase4)
+               EntityFrame4_FreeDatabase(host_client->entitydatabase4);
+       if (host_client->entitydatabase5)
+               EntityFrame5_FreeDatabase(host_client->entitydatabase5);
+
+       if (sv.active)
+       {
+               // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
+               PRVM_ED_ClearEdict(prog, host_client->edict);
+       }
+
+       // clear the client struct (this sets active to false)
+       memset(host_client, 0, sizeof(*host_client));
+
+       // update server listing on the master because player count changed
+       // (which the master uses for filtering empty/full servers)
+       NetConn_Heartbeat(1);
+
+       if (sv.loadgame)
+       {
+               for (i = 0;i < svs.maxclients;i++)
+                       if (svs.clients[i].active && !svs.clients[i].spawned)
+                               break;
+               if (i == svs.maxclients)
+               {
+                       Con_Printf("Loaded game, everyone rejoined - unpausing\n");
+                       sv.paused = sv.loadgame = false; // we're basically done with loading now
+               }
+       }
+}
 
 /*
 ===============================================================================
@@ -1114,6 +1293,7 @@ crosses a waterline.
 
 static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *cs, int enumber)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int i;
        unsigned int sendflags;
        unsigned int version;
@@ -1121,7 +1301,7 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
        unsigned int customizeentityforclient;
        unsigned int sendentity;
        float f;
-       float *v;
+       prvm_vec_t *v;
        vec3_t cullmins, cullmaxs;
        dp_model_t *model;
 
@@ -1133,18 +1313,18 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
 
        // this 2 billion unit check is actually to detect NAN origins
        // (we really don't want to send those)
-       if (!(VectorLength2(ent->fields.server->origin) < 2000000000.0*2000000000.0))
+       if (!(VectorLength2(PRVM_serveredictvector(ent, origin)) < 2000000000.0*2000000000.0))
                return false;
 
        // EF_NODRAW prevents sending for any reason except for your own
        // client, so we must keep all clients in this superset
-       effects = (unsigned)ent->fields.server->effects;
+       effects = (unsigned)PRVM_serveredictfloat(ent, effects);
 
        // we can omit invisible entities with no effects that are not clients
-       // LordHavoc: this could kill tags attached to an invisible entity, I
+       // LadyHavoc: this could kill tags attached to an invisible entity, I
        // just hope we never have to support that case
-       i = (int)ent->fields.server->modelindex;
-       modelindex = (i >= 1 && i < MAX_MODELS && ent->fields.server->model && *PRVM_GetString(ent->fields.server->model) && sv.models[i]) ? i : 0;
+       i = (int)PRVM_serveredictfloat(ent, modelindex);
+       modelindex = (i >= 1 && i < MAX_MODELS && PRVM_serveredictstring(ent, model) && *PRVM_GetString(prog, PRVM_serveredictstring(ent, model)) && sv.models[i]) ? i : 0;
 
        flags = 0;
        i = (int)(PRVM_serveredictfloat(ent, glow_size) * 0.25f);
@@ -1222,14 +1402,14 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
        *cs = defaultstate;
        cs->active = ACTIVE_NETWORK;
        cs->number = enumber;
-       VectorCopy(ent->fields.server->origin, cs->origin);
-       VectorCopy(ent->fields.server->angles, cs->angles);
+       VectorCopy(PRVM_serveredictvector(ent, origin), cs->origin);
+       VectorCopy(PRVM_serveredictvector(ent, angles), cs->angles);
        cs->flags = flags;
        cs->effects = effects;
-       cs->colormap = (unsigned)ent->fields.server->colormap;
+       cs->colormap = (unsigned)PRVM_serveredictfloat(ent, colormap);
        cs->modelindex = modelindex;
-       cs->skin = (unsigned)ent->fields.server->skin;
-       cs->frame = (unsigned)ent->fields.server->frame;
+       cs->skin = (unsigned)PRVM_serveredictfloat(ent, skin);
+       cs->frame = (unsigned)PRVM_serveredictfloat(ent, frame);
        cs->viewmodelforclient = PRVM_serveredictedict(ent, viewmodelforclient);
        cs->exteriormodelforclient = PRVM_serveredictedict(ent, exteriormodeltoclient);
        cs->nodrawtoclient = PRVM_serveredictedict(ent, nodrawtoclient);
@@ -1238,6 +1418,7 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
        cs->tagentity = PRVM_serveredictedict(ent, tag_entity);
        cs->tagindex = (unsigned char)PRVM_serveredictfloat(ent, tag_index);
        cs->glowsize = glowsize;
+       cs->traileffectnum = PRVM_serveredictfloat(ent, traileffectnum);
 
        // don't need to init cs->colormod because the defaultstate did that for us
        //cs->colormod[0] = cs->colormod[1] = cs->colormod[2] = 32;
@@ -1296,11 +1477,11 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
        if (f)
                cs->effects |= ((unsigned int)f & 0xff) << 24;
 
-       if (ent->fields.server->movetype == MOVETYPE_STEP)
+       if (PRVM_serveredictfloat(ent, movetype) == MOVETYPE_STEP)
                cs->flags |= RENDER_STEP;
        if (cs->number != sv.writeentitiestoclient_cliententitynumber && (cs->effects & EF_LOWPRECISION) && cs->origin[0] >= -32768 && cs->origin[1] >= -32768 && cs->origin[2] >= -32768 && cs->origin[0] <= 32767 && cs->origin[1] <= 32767 && cs->origin[2] <= 32767)
                cs->flags |= RENDER_LOWPRECISION;
-       if (ent->fields.server->colormap >= 1024)
+       if (PRVM_serveredictfloat(ent, colormap) >= 1024)
                cs->flags |= RENDER_COLORMAPPED;
        if (cs->viewmodelforclient)
                cs->flags |= RENDER_VIEWMODEL; // show relative to the view
@@ -1322,6 +1503,7 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
                cs->framegroupblend[2].lerp = PRVM_serveredictfloat(ent, lerpfrac3);
                cs->framegroupblend[3].lerp = PRVM_serveredictfloat(ent, lerpfrac4);
                cs->framegroupblend[0].lerp = 1.0f - cs->framegroupblend[1].lerp - cs->framegroupblend[2].lerp - cs->framegroupblend[3].lerp;
+               cs->frame = 0; // don't need the legacy frame
        }
 
        cs->light[0] = light[0];
@@ -1358,8 +1540,8 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
        else
        {
                // if there is no model (or it could not be loaded), use the physics box
-               VectorAdd(cs->origin, ent->fields.server->mins, cullmins);
-               VectorAdd(cs->origin, ent->fields.server->maxs, cullmaxs);
+               VectorAdd(cs->origin, PRVM_serveredictvector(ent, mins), cullmins);
+               VectorAdd(cs->origin, PRVM_serveredictvector(ent, maxs), cullmaxs);
        }
        if (specialvisibilityradius)
        {
@@ -1417,8 +1599,9 @@ static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *c
        return true;
 }
 
-void SV_PrepareEntitiesForSending(void)
+static void SV_PrepareEntitiesForSending(void)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int e;
        prvm_edict_t *ent;
        // send all entities that touch the pvs
@@ -1437,11 +1620,14 @@ void SV_PrepareEntitiesForSending(void)
 
 #define MAX_LINEOFSIGHTTRACES 64
 
-qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
+qboolean SV_CanSeeBox(int numtraces, vec_t eyejitter, vec_t enlarge, vec_t entboxexpand, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
 {
+       prvm_prog_t *prog = SVVM_prog;
        float pitchsign;
        float alpha;
        float starttransformed[3], endtransformed[3];
+       float boxminstransformed[3], boxmaxstransformed[3];
+       float localboxcenter[3], localboxextents[3], localboxmins[3], localboxmaxs[3];
        int blocked = 0;
        int traceindex;
        int originalnumtouchedicts;
@@ -1451,27 +1637,35 @@ qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmin
        dp_model_t *model;
        prvm_edict_t *touch;
        static prvm_edict_t *touchedicts[MAX_EDICTS];
+       vec3_t eyemins, eyemaxs, start;
        vec3_t boxmins, boxmaxs;
        vec3_t clipboxmins, clipboxmaxs;
        vec3_t endpoints[MAX_LINEOFSIGHTTRACES];
 
        numtraces = min(numtraces, MAX_LINEOFSIGHTTRACES);
 
+       // jitter the eye location within this box
+       eyemins[0] = eye[0] - eyejitter;
+       eyemaxs[0] = eye[0] + eyejitter;
+       eyemins[1] = eye[1] - eyejitter;
+       eyemaxs[1] = eye[1] + eyejitter;
+       eyemins[2] = eye[2] - eyejitter;
+       eyemaxs[2] = eye[2] + eyejitter;
        // expand the box a little
-       boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
-       boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
-       boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
-       boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
-       boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
-       boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
+       boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0] - entboxexpand;
+       boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0] + entboxexpand;
+       boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1] - entboxexpand;
+       boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1] + entboxexpand;
+       boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2] - entboxexpand;
+       boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2] + entboxexpand;
 
        VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, endpoints[0]);
        for (traceindex = 1;traceindex < numtraces;traceindex++)
                VectorSet(endpoints[traceindex], lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
 
        // calculate sweep box for the entire swarm of traces
-       VectorCopy(eye, clipboxmins);
-       VectorCopy(eye, clipboxmaxs);
+       VectorCopy(eyemins, clipboxmins);
+       VectorCopy(eyemaxs, clipboxmaxs);
        for (traceindex = 0;traceindex < numtraces;traceindex++)
        {
                clipboxmins[0] = min(clipboxmins[0], endpoints[traceindex][0]);
@@ -1484,7 +1678,7 @@ qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmin
 
        // get the list of entities in the sweep box
        if (sv_cullentities_trace_entityocclusion.integer)
-               numtouchedicts = World_EntitiesInBox(&sv.world, clipboxmins, clipboxmaxs, MAX_EDICTS, touchedicts);
+               numtouchedicts = SV_EntitiesInBox(clipboxmins, clipboxmaxs, MAX_EDICTS, touchedicts);
        if (numtouchedicts > MAX_EDICTS)
        {
                // this never happens
@@ -1497,7 +1691,7 @@ qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmin
        for (touchindex = 0;touchindex < originalnumtouchedicts;touchindex++)
        {
                touch = touchedicts[touchindex];
-               if (touch->fields.server->solid != SOLID_BSP)
+               if (PRVM_serveredictfloat(touch, solid) != SOLID_BSP)
                        continue;
                model = SV_GetModelFromEdict(touch);
                if (!model || !model->brush.TraceLineOfSight)
@@ -1506,7 +1700,7 @@ qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmin
                alpha = PRVM_serveredictfloat(touch, alpha);
                if (alpha && alpha < 1)
                        continue;
-               if ((int)touch->fields.server->effects & EF_ADDITIVE)
+               if ((int)PRVM_serveredictfloat(touch, effects) & EF_ADDITIVE)
                        continue;
                touchedicts[numtouchedicts++] = touch;
        }
@@ -1517,9 +1711,10 @@ qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmin
 
        for (traceindex = 0;traceindex < numtraces;traceindex++)
        {
+               VectorSet(start, lhrandom(eyemins[0], eyemaxs[0]), lhrandom(eyemins[1], eyemaxs[1]), lhrandom(eyemins[2], eyemaxs[2]));
                // check world occlusion
                if (sv.worldmodel && sv.worldmodel->brush.TraceLineOfSight)
-                       if (!sv.worldmodel->brush.TraceLineOfSight(sv.worldmodel, eye, endpoints[traceindex]))
+                       if (!sv.worldmodel->brush.TraceLineOfSight(sv.worldmodel, start, endpoints[traceindex], boxmins, boxmaxs))
                                continue;
                for (touchindex = 0;touchindex < numtouchedicts;touchindex++)
                {
@@ -1528,13 +1723,26 @@ qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmin
                        if(model && model->brush.TraceLineOfSight)
                        {
                                // get the entity matrix
-                               pitchsign = SV_GetPitchSign(touch);
-                               Matrix4x4_CreateFromQuakeEntity(&matrix, touch->fields.server->origin[0], touch->fields.server->origin[1], touch->fields.server->origin[2], pitchsign * touch->fields.server->angles[0], touch->fields.server->angles[1], touch->fields.server->angles[2], 1);
+                               pitchsign = SV_GetPitchSign(prog, touch);
+                               Matrix4x4_CreateFromQuakeEntity(&matrix, PRVM_serveredictvector(touch, origin)[0], PRVM_serveredictvector(touch, origin)[1], PRVM_serveredictvector(touch, origin)[2], pitchsign * PRVM_serveredictvector(touch, angles)[0], PRVM_serveredictvector(touch, angles)[1], PRVM_serveredictvector(touch, angles)[2], 1);
                                Matrix4x4_Invert_Simple(&imatrix, &matrix);
                                // see if the ray hits this entity
-                               Matrix4x4_Transform(&imatrix, eye, starttransformed);
+                               Matrix4x4_Transform(&imatrix, start, starttransformed);
                                Matrix4x4_Transform(&imatrix, endpoints[traceindex], endtransformed);
-                               if (!model->brush.TraceLineOfSight(model, starttransformed, endtransformed))
+                               Matrix4x4_Transform(&imatrix, boxmins, boxminstransformed);
+                               Matrix4x4_Transform(&imatrix, boxmaxs, boxmaxstransformed);
+                               // transform the AABB to local space
+                               VectorMAM(0.5f, boxminstransformed, 0.5f, boxmaxstransformed, localboxcenter);
+                               localboxextents[0] = fabs(boxmaxstransformed[0] - localboxcenter[0]);
+                               localboxextents[1] = fabs(boxmaxstransformed[1] - localboxcenter[1]);
+                               localboxextents[2] = fabs(boxmaxstransformed[2] - localboxcenter[2]);
+                               localboxmins[0] = localboxcenter[0] - localboxextents[0];
+                               localboxmins[1] = localboxcenter[1] - localboxextents[1];
+                               localboxmins[2] = localboxcenter[2] - localboxextents[2];
+                               localboxmaxs[0] = localboxcenter[0] + localboxextents[0];
+                               localboxmaxs[1] = localboxcenter[1] + localboxextents[1];
+                               localboxmaxs[2] = localboxcenter[2] + localboxextents[2];
+                               if (!model->brush.TraceLineOfSight(model, starttransformed, endtransformed, localboxmins, localboxmaxs))
                                {
                                        blocked++;
                                        break;
@@ -1552,8 +1760,9 @@ qboolean SV_CanSeeBox(int numtraces, vec_t enlarge, vec3_t eye, vec3_t entboxmin
        return false;
 }
 
-void SV_MarkWriteEntityStateToClient(entity_state_t *s)
+static void SV_MarkWriteEntityStateToClient(entity_state_t *s)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int isbmodel;
        dp_model_t *model;
        prvm_edict_t *ed;
@@ -1564,9 +1773,10 @@ void SV_MarkWriteEntityStateToClient(entity_state_t *s)
 
        if (s->customizeentityforclient)
        {
-               prog->globals.server->self = s->number;
-               prog->globals.server->other = sv.writeentitiestoclient_cliententitynumber;
-               PRVM_ExecuteProgram(s->customizeentityforclient, "customizeentityforclient: NULL function");
+               PRVM_serverglobalfloat(time) = sv.time;
+               PRVM_serverglobaledict(self) = s->number;
+               PRVM_serverglobaledict(other) = sv.writeentitiestoclient_cliententitynumber;
+               prog->ExecuteProgram(prog, s->customizeentityforclient, "customizeentityforclient: NULL function");
                if(!PRVM_G_FLOAT(OFS_RETURN) || !SV_PrepareEntityForSending(PRVM_EDICT_NUM(s->number), s, s->number))
                        return;
        }
@@ -1581,7 +1791,7 @@ void SV_MarkWriteEntityStateToClient(entity_state_t *s)
                        return;
                if (s->effects & EF_NODRAW)
                        return;
-               // LordHavoc: only send entities with a model or important effects
+               // LadyHavoc: only send entities with a model or important effects
                if (!s->modelindex && s->specialvisibilityradius == 0)
                        return;
 
@@ -1610,7 +1820,7 @@ void SV_MarkWriteEntityStateToClient(entity_state_t *s)
                        ed = PRVM_EDICT_NUM(s->number);
 
                        // if not touching a visible leaf
-                       if (sv_cullentities_pvs.integer && !r_novis.integer && sv.writeentitiestoclient_pvsbytes)
+                       if (sv_cullentities_pvs.integer && !r_novis.integer && !r_trippy.integer && sv.writeentitiestoclient_pvsbytes)
                        {
                                if (ed->priv.server->pvs_numclusters < 0)
                                {
@@ -1637,7 +1847,7 @@ void SV_MarkWriteEntityStateToClient(entity_state_t *s)
                        }
 
                        // or not seen by random tracelines
-                       if (sv_cullentities_trace.integer && !isbmodel && sv.worldmodel->brush.TraceLineOfSight)
+                       if (sv_cullentities_trace.integer && !isbmodel && sv.worldmodel && sv.worldmodel->brush.TraceLineOfSight && !r_trippy.integer)
                        {
                                int samples =
                                        s->number <= svs.maxclients
@@ -1652,16 +1862,16 @@ void SV_MarkWriteEntityStateToClient(entity_state_t *s)
                                {
                                        int eyeindex;
                                        for (eyeindex = 0;eyeindex < sv.writeentitiestoclient_numeyes;eyeindex++)
-                                               if(SV_CanSeeBox(samples, enlarge, sv.writeentitiestoclient_eyes[eyeindex], ed->priv.server->cullmins, ed->priv.server->cullmaxs))
+                                               if(SV_CanSeeBox(samples, sv_cullentities_trace_eyejitter.value, enlarge, sv_cullentities_trace_expand.value, sv.writeentitiestoclient_eyes[eyeindex], ed->priv.server->cullmins, ed->priv.server->cullmaxs))
                                                        break;
                                        if(eyeindex < sv.writeentitiestoclient_numeyes)
                                                svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number] =
-                                                       realtime + (
+                                                       host.realtime + (
                                                                s->number <= svs.maxclients
                                                                        ? sv_cullentities_trace_delay_players.value
                                                                        : sv_cullentities_trace_delay.value
                                                        );
-                                       else if (realtime > svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number])
+                                       else if (host.realtime > svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number])
                                        {
                                                sv.writeentitiestoclient_stats_culled_trace++;
                                                return;
@@ -1680,8 +1890,9 @@ void SV_MarkWriteEntityStateToClient(entity_state_t *s)
 
 #if MAX_LEVELNETWORKEYES > 0
 #define MAX_EYE_RECURSION 1 // increase if recursion gets supported by portals
-void SV_AddCameraEyes(void)
+static void SV_AddCameraEyes(void)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int e, i, j, k;
        prvm_edict_t *ed;
        static int cameras[MAX_LEVELNETWORKEYES];
@@ -1700,12 +1911,13 @@ void SV_AddCameraEyes(void)
                {
                        if(PRVM_serveredictfunction(ed, camera_transform))
                        {
-                               prog->globals.server->self = e;
-                               prog->globals.server->other = sv.writeentitiestoclient_cliententitynumber;
+                               PRVM_serverglobalfloat(time) = sv.time;
+                               PRVM_serverglobaledict(self) = e;
+                               PRVM_serverglobaledict(other) = sv.writeentitiestoclient_cliententitynumber;
                                VectorCopy(sv.writeentitiestoclient_eyes[0], PRVM_serverglobalvector(trace_endpos));
                                VectorCopy(sv.writeentitiestoclient_eyes[0], PRVM_G_VECTOR(OFS_PARM0));
                                VectorClear(PRVM_G_VECTOR(OFS_PARM1));
-                               PRVM_ExecuteProgram(PRVM_serveredictfunction(ed, camera_transform), "QC function e.camera_transform is missing");
+                               prog->ExecuteProgram(prog, PRVM_serveredictfunction(ed, camera_transform), "QC function e.camera_transform is missing");
                                if(!VectorCompare(PRVM_serverglobalvector(trace_endpos), sv.writeentitiestoclient_eyes[0]))
                                {
                                        VectorCopy(PRVM_serverglobalvector(trace_endpos), camera_origins[n_cameras]);
@@ -1728,12 +1940,12 @@ void SV_AddCameraEyes(void)
                if(!cameras[j])
                        continue;
                ed = PRVM_EDICT_NUM(cameras[j]);
-               VectorAdd(ed->fields.server->origin, ed->fields.server->mins, mi);
-               VectorAdd(ed->fields.server->origin, ed->fields.server->maxs, ma);
+               VectorAdd(PRVM_serveredictvector(ed, origin), PRVM_serveredictvector(ed, mins), mi);
+               VectorAdd(PRVM_serveredictvector(ed, origin), PRVM_serveredictvector(ed, maxs), ma);
                for(k = 0; k < sv.writeentitiestoclient_numeyes; ++k)
                if(eye_levels[k] <= MAX_EYE_RECURSION)
                {
-                       if(SV_CanSeeBox(sv_cullentities_trace_samples.integer, sv_cullentities_trace_enlarge.value, sv.writeentitiestoclient_eyes[k], mi, ma))
+                       if(SV_CanSeeBox(sv_cullentities_trace_samples.integer, sv_cullentities_trace_eyejitter.value, sv_cullentities_trace_enlarge.value, sv_cullentities_trace_expand.value, sv.writeentitiestoclient_eyes[k], mi, ma))
                        {
                                eye_levels[sv.writeentitiestoclient_numeyes] = eye_levels[k] + 1;
                                VectorCopy(camera_origins[j], sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes]);
@@ -1752,8 +1964,9 @@ void SV_AddCameraEyes(void)
 }
 #endif
 
-void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *msg, int maxsize)
+static void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *msg, int maxsize)
 {
+       prvm_prog_t *prog = SVVM_prog;
        qboolean need_empty = false;
        int i, numsendstates, numcsqcsendstates;
        entity_state_t *s;
@@ -1775,9 +1988,9 @@ void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *
        sv.writeentitiestoclient_numeyes = 0;
 
        // get eye location
-       sv.writeentitiestoclient_cliententitynumber = PRVM_EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
+       sv.writeentitiestoclient_cliententitynumber = PRVM_EDICT_TO_PROG(clent); // LadyHavoc: for comparison purposes
        camera = PRVM_EDICT_NUM( client->clientcamera );
-       VectorAdd(camera->fields.server->origin, clent->fields.server->view_ofs, eye);
+       VectorAdd(PRVM_serveredictvector(camera, origin), PRVM_serveredictvector(clent, view_ofs), eye);
        sv.writeentitiestoclient_pvsbytes = 0;
        // get the PVS values for the eye location, later FatPVS calls will merge
        if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
@@ -1792,8 +2005,8 @@ void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *
        {
                vec_t predtime = bound(0, host_client->ping, sv_cullentities_trace_prediction_time.value);
                vec3_t predeye;
-               VectorMA(eye, predtime, camera->fields.server->velocity, predeye);
-               if (SV_CanSeeBox(1, 0, eye, predeye, predeye))
+               VectorMA(eye, predtime, PRVM_serveredictvector(camera, velocity), predeye);
+               if (SV_CanSeeBox(1, 0, 0, 0, eye, predeye, predeye))
                {
                        VectorCopy(predeye, sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes]);
                        sv.writeentitiestoclient_numeyes++;
@@ -1847,8 +2060,17 @@ void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *
        else
                EntityFrameCSQC_WriteFrame(msg, maxsize, numcsqcsendstates, sv.writeentitiestoclient_csqcsendstates, 0);
 
-       if(client->num_skippedentityframes >= 10)
-               need_empty = true; // force every 10th frame to be not empty (or cl_movement replay takes too long)
+       // force every 16th frame to be not empty (or cl_movement replay takes
+       // too long)
+       // BTW, this should normally not kick in any more due to the check
+       // below, except if the client stopped sending movement frames
+       if(client->num_skippedentityframes >= 16)
+               need_empty = true;
+
+       // help cl_movement a bit more
+       if(client->movesequence != client->lastmovesequence)
+               need_empty = true;
+       client->lastmovesequence = client->movesequence;
 
        if (client->entitydatabase5)
                success = EntityFrame5_WriteFrame(msg, maxsize, client->entitydatabase5, numsendstates, sv.writeentitiestoclient_sendstates, client - svs.clients + 1, client->movesequence, need_empty);
@@ -1882,12 +2104,13 @@ SV_CleanupEnts
 */
 static void SV_CleanupEnts (void)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int             e;
        prvm_edict_t    *ent;
 
        ent = PRVM_NEXT_EDICT(prog->edicts);
        for (e=1 ; e<prog->num_edicts ; e++, ent = PRVM_NEXT_EDICT(ent))
-               ent->fields.server->effects = (int)ent->fields.server->effects & ~EF_MUZZLEFLASH;
+               PRVM_serveredictfloat(ent, effects) = (int)PRVM_serveredictfloat(ent, effects) & ~EF_MUZZLEFLASH;
 }
 
 /*
@@ -1898,6 +2121,7 @@ SV_WriteClientdataToMessage
 */
 void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int             bits;
        int             i;
        prvm_edict_t    *other;
@@ -1911,17 +2135,17 @@ void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t
 //
 // send a damage message
 //
-       if (ent->fields.server->dmg_take || ent->fields.server->dmg_save)
+       if (PRVM_serveredictfloat(ent, dmg_take) || PRVM_serveredictfloat(ent, dmg_save))
        {
-               other = PRVM_PROG_TO_EDICT(ent->fields.server->dmg_inflictor);
+               other = PRVM_PROG_TO_EDICT(PRVM_serveredictedict(ent, dmg_inflictor));
                MSG_WriteByte (msg, svc_damage);
-               MSG_WriteByte (msg, (int)ent->fields.server->dmg_save);
-               MSG_WriteByte (msg, (int)ent->fields.server->dmg_take);
+               MSG_WriteByte (msg, (int)PRVM_serveredictfloat(ent, dmg_save));
+               MSG_WriteByte (msg, (int)PRVM_serveredictfloat(ent, dmg_take));
                for (i=0 ; i<3 ; i++)
-                       MSG_WriteCoord (msg, other->fields.server->origin[i] + 0.5*(other->fields.server->mins[i] + other->fields.server->maxs[i]), sv.protocol);
+                       MSG_WriteCoord (msg, PRVM_serveredictvector(other, origin)[i] + 0.5*(PRVM_serveredictvector(other, mins)[i] + PRVM_serveredictvector(other, maxs)[i]), sv.protocol);
 
-               ent->fields.server->dmg_take = 0;
-               ent->fields.server->dmg_save = 0;
+               PRVM_serveredictfloat(ent, dmg_take) = 0;
+               PRVM_serveredictfloat(ent, dmg_save) = 0;
        }
 
 //
@@ -1930,15 +2154,15 @@ void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t
        SV_SetIdealPitch ();            // how much to look up / down ideally
 
 // a fixangle might get lost in a dropped packet.  Oh well.
-       if(ent->fields.server->fixangle)
+       if(PRVM_serveredictfloat(ent, fixangle))
        {
                // angle fixing was requested by global thinking code...
                // so store the current angles for later use
-               memcpy(host_client->fixangle_angles, ent->fields.server->angles, sizeof(host_client->fixangle_angles));
-               host_client->fixangle_angles_set = TRUE;
+               VectorCopy(PRVM_serveredictvector(ent, angles), host_client->fixangle_angles);
+               host_client->fixangle_angles_set = true;
 
                // and clear fixangle for the next frame
-               ent->fields.server->fixangle = 0;
+               PRVM_serveredictfloat(ent, fixangle) = 0;
        }
 
        if (host_client->fixangle_angles_set)
@@ -1946,21 +2170,19 @@ void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t
                MSG_WriteByte (msg, svc_setangle);
                for (i=0 ; i < 3 ; i++)
                        MSG_WriteAngle (msg, host_client->fixangle_angles[i], sv.protocol);
-               host_client->fixangle_angles_set = FALSE;
+               host_client->fixangle_angles_set = false;
        }
 
-       // stuff the sigil bits into the high bits of items for sbar, or else
-       // mix in items2
-       if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE)
-               items = (int)ent->fields.server->items | ((int)PRVM_serveredictfloat(ent, items2) << 23);
-       else
-               items = (int)ent->fields.server->items | ((int)prog->globals.server->serverflags << 28);
+       // the runes are in serverflags, pack them into the items value, also pack
+       // in the items2 value for mission pack huds
+       // (used only in the mission packs, which do not use serverflags)
+       items = (int)PRVM_serveredictfloat(ent, items) | ((int)PRVM_serveredictfloat(ent, items2) << 23) | ((int)PRVM_serverglobalfloat(serverflags) << 28);
 
        VectorCopy(PRVM_serveredictvector(ent, punchvector), punchvector);
 
        // cache weapon model name and index in client struct to save time
        // (this search can be almost 1% of cpu time!)
-       s = PRVM_GetString(ent->fields.server->weaponmodel);
+       s = PRVM_GetString(prog, PRVM_serveredictstring(ent, weaponmodel));
        if (strcmp(s, client->weaponmodel))
        {
                strlcpy(client->weaponmodel, s, sizeof(client->weaponmodel));
@@ -1973,88 +2195,91 @@ void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t
 
        bits = 0;
 
-       if ((int)ent->fields.server->flags & FL_ONGROUND)
+       if ((int)PRVM_serveredictfloat(ent, flags) & FL_ONGROUND)
                bits |= SU_ONGROUND;
-       if (ent->fields.server->waterlevel >= 2)
+       if (PRVM_serveredictfloat(ent, waterlevel) >= 2)
                bits |= SU_INWATER;
-       if (ent->fields.server->idealpitch)
+       if (PRVM_serveredictfloat(ent, idealpitch))
                bits |= SU_IDEALPITCH;
 
        for (i=0 ; i<3 ; i++)
        {
-               if (ent->fields.server->punchangle[i])
+               if (PRVM_serveredictvector(ent, punchangle)[i])
                        bits |= (SU_PUNCH1<<i);
                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)
                        if (punchvector[i])
                                bits |= (SU_PUNCHVEC1<<i);
-               if (ent->fields.server->velocity[i])
+               if (PRVM_serveredictvector(ent, velocity)[i])
                        bits |= (SU_VELOCITY1<<i);
        }
 
        gravity = PRVM_serveredictfloat(ent, gravity);if (!gravity) gravity = 1.0f;
 
        memset(stats, 0, sizeof(int[MAX_CL_STATS]));
-       stats[STAT_VIEWHEIGHT] = (int)ent->fields.server->view_ofs[2];
+       stats[STAT_VIEWHEIGHT] = (int)PRVM_serveredictvector(ent, view_ofs)[2];
        stats[STAT_ITEMS] = items;
-       stats[STAT_WEAPONFRAME] = (int)ent->fields.server->weaponframe;
-       stats[STAT_ARMOR] = (int)ent->fields.server->armorvalue;
+       stats[STAT_WEAPONFRAME] = (int)PRVM_serveredictfloat(ent, weaponframe);
+       stats[STAT_ARMOR] = (int)PRVM_serveredictfloat(ent, armorvalue);
        stats[STAT_WEAPON] = client->weaponmodelindex;
-       stats[STAT_HEALTH] = (int)ent->fields.server->health;
-       stats[STAT_AMMO] = (int)ent->fields.server->currentammo;
-       stats[STAT_SHELLS] = (int)ent->fields.server->ammo_shells;
-       stats[STAT_NAILS] = (int)ent->fields.server->ammo_nails;
-       stats[STAT_ROCKETS] = (int)ent->fields.server->ammo_rockets;
-       stats[STAT_CELLS] = (int)ent->fields.server->ammo_cells;
-       stats[STAT_ACTIVEWEAPON] = (int)ent->fields.server->weapon;
+       stats[STAT_HEALTH] = (int)PRVM_serveredictfloat(ent, health);
+       stats[STAT_AMMO] = (int)PRVM_serveredictfloat(ent, currentammo);
+       stats[STAT_SHELLS] = (int)PRVM_serveredictfloat(ent, ammo_shells);
+       stats[STAT_NAILS] = (int)PRVM_serveredictfloat(ent, ammo_nails);
+       stats[STAT_ROCKETS] = (int)PRVM_serveredictfloat(ent, ammo_rockets);
+       stats[STAT_CELLS] = (int)PRVM_serveredictfloat(ent, ammo_cells);
+       stats[STAT_ACTIVEWEAPON] = (int)PRVM_serveredictfloat(ent, weapon);
        stats[STAT_VIEWZOOM] = viewzoom;
-       stats[STAT_TOTALSECRETS] = (int)prog->globals.server->total_secrets;
-       stats[STAT_TOTALMONSTERS] = (int)prog->globals.server->total_monsters;
+       stats[STAT_TOTALSECRETS] = (int)PRVM_serverglobalfloat(total_secrets);
+       stats[STAT_TOTALMONSTERS] = (int)PRVM_serverglobalfloat(total_monsters);
        // the QC bumps these itself by sending svc_'s, so we have to keep them
        // zero or they'll be corrected by the engine
-       //stats[STAT_SECRETS] = prog->globals.server->found_secrets;
-       //stats[STAT_MONSTERS] = prog->globals.server->killed_monsters;
-
-       // movement settings for prediction
-       // note: these are not sent in protocols with lower MAX_CL_STATS limits
-       stats[STAT_MOVEFLAGS] = MOVEFLAG_VALID
-               | (sv_gameplayfix_q2airaccelerate.integer ? MOVEFLAG_Q2AIRACCELERATE : 0)
-               | (sv_gameplayfix_nogravityonground.integer ? MOVEFLAG_NOGRAVITYONGROUND : 0)
-               | (sv_gameplayfix_gravityunaffectedbyticrate.integer ? MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE : 0)
-       ;
-       statsf[STAT_MOVEVARS_TICRATE] = sys_ticrate.value;
-       statsf[STAT_MOVEVARS_TIMESCALE] = slowmo.value;
-       statsf[STAT_MOVEVARS_GRAVITY] = sv_gravity.value;
-       statsf[STAT_MOVEVARS_STOPSPEED] = sv_stopspeed.value;
-       statsf[STAT_MOVEVARS_MAXSPEED] = sv_maxspeed.value;
-       statsf[STAT_MOVEVARS_SPECTATORMAXSPEED] = sv_maxspeed.value; // FIXME: QW has a separate cvar for this
-       statsf[STAT_MOVEVARS_ACCELERATE] = sv_accelerate.value;
-       statsf[STAT_MOVEVARS_AIRACCELERATE] = sv_airaccelerate.value >= 0 ? sv_airaccelerate.value : sv_accelerate.value;
-       statsf[STAT_MOVEVARS_WATERACCELERATE] = sv_wateraccelerate.value >= 0 ? sv_wateraccelerate.value : sv_accelerate.value;
-       statsf[STAT_MOVEVARS_ENTGRAVITY] = gravity;
-       statsf[STAT_MOVEVARS_JUMPVELOCITY] = sv_jumpvelocity.value;
-       statsf[STAT_MOVEVARS_EDGEFRICTION] = sv_edgefriction.value;
-       statsf[STAT_MOVEVARS_MAXAIRSPEED] = sv_maxairspeed.value;
-       statsf[STAT_MOVEVARS_STEPHEIGHT] = sv_stepheight.value;
-       statsf[STAT_MOVEVARS_AIRACCEL_QW] = sv_airaccel_qw.value;
-       statsf[STAT_MOVEVARS_AIRACCEL_QW_STRETCHFACTOR] = sv_airaccel_qw_stretchfactor.value;
-       statsf[STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION] = sv_airaccel_sideways_friction.value;
-       statsf[STAT_MOVEVARS_FRICTION] = sv_friction.value;
-       statsf[STAT_MOVEVARS_WATERFRICTION] = sv_waterfriction.value >= 0 ? sv_waterfriction.value : sv_friction.value;
-       statsf[STAT_MOVEVARS_AIRSTOPACCELERATE] = sv_airstopaccelerate.value;
-       statsf[STAT_MOVEVARS_AIRSTRAFEACCELERATE] = sv_airstrafeaccelerate.value;
-       statsf[STAT_MOVEVARS_MAXAIRSTRAFESPEED] = sv_maxairstrafespeed.value;
-       statsf[STAT_MOVEVARS_AIRSTRAFEACCEL_QW] = sv_airstrafeaccel_qw.value;
-       statsf[STAT_MOVEVARS_AIRCONTROL] = sv_aircontrol.value;
-       statsf[STAT_MOVEVARS_AIRCONTROL_POWER] = sv_aircontrol_power.value;
-       statsf[STAT_MOVEVARS_AIRCONTROL_PENALTY] = sv_aircontrol_penalty.value;
-       statsf[STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL] = sv_warsowbunny_airforwardaccel.value;
-       statsf[STAT_MOVEVARS_WARSOWBUNNY_ACCEL] = sv_warsowbunny_accel.value;
-       statsf[STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED] = sv_warsowbunny_topspeed.value;
-       statsf[STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL] = sv_warsowbunny_turnaccel.value;
-       statsf[STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO] = sv_warsowbunny_backtosideratio.value;
-       statsf[STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW] = sv_airspeedlimit_nonqw.value;
-       statsf[STAT_FRAGLIMIT] = fraglimit.value;
-       statsf[STAT_TIMELIMIT] = timelimit.value;
+       //stats[STAT_SECRETS] = PRVM_serverglobalfloat(found_secrets);
+       //stats[STAT_MONSTERS] = PRVM_serverglobalfloat(killed_monsters);
+
+       if(!sv_gameplayfix_customstats.integer)
+       {
+               statsf[STAT_MOVEVARS_AIRACCEL_QW_STRETCHFACTOR] = sv_airaccel_qw_stretchfactor.value;
+               statsf[STAT_MOVEVARS_AIRCONTROL_PENALTY] = sv_aircontrol_penalty.value;
+               statsf[STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW] = sv_airspeedlimit_nonqw.value;               
+               statsf[STAT_MOVEVARS_AIRSTRAFEACCEL_QW] = sv_airstrafeaccel_qw.value;
+               statsf[STAT_MOVEVARS_AIRCONTROL_POWER] = sv_aircontrol_power.value;
+               // movement settings for prediction
+               // note: these are not sent in protocols with lower MAX_CL_STATS limits
+               stats[STAT_MOVEFLAGS] = MOVEFLAG_VALID
+                       | (sv_gameplayfix_q2airaccelerate.integer ? MOVEFLAG_Q2AIRACCELERATE : 0)
+                       | (sv_gameplayfix_nogravityonground.integer ? MOVEFLAG_NOGRAVITYONGROUND : 0)
+                       | (sv_gameplayfix_gravityunaffectedbyticrate.integer ? MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE : 0)
+               ;
+               statsf[STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL] = sv_warsowbunny_airforwardaccel.value;
+               statsf[STAT_MOVEVARS_WARSOWBUNNY_ACCEL] = sv_warsowbunny_accel.value;
+               statsf[STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED] = sv_warsowbunny_topspeed.value;
+               statsf[STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL] = sv_warsowbunny_turnaccel.value;
+               statsf[STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO] = sv_warsowbunny_backtosideratio.value;
+               statsf[STAT_MOVEVARS_AIRSTOPACCELERATE] = sv_airstopaccelerate.value;
+               statsf[STAT_MOVEVARS_AIRSTRAFEACCELERATE] = sv_airstrafeaccelerate.value;
+               statsf[STAT_MOVEVARS_MAXAIRSTRAFESPEED] = sv_maxairstrafespeed.value;
+               statsf[STAT_MOVEVARS_AIRCONTROL] = sv_aircontrol.value;
+               statsf[STAT_FRAGLIMIT] = fraglimit.value;
+               statsf[STAT_TIMELIMIT] = timelimit.value;
+               statsf[STAT_MOVEVARS_FRICTION] = sv_friction.value;     
+               statsf[STAT_MOVEVARS_WATERFRICTION] = sv_waterfriction.value >= 0 ? sv_waterfriction.value : sv_friction.value;
+               statsf[STAT_MOVEVARS_TICRATE] = sys_ticrate.value;
+               statsf[STAT_MOVEVARS_TIMESCALE] = host_timescale.value;
+               statsf[STAT_MOVEVARS_GRAVITY] = sv_gravity.value;
+               statsf[STAT_MOVEVARS_STOPSPEED] = sv_stopspeed.value;
+               statsf[STAT_MOVEVARS_MAXSPEED] = sv_maxspeed.value;
+               statsf[STAT_MOVEVARS_SPECTATORMAXSPEED] = sv_maxspeed.value; // FIXME: QW has a separate cvar for this
+               statsf[STAT_MOVEVARS_ACCELERATE] = sv_accelerate.value;
+               statsf[STAT_MOVEVARS_AIRACCELERATE] = sv_airaccelerate.value >= 0 ? sv_airaccelerate.value : sv_accelerate.value;
+               statsf[STAT_MOVEVARS_WATERACCELERATE] = sv_wateraccelerate.value >= 0 ? sv_wateraccelerate.value : sv_accelerate.value;
+               statsf[STAT_MOVEVARS_ENTGRAVITY] = gravity;
+               statsf[STAT_MOVEVARS_JUMPVELOCITY] = sv_jumpvelocity.value;
+               statsf[STAT_MOVEVARS_EDGEFRICTION] = sv_edgefriction.value;
+               statsf[STAT_MOVEVARS_MAXAIRSPEED] = sv_maxairspeed.value;
+               statsf[STAT_MOVEVARS_STEPHEIGHT] = sv_stepheight.value;
+               statsf[STAT_MOVEVARS_AIRACCEL_QW] = sv_airaccel_qw.value;
+               statsf[STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION] = sv_airaccel_sideways_friction.value;
+       }
 
        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 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
        {
@@ -2086,16 +2311,16 @@ void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t
                MSG_WriteChar (msg, stats[STAT_VIEWHEIGHT]);
 
        if (bits & SU_IDEALPITCH)
-               MSG_WriteChar (msg, (int)ent->fields.server->idealpitch);
+               MSG_WriteChar (msg, (int)PRVM_serveredictfloat(ent, idealpitch));
 
        for (i=0 ; i<3 ; i++)
        {
                if (bits & (SU_PUNCH1<<i))
                {
                        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)
-                               MSG_WriteChar(msg, (int)ent->fields.server->punchangle[i]);
+                               MSG_WriteChar(msg, (int)PRVM_serveredictvector(ent, punchangle)[i]);
                        else
-                               MSG_WriteAngle16i(msg, ent->fields.server->punchangle[i]);
+                               MSG_WriteAngle16i(msg, PRVM_serveredictvector(ent, punchangle)[i]);
                }
                if (bits & (SU_PUNCHVEC1<<i))
                {
@@ -2107,9 +2332,9 @@ void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t
                if (bits & (SU_VELOCITY1<<i))
                {
                        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 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
-                               MSG_WriteChar(msg, (int)(ent->fields.server->velocity[i] * (1.0f / 16.0f)));
+                               MSG_WriteChar(msg, (int)(PRVM_serveredictvector(ent, velocity)[i] * (1.0f / 16.0f)));
                        else
-                               MSG_WriteCoord32f(msg, ent->fields.server->velocity[i]);
+                               MSG_WriteCoord32f(msg, PRVM_serveredictvector(ent, velocity)[i]);
                }
        }
 
@@ -2153,7 +2378,7 @@ void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t
                MSG_WriteByte (msg, stats[STAT_NAILS]);
                MSG_WriteByte (msg, stats[STAT_ROCKETS]);
                MSG_WriteByte (msg, stats[STAT_CELLS]);
-               if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
+               if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_QUOTH || IS_OLDNEXUIZ_DERIVED(gamemode))
                {
                        for (i = 0;i < 32;i++)
                                if (stats[STAT_ACTIVEWEAPON] & (1<<i))
@@ -2180,7 +2405,7 @@ void SV_FlushBroadcastMessages(void)
                return;
        for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
        {
-               if (!client->spawned || !client->netconnection || client->unreliablemsg.cursize + sv.datagram.cursize > client->unreliablemsg.maxsize || client->unreliablemsg_splitpoints >= (int)(sizeof(client->unreliablemsg_splitpoint)/sizeof(client->unreliablemsg_splitpoint[0])))
+               if (!client->begun || !client->netconnection || client->unreliablemsg.cursize + sv.datagram.cursize > client->unreliablemsg.maxsize || client->unreliablemsg_splitpoints >= (int)(sizeof(client->unreliablemsg_splitpoint)/sizeof(client->unreliablemsg_splitpoint[0])))
                        continue;
                SZ_Write(&client->unreliablemsg, sv.datagram.data, sv.datagram.cursize);
                client->unreliablemsg_splitpoint[client->unreliablemsg_splitpoints++] = client->unreliablemsg.cursize;
@@ -2232,6 +2457,7 @@ static void SV_SendClientDatagram (client_t *client)
        sizebuf_t msg;
        int stats[MAX_CL_STATS];
        static unsigned char sv_sendclientdatagram_buf[NET_MAXMESSAGE];
+       double timedelta;
 
        // obey rate limit by limiting packet frequency if the packet size
        // limiting fails
@@ -2279,13 +2505,31 @@ static void SV_SendClientDatagram (client_t *client)
                //
                // at very low rates (or very small sys_ticrate) the packet size is
                // not reduced below 128, but packets may be sent less often
-               maxsize = (int)(clientrate * sys_ticrate.value);
+
+               // how long are bursts?
+               timedelta = host_client->rate_burstsize / (double)client->rate;
+
+               // how much of the burst do we keep reserved?
+               timedelta *= 1 - net_burstreserve.value;
+
+               // only try to use excess time
+               timedelta = bound(0, host.realtime - host_client->netconnection->cleartime, timedelta);
+
+               // but we know next packet will be in sys_ticrate, so we can use up THAT bandwidth
+               timedelta += sys_ticrate.value;
+
+               // note: packet overhead (not counted in maxsize) is 28 bytes
+               maxsize = (int)(clientrate * timedelta) - 28;
+
+               // put it in sound bounds
                maxsize = bound(128, maxsize, 1400);
                maxsize2 = 1400;
+
                // csqc entities can easily exceed 128 bytes, so disable throttling in
                // mods that use csqc (they are likely to use less bandwidth anyway)
-               if (sv.csqc_progsize > 0)
+               if((net_usesizelimit.integer == 1) ? (sv.csqc_progsize > 0) : (net_usesizelimit.integer < 1))
                        maxsize = maxsize2;
+
                break;
        }
 
@@ -2308,7 +2552,7 @@ static void SV_SendClientDatagram (client_t *client)
        msg.cursize = 0;
        msg.allowoverflow = false;
 
-       if (host_client->spawned)
+       if (host_client->begun)
        {
                // the player is in the game
                MSG_WriteByte (&msg, svc_time);
@@ -2317,7 +2561,7 @@ static void SV_SendClientDatagram (client_t *client)
                // add the client specific data to the datagram
                SV_WriteClientdataToMessage (client, client->edict, &msg, stats);
                // now update the stats[] array using any registered custom fields
-               VM_SV_UpdateCustomStats (client, client->edict, &msg, stats);
+               VM_SV_UpdateCustomStats(client, client->edict, &msg, stats);
                // set host_client->statsdeltabits
                Protocol_UpdateClientStats (stats);
 
@@ -2329,12 +2573,12 @@ static void SV_SendClientDatagram (client_t *client)
                // now write as many entities as we can fit, and also sends stats
                SV_WriteEntitiesToClient (client, client->edict, &msg, maxsize);
        }
-       else if (realtime > client->keepalivetime)
+       else if (host.realtime > client->keepalivetime)
        {
                // the player isn't totally in the game yet
                // send small keepalive messages if too much time has passed
                // (may also be sending downloads)
-               client->keepalivetime = realtime + 5;
+               client->keepalivetime = host.realtime + 5;
                MSG_WriteChar (&msg, svc_nop);
        }
 
@@ -2368,7 +2612,7 @@ static void SV_SendClientDatagram (client_t *client)
        SV_WriteDemoMessage(client, &msg, false);
 
 // send the datagram
-       NetConn_SendUnreliableMessage (client->netconnection, &msg, sv.protocol, clientrate, client->sendsignon == 2);
+       NetConn_SendUnreliableMessage (client->netconnection, &msg, sv.protocol, clientrate, client->rate_burstsize, client->sendsignon == 2);
        if (client->sendsignon == 1 && !client->netconnection->message.cursize)
                client->sendsignon = 2; // prevent reliable until client sends prespawn (this is the keepalive phase)
 }
@@ -2380,6 +2624,7 @@ SV_UpdateToReliableMessages
 */
 static void SV_UpdateToReliableMessages (void)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int i, j;
        client_t *client;
        const char *name;
@@ -2394,15 +2639,17 @@ static void SV_UpdateToReliableMessages (void)
                host_client->edict = PRVM_EDICT_NUM(i+1);
 
                // DP_SV_CLIENTNAME
-               name = PRVM_GetString(host_client->edict->fields.server->netname);
+               name = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, netname));
                if (name == NULL)
                        name = "";
                // always point the string back at host_client->name to keep it safe
-               strlcpy (host_client->name, name, sizeof (host_client->name));
-               host_client->edict->fields.server->netname = PRVM_SetEngineString(host_client->name);
+               //strlcpy (host_client->name, name, sizeof (host_client->name));
+               if (name != host_client->name) // prevent buffer overlap SIGABRT on Mac OSX
+                       strlcpy (host_client->name, name, sizeof (host_client->name));
+               PRVM_serveredictstring(host_client->edict, netname) = PRVM_SetEngineString(prog, host_client->name);
                if (strcmp(host_client->old_name, host_client->name))
                {
-                       if (host_client->spawned)
+                       if (host_client->begun)
                                SV_BroadcastPrintf("%s ^7changed name to %s\n", host_client->old_name, host_client->name);
                        strlcpy(host_client->old_name, host_client->name, sizeof(host_client->old_name));
                        // send notification to all clients
@@ -2424,20 +2671,24 @@ static void SV_UpdateToReliableMessages (void)
                }
 
                // NEXUIZ_PLAYERMODEL
-               model = PRVM_GetString(PRVM_serveredictstring(host_client->edict, playermodel));
+               model = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, playermodel));
                if (model == NULL)
                        model = "";
                // always point the string back at host_client->name to keep it safe
-               strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
-               PRVM_serveredictstring(host_client->edict, playermodel) = PRVM_SetEngineString(host_client->playermodel);
+               //strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
+               if (model != host_client->playermodel) // prevent buffer overlap SIGABRT on Mac OSX
+                       strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
+               PRVM_serveredictstring(host_client->edict, playermodel) = PRVM_SetEngineString(prog, host_client->playermodel);
 
                // NEXUIZ_PLAYERSKIN
-               skin = PRVM_GetString(PRVM_serveredictstring(host_client->edict, playerskin));
+               skin = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, playerskin));
                if (skin == NULL)
                        skin = "";
                // always point the string back at host_client->name to keep it safe
-               strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
-               PRVM_serveredictstring(host_client->edict, playerskin) = PRVM_SetEngineString(host_client->playerskin);
+               //strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
+               if (skin != host_client->playerskin) // prevent buffer overlap SIGABRT on Mac OSX
+                       strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
+               PRVM_serveredictstring(host_client->edict, playerskin) = PRVM_SetEngineString(prog, host_client->playerskin);
 
                // TODO: add an extension name for this [1/17/2008 Black]
                clientcamera = PRVM_serveredictedict(host_client->edict, clientcamera);
@@ -2448,7 +2699,7 @@ static void SV_UpdateToReliableMessages (void)
                                clientcamera = PRVM_NUM_FOR_EDICT(host_client->edict);
                        host_client->clientcamera = clientcamera;
 
-                       if (oldclientcamera != host_client->clientcamera)
+                       if (oldclientcamera != host_client->clientcamera && host_client->netconnection)
                        {
                                MSG_WriteByte(&host_client->netconnection->message, svc_setview);
                                MSG_WriteShort(&host_client->netconnection->message, host_client->clientcamera);
@@ -2456,9 +2707,9 @@ static void SV_UpdateToReliableMessages (void)
                }
 
                // frags
-               host_client->frags = (int)host_client->edict->fields.server->frags;
-               if(gamemode == GAME_NEXUIZ || gamemode == GAME_XONOTIC)
-                       if(!host_client->spawned && host_client->netconnection)
+               host_client->frags = (int)PRVM_serveredictfloat(host_client->edict, frags);
+               if(IS_OLDNEXUIZ_DERIVED(gamemode))
+                       if(!host_client->begun && host_client->netconnection)
                                host_client->frags = -666;
                if (host_client->old_frags != host_client->frags)
                {
@@ -2471,7 +2722,7 @@ static void SV_UpdateToReliableMessages (void)
        }
 
        for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
-               if (client->netconnection && (client->spawned || client->clientconnectcalled)) // also send MSG_ALL to people who are past ClientConnect, but not spawned yet
+               if (client->netconnection && (client->begun || client->clientconnectcalled)) // also send MSG_ALL to people who are past ClientConnect, but not spawned yet
                        SZ_Write (&client->netconnection->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
 
        SZ_Clear (&sv.reliable_datagram);
@@ -2483,7 +2734,7 @@ static void SV_UpdateToReliableMessages (void)
 SV_SendClientMessages
 =======================
 */
-void SV_SendClientMessages (void)
+void SV_SendClientMessages(void)
 {
        int i, prepared = false;
 
@@ -2515,14 +2766,14 @@ void SV_SendClientMessages (void)
                        // only prepare entities once per frame
                        SV_PrepareEntitiesForSending();
                }
-               SV_SendClientDatagram (host_client);
+               SV_SendClientDatagram(host_client);
        }
 
 // clear muzzle flashes
        SV_CleanupEnts();
 }
 
-static void SV_StartDownload_f(void)
+static void SV_StartDownload_f(cmd_state_t *cmd)
 {
        if (host_client->download_file)
                host_client->download_started = true;
@@ -2553,17 +2804,17 @@ static void SV_StartDownload_f(void)
  *       assume this extension is not supported!
  */
 
-static void Download_CheckExtensions(void)
+static void Download_CheckExtensions(cmd_state_t *cmd)
 {
        int i;
-       int argc = Cmd_Argc();
+       int argc = Cmd_Argc(cmd);
 
        // first reset them all
        host_client->download_deflate = false;
        
        for(i = 2; i < argc; ++i)
        {
-               if(!strcmp(Cmd_Argv(i), "deflate"))
+               if(!strcmp(Cmd_Argv(cmd, i), "deflate"))
                {
                        host_client->download_deflate = true;
                        break;
@@ -2571,21 +2822,21 @@ static void Download_CheckExtensions(void)
        }
 }
 
-static void SV_Download_f(void)
+static void SV_Download_f(cmd_state_t *cmd)
 {
        const char *whichpack, *whichpack2, *extension;
        qboolean is_csqc; // so we need to check only once
 
-       if (Cmd_Argc() < 2)
+       if (Cmd_Argc(cmd) < 2)
        {
                SV_ClientPrintf("usage: download <filename> {<extensions>}*\n");
                SV_ClientPrintf("       supported extensions: deflate\n");
                return;
        }
 
-       if (FS_CheckNastyPath(Cmd_Argv(1), false))
+       if (FS_CheckNastyPath(Cmd_Argv(cmd, 1), false))
        {
-               SV_ClientPrintf("Download rejected: nasty filename \"%s\"\n", Cmd_Argv(1));
+               SV_ClientPrintf("Download rejected: nasty filename \"%s\"\n", Cmd_Argv(cmd, 1));
                return;
        }
 
@@ -2593,7 +2844,7 @@ static void SV_Download_f(void)
        {
                // at this point we'll assume the previous download should be aborted
                Con_DPrintf("Download of %s aborted by %s starting a new download\n", host_client->download_name, host_client->name);
-               Host_ClientCommands("\nstopdownload\n");
+               SV_ClientCommands("\nstopdownload\n");
 
                // close the file and reset variables
                FS_Close(host_client->download_file);
@@ -2603,18 +2854,18 @@ static void SV_Download_f(void)
                host_client->download_started = false;
        }
 
-       is_csqc = (sv.csqc_progname[0] && strcmp(Cmd_Argv(1), sv.csqc_progname) == 0);
+       is_csqc = (sv.csqc_progname[0] && strcmp(Cmd_Argv(cmd, 1), sv.csqc_progname) == 0);
        
        if (!sv_allowdownloads.integer && !is_csqc)
        {
                SV_ClientPrintf("Downloads are disabled on this server\n");
-               Host_ClientCommands("\nstopdownload\n");
+               SV_ClientCommands("\nstopdownload\n");
                return;
        }
 
-       Download_CheckExtensions();
+       Download_CheckExtensions(cmd);
 
-       strlcpy(host_client->download_name, Cmd_Argv(1), sizeof(host_client->download_name));
+       strlcpy(host_client->download_name, Cmd_Argv(cmd, 1), sizeof(host_client->download_name));
        extension = FS_FileExtension(host_client->download_name);
 
        // host_client is asking to download a specified file
@@ -2637,7 +2888,7 @@ static void SV_Download_f(void)
                        host_client->download_file = FS_FileFromData(svs.csqc_progdata, sv.csqc_progsize, true);
                
                // no, no space is needed between %s and %s :P
-               Host_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
+               SV_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
 
                host_client->download_expectedposition = 0;
                host_client->download_started = false;
@@ -2648,7 +2899,7 @@ static void SV_Download_f(void)
        if (!FS_FileExists(host_client->download_name))
        {
                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);
-               Host_ClientCommands("\nstopdownload\n");
+               SV_ClientCommands("\nstopdownload\n");
                return;
        }
 
@@ -2658,7 +2909,7 @@ static void SV_Download_f(void)
        if ((whichpack && whichpack2 && !strcasecmp(whichpack, whichpack2)) || FS_IsRegisteredQuakePack(host_client->download_name))
        {
                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);
-               Host_ClientCommands("\nstopdownload\n");
+               SV_ClientCommands("\nstopdownload\n");
                return;
        }
 
@@ -2669,7 +2920,7 @@ static void SV_Download_f(void)
                if (whichpack)
                {
                        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);
-                       Host_ClientCommands("\nstopdownload\n");
+                       SV_ClientCommands("\nstopdownload\n");
                        return;
                }
        }
@@ -2679,7 +2930,7 @@ static void SV_Download_f(void)
                if (!strcasecmp(extension, "cfg"))
                {
                        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);
-                       Host_ClientCommands("\nstopdownload\n");
+                       SV_ClientCommands("\nstopdownload\n");
                        return;
                }
        }
@@ -2689,7 +2940,7 @@ static void SV_Download_f(void)
                if (!strncasecmp(host_client->download_name, "dlcache/", 8))
                {
                        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);
-                       Host_ClientCommands("\nstopdownload\n");
+                       SV_ClientCommands("\nstopdownload\n");
                        return;
                }
        }
@@ -2699,7 +2950,7 @@ static void SV_Download_f(void)
                if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3"))
                {
                        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);
-                       Host_ClientCommands("\nstopdownload\n");
+                       SV_ClientCommands("\nstopdownload\n");
                        return;
                }
        }
@@ -2708,14 +2959,14 @@ static void SV_Download_f(void)
        if (!host_client->download_file)
        {
                SV_ClientPrintf("Download rejected: server could not open the file \"%s\"\n", host_client->download_name);
-               Host_ClientCommands("\nstopdownload\n");
+               SV_ClientCommands("\nstopdownload\n");
                return;
        }
 
        if (FS_FileSize(host_client->download_file) > 1<<30)
        {
                SV_ClientPrintf("Download rejected: file \"%s\" is very large\n", host_client->download_name);
-               Host_ClientCommands("\nstopdownload\n");
+               SV_ClientCommands("\nstopdownload\n");
                FS_Close(host_client->download_file);
                host_client->download_file = NULL;
                return;
@@ -2724,7 +2975,7 @@ static void SV_Download_f(void)
        if (FS_FileSize(host_client->download_file) < 0)
        {
                SV_ClientPrintf("Download rejected: file \"%s\" is not a regular file\n", host_client->download_name);
-               Host_ClientCommands("\nstopdownload\n");
+               SV_ClientCommands("\nstopdownload\n");
                FS_Close(host_client->download_file);
                host_client->download_file = NULL;
                return;
@@ -2743,10 +2994,10 @@ static void SV_Download_f(void)
                        strlcat(extensions, " deflate", sizeof(extensions));
 
                // no, no space is needed between %s and %s :P
-               Host_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
+               SV_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
        }
        */
-       Host_ClientCommands("\ncl_downloadbegin %i %s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name);
+       SV_ClientCommands("\ncl_downloadbegin %i %s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name);
 
        host_client->download_expectedposition = 0;
        host_client->download_started = false;
@@ -2797,9 +3048,23 @@ int SV_ModelIndex(const char *s, int precachemode)
                                if (precachemode == 1)
                                        Con_Printf("SV_ModelIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
                                strlcpy(sv.model_precache[i], filename, sizeof(sv.model_precache[i]));
-                               sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
-                               if (sv.state != ss_loading)
+                               if (sv.state == ss_loading)
                                {
+                                       // running from SV_SpawnServer which is launched from the client console command interpreter
+                                       sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
+                               }
+                               else
+                               {
+                                       if (svs.threaded)
+                                       {
+                                               // 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
+                                               sv.models[i] = Mod_FindName (sv.model_precache[i], s[0] == '*' ? sv.worldname : NULL);
+                                       }
+                                       else
+                                       {
+                                               // running single threaded, so we can load the model here
+                                               sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
+                                       }
                                        MSG_WriteByte(&sv.reliable_datagram, svc_precache);
                                        MSG_WriteShort(&sv.reliable_datagram, i);
                                        MSG_WriteString(&sv.reliable_datagram, filename);
@@ -2906,7 +3171,7 @@ int SV_ParticleEffectIndex(const char *name)
                                argc = 0;
                                for (;;)
                                {
-                                       if (!COM_ParseToken_Simple(&text, true, false) || !strcmp(com_token, "\n"))
+                                       if (!COM_ParseToken_Simple(&text, true, false, true) || !strcmp(com_token, "\n"))
                                                break;
                                        if (argc < 16)
                                        {
@@ -2922,7 +3187,7 @@ int SV_ParticleEffectIndex(const char *name)
                                {
                                        if (argc == 2)
                                        {
-                                               for (effectnameindex = 1;effectnameindex < SV_MAX_PARTICLEEFFECTNAME;effectnameindex++)
+                                               for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME;effectnameindex++)
                                                {
                                                        if (sv.particleeffectname[effectnameindex][0])
                                                        {
@@ -2936,7 +3201,7 @@ int SV_ParticleEffectIndex(const char *name)
                                                        }
                                                }
                                                // if we run out of names, abort
-                                               if (effectnameindex == SV_MAX_PARTICLEEFFECTNAME)
+                                               if (effectnameindex == MAX_PARTICLEEFFECTNAME)
                                                {
                                                        Con_Printf("%s:%i: too many effects!\n", filename, linenumber);
                                                        break;
@@ -2948,7 +3213,7 @@ int SV_ParticleEffectIndex(const char *name)
                }
        }
        // search for the name
-       for (effectnameindex = 1;effectnameindex < SV_MAX_PARTICLEEFFECTNAME && sv.particleeffectname[effectnameindex][0];effectnameindex++)
+       for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME && sv.particleeffectname[effectnameindex][0];effectnameindex++)
                if (!strcmp(sv.particleeffectname[effectnameindex], name))
                        return effectnameindex;
        // return 0 if we couldn't find it
@@ -2962,10 +3227,11 @@ dp_model_t *SV_GetModelByIndex(int modelindex)
 
 dp_model_t *SV_GetModelFromEdict(prvm_edict_t *ed)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int modelindex;
        if (!ed || ed->priv.server->free)
                return NULL;
-       modelindex = (int)ed->fields.server->modelindex;
+       modelindex = (int)PRVM_serveredictfloat(ed, modelindex);
        return (modelindex > 0 && modelindex < MAX_MODELS) ? sv.models[modelindex] : NULL;
 }
 
@@ -2977,28 +3243,29 @@ SV_CreateBaseline
 */
 static void SV_CreateBaseline (void)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int i, entnum, large;
        prvm_edict_t *svent;
 
-       // LordHavoc: clear *all* states (note just active ones)
+       // LadyHavoc: clear *all* baselines (not just active ones)
        for (entnum = 0;entnum < prog->max_edicts;entnum++)
        {
                // get the current server version
                svent = PRVM_EDICT_NUM(entnum);
 
-               // LordHavoc: always clear state values, whether the entity is in use or not
+               // LadyHavoc: always clear state values, whether the entity is in use or not
                svent->priv.server->baseline = defaultstate;
 
                if (svent->priv.server->free)
                        continue;
-               if (entnum > svs.maxclients && !svent->fields.server->modelindex)
+               if (entnum > svs.maxclients && !PRVM_serveredictfloat(svent, modelindex))
                        continue;
 
                // create entity baseline
-               VectorCopy (svent->fields.server->origin, svent->priv.server->baseline.origin);
-               VectorCopy (svent->fields.server->angles, svent->priv.server->baseline.angles);
-               svent->priv.server->baseline.frame = (int)svent->fields.server->frame;
-               svent->priv.server->baseline.skin = (int)svent->fields.server->skin;
+               VectorCopy (PRVM_serveredictvector(svent, origin), svent->priv.server->baseline.origin);
+               VectorCopy (PRVM_serveredictvector(svent, angles), svent->priv.server->baseline.angles);
+               svent->priv.server->baseline.frame = (int)PRVM_serveredictfloat(svent, frame);
+               svent->priv.server->baseline.skin = (int)PRVM_serveredictfloat(svent, skin);
                if (entnum > 0 && entnum <= svs.maxclients)
                {
                        svent->priv.server->baseline.colormap = entnum;
@@ -3007,7 +3274,7 @@ static void SV_CreateBaseline (void)
                else
                {
                        svent->priv.server->baseline.colormap = 0;
-                       svent->priv.server->baseline.modelindex = (int)svent->fields.server->modelindex;
+                       svent->priv.server->baseline.modelindex = (int)PRVM_serveredictfloat(svent, modelindex);
                }
 
                large = false;
@@ -3058,7 +3325,7 @@ Load csprogs.dat and comperss it so it doesn't need to be
 reloaded on request.
 ================
 */
-void SV_Prepare_CSQC(void)
+static void SV_Prepare_CSQC(void)
 {
        fs_offset_t progsize;
 
@@ -3109,9 +3376,10 @@ transition to another level
 */
 void SV_SaveSpawnparms (void)
 {
+       prvm_prog_t *prog = SVVM_prog;
        int             i, j;
 
-       svs.serverflags = (int)prog->globals.server->serverflags;
+       svs.serverflags = (int)PRVM_serverglobalfloat(serverflags);
 
        for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
        {
@@ -3119,10 +3387,11 @@ void SV_SaveSpawnparms (void)
                        continue;
 
        // call the progs to get default spawn parms for the new client
-               prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
-               PRVM_ExecuteProgram (prog->globals.server->SetChangeParms, "QC function SetChangeParms is missing");
+               PRVM_serverglobalfloat(time) = sv.time;
+               PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
+               prog->ExecuteProgram(prog, PRVM_serverfunction(SetChangeParms), "QC function SetChangeParms is missing");
                for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
-                       host_client->spawn_parms[j] = (&prog->globals.server->parm1)[j];
+                       host_client->spawn_parms[j] = (&PRVM_serverglobalfloat(parm1))[j];
        }
 }
 
@@ -3136,11 +3405,13 @@ This is called at the start of each level
 
 void SV_SpawnServer (const char *server)
 {
+       prvm_prog_t *prog = SVVM_prog;
        prvm_edict_t *ent;
        int i;
        char *entities;
        dp_model_t *worldmodel;
        char modelname[sizeof(sv.worldname)];
+       char vabuf[1024];
 
        Con_DPrintf("SpawnServer: %s\n", server);
 
@@ -3156,23 +3427,36 @@ void SV_SpawnServer (const char *server)
                }
        }
 
+//     SV_LockThreadMutex();
+
+       if(cls.state == ca_dedicated)
+               Sys_MakeProcessNice();
+
        if (cls.state != ca_dedicated)
        {
-               SCR_BeginLoadingPlaque();
+               SCR_BeginLoadingPlaque(false);
                S_StopAllSounds();
        }
 
        if(sv.active)
        {
-               SV_VM_Begin();
+               client_t *client;
+               for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
+               {
+                       if (client->netconnection)
+                       {
+                               MSG_WriteByte(&client->netconnection->message, svc_stufftext);
+                               MSG_WriteString(&client->netconnection->message, "reconnect\n");
+                       }
+               }
                World_End(&sv.world);
                if(PRVM_serverfunction(SV_Shutdown))
                {
                        func_t s = PRVM_serverfunction(SV_Shutdown);
+                       PRVM_serverglobalfloat(time) = sv.time;
                        PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
-                       PRVM_ExecuteProgram(s,"SV_Shutdown() required");
+                       prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
                }
-               SV_VM_End();
        }
 
        // free q3 shaders so that any newly downloaded shaders will be active
@@ -3182,6 +3466,12 @@ void SV_SpawnServer (const char *server)
        if (!worldmodel || !worldmodel->TraceBox)
        {
                Con_Printf("Couldn't load map %s\n", modelname);
+
+               if(cls.state == ca_dedicated)
+                       Sys_MakeProcessMean();
+
+//             SV_UnlockThreadMutex();
+
                return;
        }
 
@@ -3189,7 +3479,7 @@ void SV_SpawnServer (const char *server)
 
        // let's not have any servers with no name
        if (hostname.string[0] == 0)
-               Cvar_Set ("hostname", "UNNAMED");
+               Cvar_SetQuick(&hostname, "UNNAMED");
        scr_centertime_off = 0;
 
        svs.changelevel_issued = false;         // now safe to issue another
@@ -3201,30 +3491,15 @@ void SV_SpawnServer (const char *server)
 //
 // tell all connected clients that we are going to a new level
 //
-       if (sv.active)
-       {
-               client_t *client;
-               for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
-               {
-                       if (client->netconnection)
-                       {
-                               MSG_WriteByte(&client->netconnection->message, svc_stufftext);
-                               MSG_WriteString(&client->netconnection->message, "reconnect\n");
-                       }
-               }
-       }
-       else
-       {
-               // open server port
+       if (!sv.active)
                NetConn_OpenServerPorts(true);
-       }
 
 //
 // make cvars consistant
 //
        if (coop.integer)
-               Cvar_SetValue ("deathmatch", 0);
-       // LordHavoc: it can be useful to have skills outside the range 0-3...
+               Cvar_SetValueQuick(&deathmatch, 0);
+       // LadyHavoc: it can be useful to have skills outside the range 0-3...
        //current_skill = bound(0, (int)(skill.value + 0.5), 3);
        //Cvar_SetValue ("skill", (float)current_skill);
        current_skill = (int)(skill.value + 0.5);
@@ -3237,7 +3512,9 @@ void SV_SpawnServer (const char *server)
        // level's data which is no longer valiud
        cls.signon = 0;
 
-       Cvar_SetValue("halflifebsp", worldmodel->brush.ishlbsp);
+       Cvar_SetValueQuick(&halflifebsp, worldmodel->brush.ishlbsp);
+       Cvar_SetValueQuick(&sv_mapformat_is_quake2, worldmodel->brush.isq2bsp);
+       Cvar_SetValueQuick(&sv_mapformat_is_quake3, worldmodel->brush.isq3bsp);
 
        if(*sv_random_seed.string)
        {
@@ -3268,8 +3545,6 @@ void SV_SpawnServer (const char *server)
                sv.protocol = PROTOCOL_QUAKE;
        }
 
-       SV_VM_Begin();
-
 // load progs to get entity field count
        //PR_LoadProgs ( sv_progs.string );
 
@@ -3292,7 +3567,7 @@ void SV_SpawnServer (const char *server)
        prog->allowworldwrites = true;
        sv.paused = false;
 
-       prog->globals.server->time = sv.time = 1.0;
+       sv.time = 1.0;
 
        Mod_ClearUsed();
        worldmodel->used = true;
@@ -3303,7 +3578,7 @@ void SV_SpawnServer (const char *server)
 //
 // clear world interaction links
 //
-       World_SetSize(&sv.world, sv.worldname, sv.worldmodel->normalmins, sv.worldmodel->normalmaxs);
+       World_SetSize(&sv.world, sv.worldname, sv.worldmodel->normalmins, sv.worldmodel->normalmaxs, prog);
        World_Start(&sv.world);
 
        strlcpy(sv.sound_precache[0], "", sizeof(sv.sound_precache[0]));
@@ -3323,26 +3598,26 @@ void SV_SpawnServer (const char *server)
 //
        // AK possible hack since num_edicts is still 0
        ent = PRVM_EDICT_NUM(0);
-       memset (ent->fields.server, 0, prog->entityfields * 4);
+       memset (ent->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
        ent->priv.server->free = false;
-       ent->fields.server->model = PRVM_SetEngineString(sv.worldname);
-       ent->fields.server->modelindex = 1;             // world model
-       ent->fields.server->solid = SOLID_BSP;
-       ent->fields.server->movetype = MOVETYPE_PUSH;
-       VectorCopy(sv.world.mins, ent->fields.server->mins);
-       VectorCopy(sv.world.maxs, ent->fields.server->maxs);
-       VectorCopy(sv.world.mins, ent->fields.server->absmin);
-       VectorCopy(sv.world.maxs, ent->fields.server->absmax);
+       PRVM_serveredictstring(ent, model) = PRVM_SetEngineString(prog, sv.worldname);
+       PRVM_serveredictfloat(ent, modelindex) = 1;             // world model
+       PRVM_serveredictfloat(ent, solid) = SOLID_BSP;
+       PRVM_serveredictfloat(ent, movetype) = MOVETYPE_PUSH;
+       VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, mins));
+       VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, maxs));
+       VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, absmin));
+       VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, absmax));
 
        if (coop.value)
-               prog->globals.server->coop = coop.integer;
+               PRVM_serverglobalfloat(coop) = coop.integer;
        else
-               prog->globals.server->deathmatch = deathmatch.integer;
+               PRVM_serverglobalfloat(deathmatch) = deathmatch.integer;
 
-       prog->globals.server->mapname = PRVM_SetEngineString(sv.name);
+       PRVM_serverglobalstring(mapname) = PRVM_SetEngineString(prog, sv.name);
 
 // serverflags are for cross level information (sigils)
-       prog->globals.server->serverflags = svs.serverflags;
+       PRVM_serverglobalfloat(serverflags) = svs.serverflags;
 
        // we need to reset the spawned flag on all connected clients here so that
        // their thinks don't run during startup (before PutClientInServer)
@@ -3350,37 +3625,40 @@ void SV_SpawnServer (const char *server)
        // and we need to set the ->edict pointers to point into the progs edicts
        for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
        {
-               host_client->spawned = false;
+               host_client->begun = false;
                host_client->edict = PRVM_EDICT_NUM(i + 1);
-               PRVM_ED_ClearEdict(host_client->edict);
+               PRVM_ED_ClearEdict(prog, host_client->edict);
        }
 
        // load replacement entity file if found
-       if (sv_entpatch.integer && (entities = (char *)FS_LoadFile(va("%s.ent", sv.worldnamenoextension), tempmempool, true, NULL)))
+       if (sv_entpatch.integer && (entities = (char *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), tempmempool, true, NULL)))
        {
                Con_Printf("Loaded %s.ent\n", sv.worldnamenoextension);
-               PRVM_ED_LoadFromFile (entities);
+               PRVM_ED_LoadFromFile(prog, entities);
                Mem_Free(entities);
        }
        else
-               PRVM_ED_LoadFromFile (sv.worldmodel->brush.entities);
+               PRVM_ED_LoadFromFile(prog, sv.worldmodel->brush.entities);
 
 
-       // LordHavoc: clear world angles (to fix e3m3.bsp)
-       VectorClear(prog->edicts->fields.server->angles);
+       // LadyHavoc: clear world angles (to fix e3m3.bsp)
+       VectorClear(PRVM_serveredictvector(prog->edicts, angles));
 
 // all setup is completed, any further precache statements are errors
-//     sv.state = ss_active; // LordHavoc: workaround for svc_precache bug
+//     sv.state = ss_active; // LadyHavoc: workaround for svc_precache bug
        prog->allowworldwrites = false;
 
 // run two frames to allow everything to settle
-       prog->globals.server->time = sv.time = 1.0001;
-       for (i = 0;i < 2;i++)
+       sv.time = 1.0001;
+       for (i = 0;i < sv_init_frame_count.integer;i++)
        {
                sv.frametime = 0.1;
                SV_Physics ();
        }
 
+       // Once all init frames have been run, we consider svqc code fully initialized.
+       prog->inittime = host.realtime;
+
        if (cls.state == ca_dedicated)
                Mod_PurgeUnused();
 
@@ -3388,11 +3666,8 @@ void SV_SpawnServer (const char *server)
        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)
                SV_CreateBaseline ();
 
-       sv.state = ss_active; // LordHavoc: workaround for svc_precache bug
+       sv.state = ss_active; // LadyHavoc: workaround for svc_precache bug
 
-       // to prevent network timeouts
-       realtime = Sys_DoubleTime();
-       
 // send serverinfo to all connected clients, and set up botclients coming back from a level change
        for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
        {
@@ -3409,51 +3684,102 @@ void SV_SpawnServer (const char *server)
 
                        // copy spawn parms out of the client_t
                        for (j=0 ; j< NUM_SPAWN_PARMS ; j++)
-                               (&prog->globals.server->parm1)[j] = host_client->spawn_parms[j];
+                               (&PRVM_serverglobalfloat(parm1))[j] = host_client->spawn_parms[j];
 
                        // call the spawn function
                        host_client->clientconnectcalled = true;
-                       prog->globals.server->time = sv.time;
-                       prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
-                       PRVM_ExecuteProgram (prog->globals.server->ClientConnect, "QC function ClientConnect is missing");
-                       PRVM_ExecuteProgram (prog->globals.server->PutClientInServer, "QC function PutClientInServer is missing");
-                       host_client->spawned = true;
+                       PRVM_serverglobalfloat(time) = sv.time;
+                       PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
+                       prog->ExecuteProgram(prog, PRVM_serverfunction(ClientConnect), "QC function ClientConnect is missing");
+                       prog->ExecuteProgram(prog, PRVM_serverfunction(PutClientInServer), "QC function PutClientInServer is missing");
+                       host_client->begun = true;
                }
        }
 
        // update the map title cvar
-       strlcpy(sv.worldmessage, PRVM_GetString(prog->edicts->fields.server->message), sizeof(sv.worldmessage)); // map title (not related to filename)
+       strlcpy(sv.worldmessage, PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)), sizeof(sv.worldmessage)); // map title (not related to filename)
        Cvar_SetQuick(&sv_worldmessage, sv.worldmessage);
 
        Con_DPrint("Server spawned.\n");
        NetConn_Heartbeat (2);
 
-       SV_VM_End();
+       if(cls.state == ca_dedicated)
+               Sys_MakeProcessMean();
+
+//     SV_UnlockThreadMutex();
+}
+
+/*
+==================
+SV_Shutdown
+
+This only happens at the end of a game, not between levels
+==================
+*/
+void SV_Shutdown(void)
+{
+       prvm_prog_t *prog = SVVM_prog;
+       int i;
+
+       Con_DPrintf("SV_Shutdown\n");
+
+       if (!sv.active)
+               return;
+
+       NetConn_Heartbeat(2);
+       NetConn_Heartbeat(2);
+
+// make sure all the clients know we're disconnecting
+       World_End(&sv.world);
+       if(prog->loaded)
+       {
+               if(PRVM_serverfunction(SV_Shutdown))
+               {
+                       func_t s = PRVM_serverfunction(SV_Shutdown);
+                       PRVM_serverglobalfloat(time) = sv.time;
+                       PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
+                       prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
+               }
+       }
+       for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
+               if (host_client->active)
+                       SV_DropClient(false); // server shutdown
+
+       NetConn_CloseServerPorts();
+
+       sv.active = false;
+//
+// clear structures
+//
+       memset(&sv, 0, sizeof(sv));
+       memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
+
+       cl.islocalgame = false;
 }
 
 /////////////////////////////////////////////////////
 // SV VM stuff
 
-static void SV_VM_CB_BeginIncreaseEdicts(void)
+static void SVVM_begin_increase_edicts(prvm_prog_t *prog)
 {
        // links don't survive the transition, so unlink everything
        World_UnlinkAll(&sv.world);
 }
 
-static void SV_VM_CB_EndIncreaseEdicts(void)
+static void SVVM_end_increase_edicts(prvm_prog_t *prog)
 {
        int i;
        prvm_edict_t *ent;
 
        // link every entity except world
        for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
-               if (!ent->priv.server->free)
+               if (!ent->priv.server->free && !VectorCompare(PRVM_serveredictvector(ent, absmin), PRVM_serveredictvector(ent, absmax)))
                        SV_LinkEdict(ent);
 }
 
-static void SV_VM_CB_InitEdict(prvm_edict_t *e)
+static void SVVM_init_edict(prvm_prog_t *prog, prvm_edict_t *e)
 {
-       // LordHavoc: for consistency set these here
+       // LadyHavoc: for consistency set these here
        int num = PRVM_NUM_FOR_EDICT(e) - 1;
 
        e->priv.server->move = false; // don't move on first frame
@@ -3461,67 +3787,68 @@ static void SV_VM_CB_InitEdict(prvm_edict_t *e)
        if (num >= 0 && num < svs.maxclients)
        {
                // set colormap and team on newly created player entity
-               e->fields.server->colormap = num + 1;
-               e->fields.server->team = (svs.clients[num].colors & 15) + 1;
+               PRVM_serveredictfloat(e, colormap) = num + 1;
+               PRVM_serveredictfloat(e, team) = (svs.clients[num].colors & 15) + 1;
                // set netname/clientcolors back to client values so that
                // DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS will not immediately
                // reset them
-               e->fields.server->netname = PRVM_SetEngineString(svs.clients[num].name);
+               PRVM_serveredictstring(e, netname) = PRVM_SetEngineString(prog, svs.clients[num].name);
                PRVM_serveredictfloat(e, clientcolors) = svs.clients[num].colors;
                // NEXUIZ_PLAYERMODEL and NEXUIZ_PLAYERSKIN
-               PRVM_serveredictstring(e, playermodel) = PRVM_SetEngineString(svs.clients[num].playermodel);
-               PRVM_serveredictstring(e, playerskin) = PRVM_SetEngineString(svs.clients[num].playerskin);
+               PRVM_serveredictstring(e, playermodel) = PRVM_SetEngineString(prog, svs.clients[num].playermodel);
+               PRVM_serveredictstring(e, playerskin) = PRVM_SetEngineString(prog, svs.clients[num].playerskin);
                // Assign netaddress (IP Address, etc)
                if(svs.clients[num].netconnection != NULL)
                {
                        // Acquire Readable Address
                        LHNETADDRESS_ToString(&svs.clients[num].netconnection->peeraddress, svs.clients[num].netaddress, sizeof(svs.clients[num].netaddress), false);
-                       PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(svs.clients[num].netaddress);
+                       PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, svs.clients[num].netaddress);
                }
                else
-                       PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString("null/botclient");
+                       PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, "null/botclient");
                if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_idfp[0])
-                       PRVM_serveredictstring(e, crypto_idfp) = PRVM_SetEngineString(svs.clients[num].netconnection->crypto.client_idfp);
+                       PRVM_serveredictstring(e, crypto_idfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_idfp);
                else
                        PRVM_serveredictstring(e, crypto_idfp) = 0;
+               PRVM_serveredictfloat(e, crypto_idfp_signed) = (svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_issigned);
                if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_keyfp[0])
-                       PRVM_serveredictstring(e, crypto_keyfp) = PRVM_SetEngineString(svs.clients[num].netconnection->crypto.client_keyfp);
+                       PRVM_serveredictstring(e, crypto_keyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_keyfp);
                else
                        PRVM_serveredictstring(e, crypto_keyfp) = 0;
                if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.server_keyfp[0])
-                       PRVM_serveredictstring(e, crypto_mykeyfp) = PRVM_SetEngineString(svs.clients[num].netconnection->crypto.server_keyfp);
+                       PRVM_serveredictstring(e, crypto_mykeyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.server_keyfp);
                else
                        PRVM_serveredictstring(e, crypto_mykeyfp) = 0;
                if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.use_aes)
-                       PRVM_serveredictstring(e, crypto_encryptmethod) = PRVM_SetEngineString("AES128");
+                       PRVM_serveredictstring(e, crypto_encryptmethod) = PRVM_SetEngineString(prog, "AES128");
                else
                        PRVM_serveredictstring(e, crypto_encryptmethod) = 0;
                if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated)
-                       PRVM_serveredictstring(e, crypto_signmethod) = PRVM_SetEngineString("HMAC-SHA256");
+                       PRVM_serveredictstring(e, crypto_signmethod) = PRVM_SetEngineString(prog, "HMAC-SHA256");
                else
                        PRVM_serveredictstring(e, crypto_signmethod) = 0;
        }
 }
 
-static void SV_VM_CB_FreeEdict(prvm_edict_t *ed)
+static void SVVM_free_edict(prvm_prog_t *prog, prvm_edict_t *ed)
 {
        int i;
        int e;
 
        World_UnlinkEdict(ed);          // unlink from world bsp
 
-       ed->fields.server->model = 0;
-       ed->fields.server->takedamage = 0;
-       ed->fields.server->modelindex = 0;
-       ed->fields.server->colormap = 0;
-       ed->fields.server->skin = 0;
-       ed->fields.server->frame = 0;
-       VectorClear(ed->fields.server->origin);
-       VectorClear(ed->fields.server->angles);
-       ed->fields.server->nextthink = -1;
-       ed->fields.server->solid = 0;
-
-       VM_RemoveEdictSkeleton(ed);
+       PRVM_serveredictstring(ed, model) = 0;
+       PRVM_serveredictfloat(ed, takedamage) = 0;
+       PRVM_serveredictfloat(ed, modelindex) = 0;
+       PRVM_serveredictfloat(ed, colormap) = 0;
+       PRVM_serveredictfloat(ed, skin) = 0;
+       PRVM_serveredictfloat(ed, frame) = 0;
+       VectorClear(PRVM_serveredictvector(ed, origin));
+       VectorClear(PRVM_serveredictvector(ed, angles));
+       PRVM_serveredictfloat(ed, nextthink) = -1;
+       PRVM_serveredictfloat(ed, solid) = 0;
+
+       VM_RemoveEdictSkeleton(prog, ed);
        World_Physics_RemoveFromEntity(&sv.world, ed);
        World_Physics_RemoveJointFromEntity(&sv.world, ed);
 
@@ -3529,14 +3856,10 @@ static void SV_VM_CB_FreeEdict(prvm_edict_t *ed)
        e = PRVM_NUM_FOR_EDICT(ed);
        sv.csqcentityversion[e] = 0;
        for (i = 0;i < svs.maxclients;i++)
-       {
-               if (svs.clients[i].csqcentityscope[e])
-                       svs.clients[i].csqcentityscope[e] = 1; // removed, awaiting send
                svs.clients[i].csqcentitysendflags[e] = 0xFFFFFF;
-       }
 }
 
-static void SV_VM_CB_CountEdicts(void)
+static void SVVM_count_edicts(prvm_prog_t *prog)
 {
        int             i;
        prvm_edict_t    *ent;
@@ -3549,11 +3872,11 @@ static void SV_VM_CB_CountEdicts(void)
                if (ent->priv.server->free)
                        continue;
                active++;
-               if (ent->fields.server->solid)
+               if (PRVM_serveredictfloat(ent, solid))
                        solid++;
-               if (ent->fields.server->model)
+               if (PRVM_serveredictstring(ent, model))
                        models++;
-               if (ent->fields.server->movetype == MOVETYPE_STEP)
+               if (PRVM_serveredictfloat(ent, movetype) == MOVETYPE_STEP)
                        step++;
        }
 
@@ -3564,21 +3887,21 @@ static void SV_VM_CB_CountEdicts(void)
        Con_Printf("step      :%3i\n", step);
 }
 
-static qboolean SV_VM_CB_LoadEdict(prvm_edict_t *ent)
+static qboolean SVVM_load_edict(prvm_prog_t *prog, prvm_edict_t *ent)
 {
        // remove things from different skill levels or deathmatch
        if (gamemode != GAME_TRANSFUSION) //Transfusion does this in QC
        {
                if (deathmatch.integer)
                {
-                       if (((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_DEATHMATCH))
+                       if (((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_DEATHMATCH))
                        {
                                return false;
                        }
                }
-               else if ((current_skill <= 0 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_EASY  ))
-                       || (current_skill == 1 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_MEDIUM))
-                       || (current_skill >= 2 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_HARD  )))
+               else if ((current_skill <= 0 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_EASY  ))
+                       || (current_skill == 1 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_MEDIUM))
+                       || (current_skill >= 2 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_HARD  )))
                {
                        return false;
                }
@@ -3588,16 +3911,14 @@ static qboolean SV_VM_CB_LoadEdict(prvm_edict_t *ent)
 
 static void SV_VM_Setup(void)
 {
-       PRVM_Begin;
-       PRVM_InitProg( PRVM_SERVERPROG );
+       prvm_prog_t *prog = SVVM_prog;
+       PRVM_Prog_Init(prog, &cmd_server);
 
        // allocate the mempools
        // TODO: move the magic numbers/constants into #defines [9/13/2006 Black]
        prog->progs_mempool = Mem_AllocPool("Server Progs", 0, NULL);
        prog->builtins = vm_sv_builtins;
        prog->numbuiltins = vm_sv_numbuiltins;
-       prog->headercrc = PROGHEADER_CRC;
-       prog->headercrc2 = PROGHEADER_CRC_TENEBRAE;
        prog->max_edicts = 512;
        if (sv.protocol == PROTOCOL_QUAKE)
                prog->limit_edicts = 640; // before quake mission pack 1 this was 512
@@ -3615,64 +3936,330 @@ static void SV_VM_Setup(void)
        prog->extensionstring = vm_sv_extensions;
        prog->loadintoworld = true;
 
-       prog->begin_increase_edicts = SV_VM_CB_BeginIncreaseEdicts;
-       prog->end_increase_edicts = SV_VM_CB_EndIncreaseEdicts;
-       prog->init_edict = SV_VM_CB_InitEdict;
-       prog->free_edict = SV_VM_CB_FreeEdict;
-       prog->count_edicts = SV_VM_CB_CountEdicts;
-       prog->load_edict = SV_VM_CB_LoadEdict;
-       prog->init_cmd = VM_SV_Cmd_Init;
-       prog->reset_cmd = VM_SV_Cmd_Reset;
-       prog->error_cmd = Host_Error;
-       prog->ExecuteProgram = SVVM_ExecuteProgram;
+       // all callbacks must be defined (pointers are not checked before calling)
+       prog->begin_increase_edicts = SVVM_begin_increase_edicts;
+       prog->end_increase_edicts   = SVVM_end_increase_edicts;
+       prog->init_edict            = SVVM_init_edict;
+       prog->free_edict            = SVVM_free_edict;
+       prog->count_edicts          = SVVM_count_edicts;
+       prog->load_edict            = SVVM_load_edict;
+       prog->init_cmd              = SVVM_init_cmd;
+       prog->reset_cmd             = SVVM_reset_cmd;
+       prog->error_cmd             = Host_Error;
+       prog->ExecuteProgram        = SVVM_ExecuteProgram;
 
-       PRVM_LoadProgs( sv_progs.string, SV_REQFUNCS, sv_reqfuncs, SV_REQFIELDS, sv_reqfields, SV_REQGLOBALS, sv_reqglobals);
+       PRVM_Prog_Load(prog, sv_progs.string, NULL, 0, SV_REQFUNCS, sv_reqfuncs, SV_REQFIELDS, sv_reqfields, SV_REQGLOBALS, sv_reqglobals);
 
        // some mods compiled with scrambling compilers lack certain critical
        // global names and field names such as "self" and "time" and "nextthink"
        // so we have to set these offsets manually, matching the entvars_t
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, angles);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, chain);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, classname);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frame);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, groundentity);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ideal_yaw);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, nextthink);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, think);
-       PRVM_ED_FindFieldOffset_FromStruct(entvars_t, yaw_speed);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, self);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, time);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_forward);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_right);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_up);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_allsolid);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_startsolid);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_fraction);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inwater);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inopen);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_endpos);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_normal);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_dist);
-       PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_ent);
-       // OP_STATE is always supported on server (due to entvars_t)
+       // but we only do this if the prog header crc matches, otherwise it's totally freeform
+       if (prog->progs_crc == PROGHEADER_CRC || prog->progs_crc == PROGHEADER_CRC_TENEBRAE)
+       {
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, modelindex);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmin);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmax);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ltime);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movetype);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, solid);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, origin);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, oldorigin);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, velocity);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, angles);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, avelocity);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, punchangle);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, classname);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, model);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frame);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, skin);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, effects);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, mins);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, maxs);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, size);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, touch);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, use);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, think);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, blocked);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, nextthink);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, groundentity);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, health);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frags);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weapon);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponmodel);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponframe);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, currentammo);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_shells);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_nails);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_rockets);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_cells);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, items);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, takedamage);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, chain);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, deadflag);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, view_ofs);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button0);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button1);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button2);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, impulse);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, fixangle);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, v_angle);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, idealpitch);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, netname);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, enemy);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, flags);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, colormap);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, team);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, max_health);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, teleport_time);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armortype);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armorvalue);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, waterlevel);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, watertype);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ideal_yaw);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, yaw_speed);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, aiment);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, goalentity);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, spawnflags);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, target);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, targetname);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_take);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_save);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_inflictor);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, owner);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movedir);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, message);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, sounds);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise1);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise2);
+               PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise3);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, self);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, other);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, world);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, time);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, frametime);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, force_retouch);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, mapname);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, deathmatch);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, coop);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, teamplay);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, serverflags);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_secrets);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_monsters);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, found_secrets);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, killed_monsters);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm1);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm2);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm3);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm4);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm5);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm6);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm7);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm8);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm9);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm10);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm11);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm12);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm13);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm14);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm15);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm16);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_forward);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_up);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_right);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_allsolid);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_startsolid);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_fraction);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_endpos);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_normal);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_dist);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_ent);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inopen);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inwater);
+               PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, msg_entity);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, main);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, StartFrame);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPreThink);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPostThink);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientKill);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientConnect);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PutClientInServer);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientDisconnect);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetNewParms);
+//             PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetChangeParms);
+       }
+       else
+               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);
+
+       // OP_STATE is always supported on server because we add fields/globals for it
        prog->flag |= PRVM_OP_STATE;
 
        VM_CustomStats_Clear();//[515]: csqc
 
-       PRVM_End;
-
        SV_Prepare_CSQC();
 }
 
-void SV_VM_Begin(void)
+extern cvar_t host_maxwait;
+extern cvar_t host_framerate;
+static int SV_ThreadFunc(void *voiddata)
 {
-       PRVM_Begin;
-       PRVM_SetProg( PRVM_SERVERPROG );
+       prvm_prog_t *prog = SVVM_prog;
+       qboolean playing = false;
+       double sv_timer = 0;
+       double sv_deltarealtime, sv_oldrealtime, sv_realtime;
+       double wait;
+       int i;
+       char vabuf[1024];
+       sv_realtime = Sys_DirtyTime();
+       while (!svs.threadstop)
+       {
+               // FIXME: we need to handle Host_Error in the server thread somehow
+//             if (setjmp(sv_abortframe))
+//                     continue;                       // something bad happened in the server game
+
+               sv_oldrealtime = sv_realtime;
+               sv_realtime = Sys_DirtyTime();
+               sv_deltarealtime = sv_realtime - sv_oldrealtime;
+               if (sv_deltarealtime < 0 || sv_deltarealtime >= 1800) sv_deltarealtime = 0;
+
+               sv_timer += sv_deltarealtime;
+
+               svs.perf_acc_realtime += sv_deltarealtime;
+
+               // 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)
+               SV_LockThreadMutex();
+
+               // Look for clients who have spawned
+               playing = false;
+               if (sv.active)
+                       for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
+                               if(host_client->begun)
+                                       if(host_client->netconnection)
+                                               playing = true;
+               if(sv.time < 10)
+               {
+                       // don't accumulate time for the first 10 seconds of a match
+                       // so things can settle
+                       svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
+               }
+               else if(svs.perf_acc_realtime > 5)
+               {
+                       svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
+                       svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
+                       if(svs.perf_acc_offset_samples > 0)
+                       {
+                               svs.perf_offset_max = svs.perf_acc_offset_max;
+                               svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
+                               svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
+                       }
+                       if(svs.perf_lost > 0 && developer_extra.integer)
+                               if(playing)
+                                       Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
+                       svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
+               }
+
+               // get new packets
+               if (sv.active)
+                       NetConn_ServerFrame();
+
+               // if the accumulators haven't become positive yet, wait a while
+               wait = sv_timer * -1000000.0;
+               if (wait >= 1)
+               {
+                       double time0, delta;
+                       SV_UnlockThreadMutex(); // don't keep mutex locked while sleeping
+                       if (host_maxwait.value <= 0)
+                               wait = min(wait, 1000000.0);
+                       else
+                               wait = min(wait, host_maxwait.value * 1000.0);
+                       if(wait < 1)
+                               wait = 1; // because we cast to int
+                       time0 = Sys_DirtyTime();
+                       Sys_Sleep((int)wait);
+                       delta = Sys_DirtyTime() - time0;if (delta < 0 || delta >= 1800) delta = 0;
+                       svs.perf_acc_sleeptime += delta;
+                       continue;
+               }
+
+               if (sv.active && sv_timer > 0)
+               {
+                       // execute one server frame
+                       double advancetime;
+                       float offset;
+
+                       if (sys_ticrate.value <= 0)
+                               advancetime = min(sv_timer, 0.1); // don't step more than 100ms
+                       else
+                               advancetime = sys_ticrate.value;
 
-       prog->globals.server->time = (float) sv.time;
+                       if(advancetime > 0)
+                       {
+                               offset = sv_timer + (Sys_DirtyTime() - sv_realtime); // LadyHavoc: FIXME: I don't understand this line
+                               ++svs.perf_acc_offset_samples;
+                               svs.perf_acc_offset += offset;
+                               svs.perf_acc_offset_squared += offset * offset;
+                               if(svs.perf_acc_offset_max < offset)
+                                       svs.perf_acc_offset_max = offset;
+                       }
+
+                       // only advance time if not paused
+                       // the game also pauses in singleplayer when menu or console is used
+                       sv.frametime = advancetime * host_timescale.value;
+                       if (host_framerate.value)
+                               sv.frametime = host_framerate.value;
+                       if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
+                               sv.frametime = 0;
+
+                       sv_timer -= advancetime;
+
+                       // move things around and think unless paused
+                       if (sv.frametime)
+                               SV_Physics();
+
+                       // send all messages to the clients
+                       SV_SendClientMessages();
+
+                       if (sv.paused == 1 && sv_realtime > sv.pausedstart && sv.pausedstart > 0)
+                       {
+                               PRVM_serverglobalfloat(time) = sv.time;
+                               prog->globals.fp[OFS_PARM0] = sv_realtime - sv.pausedstart;
+                               prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
+                       }
+
+                       // send an heartbeat if enough time has passed since the last one
+                       NetConn_Heartbeat(0);
+
+               }
+
+               // we're back to safe code now
+               SV_UnlockThreadMutex();
+
+               // if there is some time remaining from this frame, reset the timers
+               if (sv_timer >= 0)
+               {
+                       svs.perf_acc_lost += sv_timer;
+                       sv_timer = 0;
+               }
+       }
+       return 0;
 }
 
-void SV_VM_End(void)
+void SV_StartThread(void)
 {
-       PRVM_End;
+       if (!sv_threaded.integer || !Thread_HasThreads())
+               return;
+       svs.threaded = true;
+       svs.threadstop = false;
+       svs.threadmutex = Thread_CreateMutex();
+       svs.thread = Thread_CreateThread(SV_ThreadFunc, NULL);
+}
+
+void SV_StopThread(void)
+{
+       if (!svs.threaded)
+               return;
+       svs.threadstop = true;
+       Thread_WaitThread(svs.thread, 0);
+       Thread_DestroyMutex(svs.threadmutex);
+       svs.threaded = false;
 }