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