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