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