added friction and waterfriction movevars stats
[divverent/darkplaces.git] / sv_user.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sv_user.c -- server code for moving users
21
22 #include "quakedef.h"
23 #define DEBUGMOVES 0
24
25 cvar_t sv_wallfriction = {CVAR_NOTIFY, "sv_wallfriction", "1", "how much you slow down when sliding along a wall"};
26 cvar_t sv_stepheight = {CVAR_NOTIFY, "sv_stepheight", "18", "how high you can step up (TW_SV_STEPCONTROL extension)"};
27 cvar_t sv_stopspeed = {CVAR_NOTIFY, "sv_stopspeed","100", "how fast you come to a complete stop"};
28 cvar_t sv_friction = {CVAR_NOTIFY, "sv_friction","4", "how fast you slow down"};
29 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"};
30 cvar_t sv_edgefriction = {0, "edgefriction", "2", "how much you slow down when nearing a ledge you might fall off"};
31 cvar_t sv_idealpitchscale = {0, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
32 cvar_t sv_maxspeed = {CVAR_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
33 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)"};
34 cvar_t sv_accelerate = {0, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
35 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"};
36 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"};
37 cvar_t sv_jumpvelocity = {0, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
38 cvar_t sv_airaccel_qw = {0, "sv_airaccel_qw", "1", "ratio of QW-style air control as opposed to simple acceleration"};
39 cvar_t sv_airaccel_sideways_friction = {0, "sv_airaccel_sideways_friction", "", "anti-sideways movement stabilization (reduces speed gain when zigzagging)"};
40 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"};
41 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)"};
42 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)"};
43 cvar_t sv_clmovement_waitforinput = {0, "sv_clmovement_waitforinput", "16", "when a client does not send input for this many frames, force them to move anyway (unlike QuakeWorld)"};
44
45 static usercmd_t cmd;
46
47
48 /*
49 ===============
50 SV_SetIdealPitch
51 ===============
52 */
53 #define MAX_FORWARD     6
54 void SV_SetIdealPitch (void)
55 {
56         float   angleval, sinval, cosval, step, dir;
57         trace_t tr;
58         vec3_t  top, bottom;
59         float   z[MAX_FORWARD];
60         int             i, j;
61         int             steps;
62
63         if (!((int)host_client->edict->fields.server->flags & FL_ONGROUND))
64                 return;
65
66         angleval = host_client->edict->fields.server->angles[YAW] * M_PI*2 / 360;
67         sinval = sin(angleval);
68         cosval = cos(angleval);
69
70         for (i=0 ; i<MAX_FORWARD ; i++)
71         {
72                 top[0] = host_client->edict->fields.server->origin[0] + cosval*(i+3)*12;
73                 top[1] = host_client->edict->fields.server->origin[1] + sinval*(i+3)*12;
74                 top[2] = host_client->edict->fields.server->origin[2] + host_client->edict->fields.server->view_ofs[2];
75
76                 bottom[0] = top[0];
77                 bottom[1] = top[1];
78                 bottom[2] = top[2] - 160;
79
80                 tr = SV_Move (top, vec3_origin, vec3_origin, bottom, MOVE_NOMONSTERS, host_client->edict, SUPERCONTENTS_SOLID);
81                 // if looking at a wall, leave ideal the way is was
82                 if (tr.startsolid)
83                         return;
84
85                 // near a dropoff
86                 if (tr.fraction == 1)
87                         return;
88
89                 z[i] = top[2] + tr.fraction*(bottom[2]-top[2]);
90         }
91
92         dir = 0;
93         steps = 0;
94         for (j=1 ; j<i ; j++)
95         {
96                 step = z[j] - z[j-1];
97                 if (step > -ON_EPSILON && step < ON_EPSILON)
98                         continue;
99
100                 // mixed changes
101                 if (dir && ( step-dir > ON_EPSILON || step-dir < -ON_EPSILON ) )
102                         return;
103
104                 steps++;
105                 dir = step;
106         }
107
108         if (!dir)
109         {
110                 host_client->edict->fields.server->idealpitch = 0;
111                 return;
112         }
113
114         if (steps < 2)
115                 return;
116         host_client->edict->fields.server->idealpitch = -dir * sv_idealpitchscale.value;
117 }
118
119 static vec3_t wishdir, forward, right, up;
120 static float wishspeed;
121
122 static qboolean onground;
123
124 /*
125 ==================
126 SV_UserFriction
127
128 ==================
129 */
130 void SV_UserFriction (void)
131 {
132         float speed, newspeed, control, friction;
133         vec3_t start, stop;
134         trace_t trace;
135
136         speed = sqrt(host_client->edict->fields.server->velocity[0]*host_client->edict->fields.server->velocity[0]+host_client->edict->fields.server->velocity[1]*host_client->edict->fields.server->velocity[1]);
137         if (!speed)
138                 return;
139
140         // if the leading edge is over a dropoff, increase friction
141         start[0] = stop[0] = host_client->edict->fields.server->origin[0] + host_client->edict->fields.server->velocity[0]/speed*16;
142         start[1] = stop[1] = host_client->edict->fields.server->origin[1] + host_client->edict->fields.server->velocity[1]/speed*16;
143         start[2] = host_client->edict->fields.server->origin[2] + host_client->edict->fields.server->mins[2];
144         stop[2] = start[2] - 34;
145
146         trace = SV_Move (start, vec3_origin, vec3_origin, stop, MOVE_NOMONSTERS, host_client->edict, SV_GenericHitSuperContentsMask(host_client->edict));
147
148         if (trace.fraction == 1.0)
149                 friction = sv_friction.value*sv_edgefriction.value;
150         else
151                 friction = sv_friction.value;
152
153         // apply friction
154         control = speed < sv_stopspeed.value ? sv_stopspeed.value : speed;
155         newspeed = speed - sv.frametime*control*friction;
156
157         if (newspeed < 0)
158                 newspeed = 0;
159         else
160                 newspeed /= speed;
161
162         VectorScale(host_client->edict->fields.server->velocity, newspeed, host_client->edict->fields.server->velocity);
163 }
164
165 /*
166 ==============
167 SV_Accelerate
168 ==============
169 */
170 void SV_Accelerate (void)
171 {
172         int i;
173         float addspeed, accelspeed, currentspeed;
174
175         currentspeed = DotProduct (host_client->edict->fields.server->velocity, wishdir);
176         addspeed = wishspeed - currentspeed;
177         if (addspeed <= 0)
178                 return;
179         accelspeed = sv_accelerate.value*sv.frametime*wishspeed;
180         if (accelspeed > addspeed)
181                 accelspeed = addspeed;
182
183         for (i=0 ; i<3 ; i++)
184                 host_client->edict->fields.server->velocity[i] += accelspeed*wishdir[i];
185 }
186
187 void SV_AirAccelerate (vec3_t wishveloc)
188 {
189         int i;
190         float addspeed, wishspd, accelspeed, currentspeed;
191
192         wishspd = VectorNormalizeLength (wishveloc);
193         if (wishspd > sv_maxairspeed.value)
194                 wishspd = sv_maxairspeed.value;
195         currentspeed = DotProduct (host_client->edict->fields.server->velocity, wishveloc);
196         addspeed = wishspd - currentspeed;
197         if (addspeed <= 0)
198                 return;
199         accelspeed = (sv_airaccelerate.value < 0 ? sv_accelerate.value : sv_airaccelerate.value)*wishspeed * sv.frametime;
200         if (accelspeed > addspeed)
201                 accelspeed = addspeed;
202
203         for (i=0 ; i<3 ; i++)
204                 host_client->edict->fields.server->velocity[i] += accelspeed*wishveloc[i];
205 }
206
207
208 void DropPunchAngle (void)
209 {
210         float len;
211         prvm_eval_t *val;
212
213         len = VectorNormalizeLength (host_client->edict->fields.server->punchangle);
214
215         len -= 10*sv.frametime;
216         if (len < 0)
217                 len = 0;
218         VectorScale (host_client->edict->fields.server->punchangle, len, host_client->edict->fields.server->punchangle);
219
220         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.punchvector)))
221         {
222                 len = VectorNormalizeLength (val->vector);
223
224                 len -= 20*sv.frametime;
225                 if (len < 0)
226                         len = 0;
227                 VectorScale (val->vector, len, val->vector);
228         }
229 }
230
231 /*
232 ===================
233 SV_FreeMove
234 ===================
235 */
236 void SV_FreeMove (void)
237 {
238         int i;
239         float wishspeed;
240
241         AngleVectors (host_client->edict->fields.server->v_angle, forward, right, up);
242
243         for (i = 0; i < 3; i++)
244                 host_client->edict->fields.server->velocity[i] = forward[i] * cmd.forwardmove + right[i] * cmd.sidemove;
245
246         host_client->edict->fields.server->velocity[2] += cmd.upmove;
247
248         wishspeed = VectorLength(host_client->edict->fields.server->velocity);
249         if (wishspeed > sv_maxspeed.value)
250                 VectorScale(host_client->edict->fields.server->velocity, sv_maxspeed.value / wishspeed, host_client->edict->fields.server->velocity);
251 }
252
253 /*
254 ===================
255 SV_WaterMove
256
257 ===================
258 */
259 void SV_WaterMove (void)
260 {
261         int i;
262         vec3_t wishvel;
263         float speed, newspeed, wishspeed, addspeed, accelspeed, temp;
264
265         // user intentions
266         AngleVectors (host_client->edict->fields.server->v_angle, forward, right, up);
267
268         for (i=0 ; i<3 ; i++)
269                 wishvel[i] = forward[i]*cmd.forwardmove + right[i]*cmd.sidemove;
270
271         if (!cmd.forwardmove && !cmd.sidemove && !cmd.upmove)
272                 wishvel[2] -= 60;               // drift towards bottom
273         else
274                 wishvel[2] += cmd.upmove;
275
276         wishspeed = VectorLength(wishvel);
277         if (wishspeed > sv_maxspeed.value)
278         {
279                 temp = sv_maxspeed.value/wishspeed;
280                 VectorScale (wishvel, temp, wishvel);
281                 wishspeed = sv_maxspeed.value;
282         }
283         wishspeed *= 0.7;
284
285         // water friction
286         speed = VectorLength(host_client->edict->fields.server->velocity);
287         if (speed)
288         {
289                 newspeed = speed - sv.frametime * speed * (sv_waterfriction.value < 0 ? sv_friction.value : sv_waterfriction.value);
290                 if (newspeed < 0)
291                         newspeed = 0;
292                 temp = newspeed/speed;
293                 VectorScale(host_client->edict->fields.server->velocity, temp, host_client->edict->fields.server->velocity);
294         }
295         else
296                 newspeed = 0;
297
298         // water acceleration
299         if (!wishspeed)
300                 return;
301
302         addspeed = wishspeed - newspeed;
303         if (addspeed <= 0)
304                 return;
305
306         VectorNormalize (wishvel);
307         accelspeed = (sv_wateraccelerate.value < 0 ? sv_accelerate.value : sv_wateraccelerate.value) * wishspeed * sv.frametime;
308         if (accelspeed > addspeed)
309                 accelspeed = addspeed;
310
311         for (i=0 ; i<3 ; i++)
312                 host_client->edict->fields.server->velocity[i] += accelspeed * wishvel[i];
313 }
314
315 void SV_WaterJump (void)
316 {
317         if (sv.time > host_client->edict->fields.server->teleport_time || !host_client->edict->fields.server->waterlevel)
318         {
319                 host_client->edict->fields.server->flags = (int)host_client->edict->fields.server->flags & ~FL_WATERJUMP;
320                 host_client->edict->fields.server->teleport_time = 0;
321         }
322         host_client->edict->fields.server->velocity[0] = host_client->edict->fields.server->movedir[0];
323         host_client->edict->fields.server->velocity[1] = host_client->edict->fields.server->movedir[1];
324 }
325
326
327 /*
328 ===================
329 SV_AirMove
330
331 ===================
332 */
333 void SV_AirMove (void)
334 {
335         int i;
336         vec3_t wishvel;
337         float fmove, smove, temp;
338
339         // LordHavoc: correct quake movement speed bug when looking up/down
340         wishvel[0] = wishvel[2] = 0;
341         wishvel[1] = host_client->edict->fields.server->angles[1];
342         AngleVectors (wishvel, forward, right, up);
343
344         fmove = cmd.forwardmove;
345         smove = cmd.sidemove;
346
347 // hack to not let you back into teleporter
348         if (sv.time < host_client->edict->fields.server->teleport_time && fmove < 0)
349                 fmove = 0;
350
351         for (i=0 ; i<3 ; i++)
352                 wishvel[i] = forward[i]*fmove + right[i]*smove;
353
354         if ((int)host_client->edict->fields.server->movetype != MOVETYPE_WALK)
355                 wishvel[2] += cmd.upmove;
356
357         VectorCopy (wishvel, wishdir);
358         wishspeed = VectorNormalizeLength(wishdir);
359         if (wishspeed > sv_maxspeed.value)
360         {
361                 temp = sv_maxspeed.value/wishspeed;
362                 VectorScale (wishvel, temp, wishvel);
363                 wishspeed = sv_maxspeed.value;
364         }
365
366         if (host_client->edict->fields.server->movetype == MOVETYPE_NOCLIP)
367         {
368                 // noclip
369                 VectorCopy (wishvel, host_client->edict->fields.server->velocity);
370         }
371         else if (onground && (!sv_gameplayfix_qwplayerphysics.integer || !(host_client->edict->fields.server->button2 || !((int)host_client->edict->fields.server->flags & FL_JUMPRELEASED))))
372         {
373                 SV_UserFriction ();
374                 SV_Accelerate ();
375         }
376         else
377         {
378                 // not on ground, so little effect on velocity
379                 SV_AirAccelerate (wishvel);
380         }
381 }
382
383 /*
384 ===================
385 SV_ClientThink
386
387 the move fields specify an intended velocity in pix/sec
388 the angle fields specify an exact angular motion in degrees
389 ===================
390 */
391 extern cvar_t sv_playerphysicsqc;
392 void SV_ClientThink (void)
393 {
394         vec3_t v_angle;
395
396         SV_ApplyClientMove();
397         // make sure the velocity is sane (not a NaN)
398         SV_CheckVelocity(host_client->edict);
399
400         // LordHavoc: QuakeC replacement for SV_ClientThink (player movement)
401         if (prog->funcoffsets.SV_PlayerPhysics && sv_playerphysicsqc.integer)
402         {
403                 prog->globals.server->time = sv.time;
404                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
405                 PRVM_ExecuteProgram (prog->funcoffsets.SV_PlayerPhysics, "QC function SV_PlayerPhysics is missing");
406                 SV_CheckVelocity(host_client->edict);
407                 return;
408         }
409
410         if (host_client->edict->fields.server->movetype == MOVETYPE_NONE)
411                 return;
412
413         onground = (int)host_client->edict->fields.server->flags & FL_ONGROUND;
414
415         DropPunchAngle ();
416
417         // if dead, behave differently
418         if (host_client->edict->fields.server->health <= 0)
419                 return;
420
421         cmd = host_client->cmd;
422
423         // angles
424         // show 1/3 the pitch angle and all the roll angle
425         VectorAdd (host_client->edict->fields.server->v_angle, host_client->edict->fields.server->punchangle, v_angle);
426         host_client->edict->fields.server->angles[ROLL] = V_CalcRoll (host_client->edict->fields.server->angles, host_client->edict->fields.server->velocity)*4;
427         if (!host_client->edict->fields.server->fixangle)
428         {
429                 host_client->edict->fields.server->angles[PITCH] = -v_angle[PITCH]/3;
430                 host_client->edict->fields.server->angles[YAW] = v_angle[YAW];
431         }
432
433         if ( (int)host_client->edict->fields.server->flags & FL_WATERJUMP )
434         {
435                 SV_WaterJump ();
436                 SV_CheckVelocity(host_client->edict);
437                 return;
438         }
439
440         /*
441         // Player is (somehow) outside of the map, or flying, or noclipping
442         if (host_client->edict->fields.server->movetype != MOVETYPE_NOCLIP && (host_client->edict->fields.server->movetype == MOVETYPE_FLY || SV_TestEntityPosition (host_client->edict)))
443         //if (host_client->edict->fields.server->movetype == MOVETYPE_NOCLIP || host_client->edict->fields.server->movetype == MOVETYPE_FLY || SV_TestEntityPosition (host_client->edict))
444         {
445                 SV_FreeMove ();
446                 return;
447         }
448         */
449
450         // walk
451         if ((host_client->edict->fields.server->waterlevel >= 2) && (host_client->edict->fields.server->movetype != MOVETYPE_NOCLIP))
452         {
453                 SV_WaterMove ();
454                 SV_CheckVelocity(host_client->edict);
455                 return;
456         }
457
458         SV_AirMove ();
459         SV_CheckVelocity(host_client->edict);
460 }
461
462 /*
463 ===================
464 SV_ReadClientMove
465 ===================
466 */
467 int sv_numreadmoves = 0;
468 usercmd_t sv_readmoves[CL_MAX_USERCMDS];
469 void SV_ReadClientMove (void)
470 {
471         int i;
472         usercmd_t newmove;
473         usercmd_t *move = &newmove;
474
475         memset(move, 0, sizeof(*move));
476
477         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
478
479         // read ping time
480         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5 && sv.protocol != PROTOCOL_DARKPLACES6)
481                 move->sequence = MSG_ReadLong ();
482         move->time = MSG_ReadFloat ();
483         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
484         move->receivetime = (float)sv.time;
485
486 #if DEBUGMOVES
487         Con_Printf("%s move%i #%i %ims (%ims) %i %i '%i %i %i' '%i %i %i'\n", move->time > move->receivetime ? "^3read future" : "^4read normal", sv_numreadmoves + 1, move->sequence, (int)floor((move->time - host_client->cmd.time) * 1000.0 + 0.5), (int)floor(move->time * 1000.0 + 0.5), move->impulse, move->buttons, (int)move->viewangles[0], (int)move->viewangles[1], (int)move->viewangles[2], (int)move->forwardmove, (int)move->sidemove, (int)move->upmove);
488 #endif
489         // limit reported time to current time
490         // (incase the client is trying to cheat)
491         move->time = min(move->time, move->receivetime + sv.frametime);
492
493         // read current angles
494         for (i = 0;i < 3;i++)
495         {
496                 if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE)
497                         move->viewangles[i] = MSG_ReadAngle8i();
498                 else if (sv.protocol == PROTOCOL_DARKPLACES1)
499                         move->viewangles[i] = MSG_ReadAngle16i();
500                 else if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
501                         move->viewangles[i] = MSG_ReadAngle32f();
502                 else
503                         move->viewangles[i] = MSG_ReadAngle16i();
504         }
505         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
506
507         // read movement
508         move->forwardmove = MSG_ReadCoord16i ();
509         move->sidemove = MSG_ReadCoord16i ();
510         move->upmove = MSG_ReadCoord16i ();
511         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
512
513         // read buttons
514         // be sure to bitwise OR them into the move->buttons because we want to
515         // accumulate button presses from multiple packets per actual move
516         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
517                 move->buttons = MSG_ReadByte ();
518         else
519                 move->buttons = MSG_ReadLong ();
520         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
521
522         // read impulse
523         move->impulse = MSG_ReadByte ();
524         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
525
526         // PRYDON_CLIENTCURSOR
527         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5)
528         {
529                 // 30 bytes
530                 move->cursor_screen[0] = MSG_ReadShort() * (1.0f / 32767.0f);
531                 move->cursor_screen[1] = MSG_ReadShort() * (1.0f / 32767.0f);
532                 move->cursor_start[0] = MSG_ReadFloat();
533                 move->cursor_start[1] = MSG_ReadFloat();
534                 move->cursor_start[2] = MSG_ReadFloat();
535                 move->cursor_impact[0] = MSG_ReadFloat();
536                 move->cursor_impact[1] = MSG_ReadFloat();
537                 move->cursor_impact[2] = MSG_ReadFloat();
538                 move->cursor_entitynumber = (unsigned short)MSG_ReadShort();
539                 if (move->cursor_entitynumber >= prog->max_edicts)
540                 {
541                         Con_DPrintf("SV_ReadClientMessage: client send bad cursor_entitynumber\n");
542                         move->cursor_entitynumber = 0;
543                 }
544                 // as requested by FrikaC, cursor_trace_ent is reset to world if the
545                 // entity is free at time of receipt
546                 if (PRVM_EDICT_NUM(move->cursor_entitynumber)->priv.server->free)
547                         move->cursor_entitynumber = 0;
548                 if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
549         }
550
551         // if the previous move has not been applied yet, we need to accumulate
552         // the impulse/buttons from it
553         if (!host_client->cmd.applied)
554         {
555                 if (!move->impulse)
556                         move->impulse = host_client->cmd.impulse;
557                 move->buttons |= host_client->cmd.buttons;
558         }
559
560         // now store this move for later execution
561         // (we have to buffer the moves because of old ones being repeated)
562         if (sv_numreadmoves < CL_MAX_USERCMDS)
563                 sv_readmoves[sv_numreadmoves++] = *move;
564 }
565
566 void SV_ExecuteClientMoves(void)
567 {
568         int moveindex;
569         float moveframetime;
570         double oldframetime;
571         double oldframetime2;
572 #ifdef NUM_PING_TIMES
573         double total;
574 #endif
575         prvm_eval_t *val;
576         if (sv_numreadmoves < 1)
577                 return;
578         // only start accepting input once the player is spawned
579         if (!host_client->spawned)
580                 return;
581 #if DEBUGMOVES
582         Con_Printf("SV_ExecuteClientMoves: read %i moves at sv.time %f\n", sv_numreadmoves, (float)sv.time);
583 #endif
584         // disable clientside movement prediction in some cases
585         if (ceil(max(sv_readmoves[sv_numreadmoves-1].receivetime - sv_readmoves[sv_numreadmoves-1].time, 0) * 1000.0) < sv_clmovement_minping.integer)
586                 host_client->clmovement_disabletimeout = realtime + sv_clmovement_minping_disabletime.value / 1000.0;
587         // several conditions govern whether clientside movement prediction is allowed
588         if (sv_readmoves[sv_numreadmoves-1].sequence && sv_clmovement_enable.integer && sv_clmovement_waitforinput.integer > 0 && host_client->clmovement_disabletimeout <= realtime && host_client->edict->fields.server->movetype == MOVETYPE_WALK && (!(val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.disableclientprediction)) || !val->_float))
589         {
590                 // process the moves in order and ignore old ones
591                 // but always trust the latest move
592                 // (this deals with bogus initial move sequences after level change,
593                 //  where the client will eventually catch up with the level change
594                 //  and reset its move sequence)
595                 for (moveindex = 0;moveindex < sv_numreadmoves;moveindex++)
596                 {
597                         usercmd_t *move = sv_readmoves + moveindex;
598                         if (host_client->movesequence < move->sequence || moveindex == sv_numreadmoves - 1)
599                         {
600 #if DEBUGMOVES
601                                 Con_Printf("%smove #%i %ims (%ims) %i %i '%i %i %i' '%i %i %i'\n", (move->time - host_client->cmd.time) > sv.frametime * 1.01 ? "^1" : "^2", move->sequence, (int)floor((move->time - host_client->cmd.time) * 1000.0 + 0.5), (int)floor(move->time * 1000.0 + 0.5), move->impulse, move->buttons, (int)move->viewangles[0], (int)move->viewangles[1], (int)move->viewangles[2], (int)move->forwardmove, (int)move->sidemove, (int)move->upmove);
602 #endif
603                                 // this is a new move
604                                 moveframetime = bound(0, move->time - host_client->cmd.time, 0.1);
605                                 //Con_Printf("movesequence = %i (%i lost), moveframetime = %f\n", move->sequence, move->sequence ? move->sequence - host_client->movesequence - 1 : 0, moveframetime);
606                                 host_client->cmd = *move;
607                                 host_client->movesequence = move->sequence;
608
609                                 // if using prediction, we need to perform moves when packets are
610                                 // received, even if multiple occur in one frame
611                                 // (they can't go beyond the current time so there is no cheat issue
612                                 //  with this approach, and if they don't send input for a while they
613                                 //  start moving anyway, so the longest 'lagaport' possible is
614                                 //  determined by the sv_clmovement_waitforinput cvar)
615                                 if (moveframetime <= 0)
616                                         continue;
617                                 oldframetime = prog->globals.server->frametime;
618                                 oldframetime2 = sv.frametime;
619                                 // update ping time for qc to see while executing this move
620                                 host_client->ping = host_client->cmd.receivetime - host_client->cmd.time;
621                                 // the server and qc frametime values must be changed temporarily
622                                 prog->globals.server->frametime = sv.frametime = moveframetime;
623                                 // if move is more than 50ms, split it into two moves (this matches QWSV behavior and the client prediction)
624                                 if (sv.frametime > 0.05)
625                                 {
626                                         prog->globals.server->frametime = sv.frametime = moveframetime * 0.5f;
627                                         SV_Physics_ClientMove();
628                                 }
629                                 SV_Physics_ClientMove();
630                                 sv.frametime = oldframetime2;
631                                 prog->globals.server->frametime = oldframetime;
632                                 host_client->clmovement_skipphysicsframes = sv_clmovement_waitforinput.integer;
633                         }
634                 }
635         }
636         else
637         {
638                 // try to gather button bits from old moves, but only if their time is
639                 // advancing (ones with the same timestamp can't be trusted)
640                 for (moveindex = 0;moveindex < sv_numreadmoves-1;moveindex++)
641                 {
642                         usercmd_t *move = sv_readmoves + moveindex;
643                         if (host_client->cmd.time < move->time)
644                         {
645                                 sv_readmoves[sv_numreadmoves-1].buttons |= move->buttons;
646                                 if (move->impulse)
647                                         sv_readmoves[sv_numreadmoves-1].impulse = move->impulse;
648                         }
649                 }
650                 // now copy the new move
651                 host_client->cmd = sv_readmoves[sv_numreadmoves-1];
652                 host_client->movesequence = 0;
653                 // make sure that normal physics takes over immediately
654                 host_client->clmovement_skipphysicsframes = 0;
655         }
656
657         // calculate average ping time
658         host_client->ping = host_client->cmd.receivetime - host_client->cmd.time;
659 #ifdef NUM_PING_TIMES
660         host_client->ping_times[host_client->num_pings % NUM_PING_TIMES] = host_client->cmd.receivetime - host_client->cmd.time;
661         host_client->num_pings++;
662         for (i=0, total = 0;i < NUM_PING_TIMES;i++)
663                 total += host_client->ping_times[i];
664         host_client->ping = total / NUM_PING_TIMES;
665 #endif
666 }
667
668 void SV_ApplyClientMove (void)
669 {
670         prvm_eval_t *val;
671         usercmd_t *move = &host_client->cmd;
672
673         if (!move->receivetime)
674                 return;
675
676         // note: a move can be applied multiple times if the client packets are
677         // not coming as often as the physics is executed, and the move must be
678         // applied before running qc each time because the id1 qc had a bug where
679         // it clears self.button2 in PlayerJump, causing pogostick behavior if
680         // moves are not applied every time before calling qc
681         move->applied = true;
682
683         // set the edict fields
684         host_client->edict->fields.server->button0 = move->buttons & 1;
685         host_client->edict->fields.server->button2 = (move->buttons & 2)>>1;
686         if (move->impulse)
687                 host_client->edict->fields.server->impulse = move->impulse;
688         // only send the impulse to qc once
689         move->impulse = 0;
690         VectorCopy(move->viewangles, host_client->edict->fields.server->v_angle);
691         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button3))) val->_float = ((move->buttons >> 2) & 1);
692         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button4))) val->_float = ((move->buttons >> 3) & 1);
693         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button5))) val->_float = ((move->buttons >> 4) & 1);
694         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button6))) val->_float = ((move->buttons >> 5) & 1);
695         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button7))) val->_float = ((move->buttons >> 6) & 1);
696         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button8))) val->_float = ((move->buttons >> 7) & 1);
697         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button9))) val->_float = ((move->buttons >> 11) & 1);
698         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button10))) val->_float = ((move->buttons >> 12) & 1);
699         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button11))) val->_float = ((move->buttons >> 13) & 1);
700         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button12))) val->_float = ((move->buttons >> 14) & 1);
701         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button13))) val->_float = ((move->buttons >> 15) & 1);
702         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button14))) val->_float = ((move->buttons >> 16) & 1);
703         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button15))) val->_float = ((move->buttons >> 17) & 1);
704         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button16))) val->_float = ((move->buttons >> 18) & 1);
705         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.buttonuse))) val->_float = ((move->buttons >> 8) & 1);
706         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.buttonchat))) val->_float = ((move->buttons >> 9) & 1);
707         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_active))) val->_float = ((move->buttons >> 10) & 1);
708         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.movement))) VectorSet(val->vector, move->forwardmove, move->sidemove, move->upmove);
709         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_screen))) VectorCopy(move->cursor_screen, val->vector);
710         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_trace_start))) VectorCopy(move->cursor_start, val->vector);
711         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_trace_endpos))) VectorCopy(move->cursor_impact, val->vector);
712         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_trace_ent))) val->edict = PRVM_EDICT_TO_PROG(PRVM_EDICT_NUM(move->cursor_entitynumber));
713         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.ping))) val->_float = host_client->ping * 1000.0;
714 }
715
716 void SV_FrameLost(int framenum)
717 {
718         if (host_client->entitydatabase5)
719                 EntityFrame5_LostFrame(host_client->entitydatabase5, framenum);
720 }
721
722 void SV_FrameAck(int framenum)
723 {
724         if (host_client->entitydatabase)
725                 EntityFrame_AckFrame(host_client->entitydatabase, framenum);
726         else if (host_client->entitydatabase4)
727                 EntityFrame4_AckFrame(host_client->entitydatabase4, framenum, true);
728         else if (host_client->entitydatabase5)
729                 EntityFrame5_AckFrame(host_client->entitydatabase5, framenum);
730 }
731
732 /*
733 ===================
734 SV_ReadClientMessage
735 ===================
736 */
737 extern void SV_SendServerinfo(client_t *client);
738 extern sizebuf_t vm_tempstringsbuf;
739 void SV_ReadClientMessage(void)
740 {
741         int cmd, num, start;
742         char *s;
743
744         //MSG_BeginReading ();
745         sv_numreadmoves = 0;
746
747         for(;;)
748         {
749                 if (!host_client->active)
750                 {
751                         // a command caused an error
752                         SV_DropClient (false);
753                         return;
754                 }
755
756                 if (msg_badread)
757                 {
758                         Con_Print("SV_ReadClientMessage: badread\n");
759                         SV_DropClient (false);
760                         return;
761                 }
762
763                 cmd = MSG_ReadByte ();
764                 if (cmd == -1)
765                 {
766                         // end of message
767                         // apply the moves that were read this frame
768                         SV_ExecuteClientMoves();
769                         break;
770                 }
771
772                 switch (cmd)
773                 {
774                 default:
775                         Con_Printf("SV_ReadClientMessage: unknown command char %i\n", cmd);
776                         SV_DropClient (false);
777                         return;
778
779                 case clc_nop:
780                         break;
781
782                 case clc_stringcmd:
783                         s = MSG_ReadString ();
784                         if (strncasecmp(s, "spawn", 5) == 0
785                          || strncasecmp(s, "begin", 5) == 0
786                          || strncasecmp(s, "prespawn", 8) == 0)
787                                 Cmd_ExecuteString (s, src_client);
788                         else if (prog->funcoffsets.SV_ParseClientCommand)
789                         {
790                                 int restorevm_tempstringsbuf_cursize;
791                                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
792                                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(s);
793                                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
794                                 PRVM_ExecuteProgram (prog->funcoffsets.SV_ParseClientCommand, "QC function SV_ParseClientCommand is missing");
795                                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
796                         }
797                         else
798                                 Cmd_ExecuteString (s, src_client);
799                         break;
800
801                 case clc_disconnect:
802                         SV_DropClient (false); // client wants to disconnect
803                         return;
804
805                 case clc_move:
806                         SV_ReadClientMove();
807                         break;
808
809                 case clc_ackdownloaddata:
810                         start = MSG_ReadLong();
811                         num = MSG_ReadShort();
812                         if (host_client->download_file && host_client->download_started)
813                         {
814                                 if (host_client->download_expectedposition == start)
815                                 {
816                                         int size = (int)FS_FileSize(host_client->download_file);
817                                         // a data block was successfully received by the client,
818                                         // update the expected position on the next data block
819                                         host_client->download_expectedposition = start + num;
820                                         // if this was the last data block of the file, it's done
821                                         if (host_client->download_expectedposition >= FS_FileSize(host_client->download_file))
822                                         {
823                                                 // tell the client that the download finished
824                                                 // we need to calculate the crc now
825                                                 //
826                                                 // note: at this point the OS probably has the file
827                                                 // entirely in memory, so this is a faster operation
828                                                 // now than it was when the download started.
829                                                 //
830                                                 // it is also preferable to do this at the end of the
831                                                 // download rather than the start because it reduces
832                                                 // potential for Denial Of Service attacks against the
833                                                 // server.
834                                                 int crc;
835                                                 unsigned char *temp;
836                                                 FS_Seek(host_client->download_file, 0, SEEK_SET);
837                                                 temp = Mem_Alloc(tempmempool, size);
838                                                 FS_Read(host_client->download_file, temp, size);
839                                                 crc = CRC_Block(temp, size);
840                                                 Mem_Free(temp);
841                                                 // calculated crc, send the file info to the client
842                                                 // (so that it can verify the data)
843                                                 Host_ClientCommands(va("\ncl_downloadfinished %i %i %s\n", size, crc, host_client->download_name));
844                                                 Con_DPrintf("Download of %s by %s has finished\n", host_client->download_name, host_client->name);
845                                                 FS_Close(host_client->download_file);
846                                                 host_client->download_file = NULL;
847                                                 host_client->download_name[0] = 0;
848                                                 host_client->download_expectedposition = 0;
849                                                 host_client->download_started = false;
850                                         }
851                                 }
852                                 else
853                                 {
854                                         // a data block was lost, reset to the expected position
855                                         // and resume sending from there
856                                         FS_Seek(host_client->download_file, host_client->download_expectedposition, SEEK_SET);
857                                 }
858                         }
859                         break;
860
861                 case clc_ackframe:
862                         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
863                         num = MSG_ReadLong();
864                         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
865                         if (developer_networkentities.integer >= 10)
866                                 Con_Printf("recv clc_ackframe %i\n", num);
867                         // if the client hasn't progressed through signons yet,
868                         // ignore any clc_ackframes we get (they're probably from the
869                         // previous level)
870                         if (host_client->spawned && host_client->latestframenum < num)
871                         {
872                                 int i;
873                                 for (i = host_client->latestframenum + 1;i < num;i++)
874                                         SV_FrameLost(i);
875                                 SV_FrameAck(num);
876                                 host_client->latestframenum = num;
877                         }
878                         break;
879                 }
880         }
881 }
882