]> git.xonotic.org Git - xonotic/darkplaces.git/blob - sv_user.c
test alpha
[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 usercmd;
27 extern cvar_t sv_autodemo_perclient;
28 extern cvar_t sv_rollangle;
29 extern cvar_t sv_rollspeed;
30
31 /*
32 ==================
33 SV_PreSpawn_f
34 ==================
35 */
36 void SV_PreSpawn_f(cmd_state_t *cmd)
37 {
38         if (host_client->prespawned)
39         {
40                 Con_Print("prespawn not valid -- already prespawned\n");
41                 return;
42         }
43         host_client->prespawned = true;
44
45         if (host_client->netconnection)
46         {
47                 SZ_Write (&host_client->netconnection->message, sv.signon.data, sv.signon.cursize);
48                 MSG_WriteByte (&host_client->netconnection->message, svc_signonnum);
49                 MSG_WriteByte (&host_client->netconnection->message, 2);
50                 host_client->sendsignon = 0;            // enable unlimited sends again
51         }
52
53         // reset the name change timer because the client will send name soon
54         host_client->nametime = 0;
55 }
56
57 /*
58 ==================
59 SV_Spawn_f
60 ==================
61 */
62 void SV_Spawn_f(cmd_state_t *cmd)
63 {
64         prvm_prog_t *prog = SVVM_prog;
65         int i;
66         client_t *client;
67         int stats[MAX_CL_STATS];
68
69         if (!host_client->prespawned)
70         {
71                 Con_Print("Spawn not valid -- not yet prespawned\n");
72                 return;
73         }
74         if (host_client->spawned)
75         {
76                 Con_Print("Spawn not valid -- already spawned\n");
77                 return;
78         }
79         host_client->spawned = true;
80
81         // reset name change timer again because they might want to change name
82         // again in the first 5 seconds after connecting
83         host_client->nametime = 0;
84
85         // LadyHavoc: moved this above the QC calls at FrikaC's request
86         // LadyHavoc: commented this out
87         //if (host_client->netconnection)
88         //      SZ_Clear (&host_client->netconnection->message);
89
90         // run the entrance script
91         if (sv.loadgame)
92         {
93                 // loaded games are fully initialized already
94                 if (PRVM_serverfunction(RestoreGame))
95                 {
96                         Con_DPrint("Calling RestoreGame\n");
97                         PRVM_serverglobalfloat(time) = sv.time;
98                         PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
99                         prog->ExecuteProgram(prog, PRVM_serverfunction(RestoreGame), "QC function RestoreGame is missing");
100                 }
101         }
102         else
103         {
104                 //Con_Printf("SV_Spawn_f: host_client->edict->netname = %s, host_client->edict->netname = %s, host_client->name = %s\n", PRVM_GetString(PRVM_serveredictstring(host_client->edict, netname)), PRVM_GetString(PRVM_serveredictstring(host_client->edict, netname)), host_client->name);
105
106                 // copy spawn parms out of the client_t
107                 for (i=0 ; i< NUM_SPAWN_PARMS ; i++)
108                         (&PRVM_serverglobalfloat(parm1))[i] = host_client->spawn_parms[i];
109
110                 // call the spawn function
111                 host_client->clientconnectcalled = true;
112                 PRVM_serverglobalfloat(time) = sv.time;
113                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
114                 prog->ExecuteProgram(prog, PRVM_serverfunction(ClientConnect), "QC function ClientConnect is missing");
115
116                 Con_Printf("%s connected\n", host_client->name);
117
118                 PRVM_serverglobalfloat(time) = sv.time;
119                 prog->ExecuteProgram(prog, PRVM_serverfunction(PutClientInServer), "QC function PutClientInServer is missing");
120         }
121
122         if (!host_client->netconnection)
123                 return;
124
125         // send time of update
126         MSG_WriteByte (&host_client->netconnection->message, svc_time);
127         MSG_WriteFloat (&host_client->netconnection->message, sv.time);
128
129         // send all current names, colors, and frag counts
130         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
131         {
132                 if (!client->active)
133                         continue;
134                 MSG_WriteByte (&host_client->netconnection->message, svc_updatename);
135                 MSG_WriteByte (&host_client->netconnection->message, i);
136                 MSG_WriteString (&host_client->netconnection->message, client->name);
137                 MSG_WriteByte (&host_client->netconnection->message, svc_updatefrags);
138                 MSG_WriteByte (&host_client->netconnection->message, i);
139                 MSG_WriteShort (&host_client->netconnection->message, client->frags);
140                 MSG_WriteByte (&host_client->netconnection->message, svc_updatecolors);
141                 MSG_WriteByte (&host_client->netconnection->message, i);
142                 MSG_WriteByte (&host_client->netconnection->message, client->colors);
143         }
144
145         // send all current light styles
146         for (i=0 ; i<MAX_LIGHTSTYLES ; i++)
147         {
148                 if (sv.lightstyles[i][0])
149                 {
150                         MSG_WriteByte (&host_client->netconnection->message, svc_lightstyle);
151                         MSG_WriteByte (&host_client->netconnection->message, (char)i);
152                         MSG_WriteString (&host_client->netconnection->message, sv.lightstyles[i]);
153                 }
154         }
155
156         // send some stats
157         MSG_WriteByte (&host_client->netconnection->message, svc_updatestat);
158         MSG_WriteByte (&host_client->netconnection->message, STAT_TOTALSECRETS);
159         MSG_WriteLong (&host_client->netconnection->message, (int)PRVM_serverglobalfloat(total_secrets));
160
161         MSG_WriteByte (&host_client->netconnection->message, svc_updatestat);
162         MSG_WriteByte (&host_client->netconnection->message, STAT_TOTALMONSTERS);
163         MSG_WriteLong (&host_client->netconnection->message, (int)PRVM_serverglobalfloat(total_monsters));
164
165         MSG_WriteByte (&host_client->netconnection->message, svc_updatestat);
166         MSG_WriteByte (&host_client->netconnection->message, STAT_SECRETS);
167         MSG_WriteLong (&host_client->netconnection->message, (int)PRVM_serverglobalfloat(found_secrets));
168
169         MSG_WriteByte (&host_client->netconnection->message, svc_updatestat);
170         MSG_WriteByte (&host_client->netconnection->message, STAT_MONSTERS);
171         MSG_WriteLong (&host_client->netconnection->message, (int)PRVM_serverglobalfloat(killed_monsters));
172
173         // send a fixangle
174         // Never send a roll angle, because savegames can catch the server
175         // in a state where it is expecting the client to correct the angle
176         // and it won't happen if the game was just loaded, so you wind up
177         // with a permanent head tilt
178         if (sv.loadgame)
179         {
180                 MSG_WriteByte (&host_client->netconnection->message, svc_setangle);
181                 MSG_WriteAngle (&host_client->netconnection->message, PRVM_serveredictvector(host_client->edict, v_angle)[0], sv.protocol);
182                 MSG_WriteAngle (&host_client->netconnection->message, PRVM_serveredictvector(host_client->edict, v_angle)[1], sv.protocol);
183                 MSG_WriteAngle (&host_client->netconnection->message, 0, sv.protocol);
184         }
185         else
186         {
187                 MSG_WriteByte (&host_client->netconnection->message, svc_setangle);
188                 MSG_WriteAngle (&host_client->netconnection->message, PRVM_serveredictvector(host_client->edict, angles)[0], sv.protocol);
189                 MSG_WriteAngle (&host_client->netconnection->message, PRVM_serveredictvector(host_client->edict, angles)[1], sv.protocol);
190                 MSG_WriteAngle (&host_client->netconnection->message, 0, sv.protocol);
191         }
192
193         SV_WriteClientdataToMessage (host_client, host_client->edict, &host_client->netconnection->message, stats);
194
195         MSG_WriteByte (&host_client->netconnection->message, svc_signonnum);
196         MSG_WriteByte (&host_client->netconnection->message, 3);
197 }
198
199 /*
200 ==================
201 SV_Begin_f
202 ==================
203 */
204 void SV_Begin_f(cmd_state_t *cmd)
205 {
206         if (!host_client->spawned)
207         {
208                 Con_Print("Begin not valid -- not yet spawned\n");
209                 return;
210         }
211         if (host_client->begun)
212         {
213                 Con_Print("Begin not valid -- already begun\n");
214                 return;
215         }
216         host_client->begun = true;
217
218         // LadyHavoc: note: this code also exists in SV_DropClient
219         if (sv.loadgame)
220         {
221                 int i;
222                 for (i = 0;i < svs.maxclients;i++)
223                         if (svs.clients[i].active && !svs.clients[i].spawned)
224                                 break;
225                 if (i == svs.maxclients)
226                 {
227                         Con_Printf("Loaded game, everyone rejoined - unpausing\n");
228                         sv.paused = sv.loadgame = false; // we're basically done with loading now
229                 }
230         }
231 }
232
233 /*
234 ===============
235 SV_SetIdealPitch
236 ===============
237 */
238 #define MAX_FORWARD     6
239 void SV_SetIdealPitch (void)
240 {
241         prvm_prog_t *prog = SVVM_prog;
242         float   angleval, sinval, cosval, step, dir;
243         trace_t tr;
244         vec3_t  top, bottom;
245         float   z[MAX_FORWARD];
246         int             i, j;
247         int             steps;
248
249         if (!((int)PRVM_serveredictfloat(host_client->edict, flags) & FL_ONGROUND))
250                 return;
251
252         angleval = PRVM_serveredictvector(host_client->edict, angles)[YAW] * M_PI*2 / 360;
253         sinval = sin(angleval);
254         cosval = cos(angleval);
255
256         for (i=0 ; i<MAX_FORWARD ; i++)
257         {
258                 top[0] = PRVM_serveredictvector(host_client->edict, origin)[0] + cosval*(i+3)*12;
259                 top[1] = PRVM_serveredictvector(host_client->edict, origin)[1] + sinval*(i+3)*12;
260                 top[2] = PRVM_serveredictvector(host_client->edict, origin)[2] + PRVM_serveredictvector(host_client->edict, view_ofs)[2];
261
262                 bottom[0] = top[0];
263                 bottom[1] = top[1];
264                 bottom[2] = top[2] - 160;
265
266                 tr = SV_TraceLine(top, bottom, MOVE_NOMONSTERS, host_client->edict, SUPERCONTENTS_SOLID, 0, 0, collision_extendmovelength.value);
267                 // if looking at a wall, leave ideal the way is was
268                 if (tr.startsolid)
269                         return;
270
271                 // near a dropoff
272                 if (tr.fraction == 1)
273                         return;
274
275                 z[i] = top[2] + tr.fraction*(bottom[2]-top[2]);
276         }
277
278         dir = 0;
279         steps = 0;
280         for (j=1 ; j<i ; j++)
281         {
282                 step = z[j] - z[j-1];
283                 if (step > -ON_EPSILON && step < ON_EPSILON)
284                         continue;
285
286                 // mixed changes
287                 if (dir && ( step-dir > ON_EPSILON || step-dir < -ON_EPSILON ) )
288                         return;
289
290                 steps++;
291                 dir = step;
292         }
293
294         if (!dir)
295         {
296                 PRVM_serveredictfloat(host_client->edict, idealpitch) = 0;
297                 return;
298         }
299
300         if (steps < 2)
301                 return;
302         PRVM_serveredictfloat(host_client->edict, idealpitch) = -dir * sv_idealpitchscale.value;
303 }
304
305 static vec3_t wishdir, forward, right, up;
306 static float wishspeed;
307
308 static qbool onground;
309
310 /*
311 ==================
312 SV_UserFriction
313
314 ==================
315 */
316 static void SV_UserFriction (void)
317 {
318         prvm_prog_t *prog = SVVM_prog;
319         float speed, newspeed, control, friction;
320         vec3_t start, stop;
321         trace_t trace;
322
323         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]);
324         if (!speed)
325                 return;
326
327         // if the leading edge is over a dropoff, increase friction
328         start[0] = stop[0] = PRVM_serveredictvector(host_client->edict, origin)[0] + PRVM_serveredictvector(host_client->edict, velocity)[0]/speed*16;
329         start[1] = stop[1] = PRVM_serveredictvector(host_client->edict, origin)[1] + PRVM_serveredictvector(host_client->edict, velocity)[1]/speed*16;
330         start[2] = PRVM_serveredictvector(host_client->edict, origin)[2] + PRVM_serveredictvector(host_client->edict, mins)[2];
331         stop[2] = start[2] - 34;
332
333         trace = SV_TraceLine(start, stop, MOVE_NOMONSTERS, host_client->edict, SV_GenericHitSuperContentsMask(host_client->edict), 0, 0, collision_extendmovelength.value);
334
335         if (trace.fraction == 1.0)
336                 friction = sv_friction.value*sv_edgefriction.value;
337         else
338                 friction = sv_friction.value;
339
340         // apply friction
341         control = speed < sv_stopspeed.value ? sv_stopspeed.value : speed;
342         newspeed = speed - sv.frametime*control*friction;
343
344         if (newspeed < 0)
345                 newspeed = 0;
346         else
347                 newspeed /= speed;
348
349         VectorScale(PRVM_serveredictvector(host_client->edict, velocity), newspeed, PRVM_serveredictvector(host_client->edict, velocity));
350 }
351
352 /*
353 ==============
354 SV_Accelerate
355 ==============
356 */
357 static void SV_Accelerate (void)
358 {
359         prvm_prog_t *prog = SVVM_prog;
360         int i;
361         float addspeed, accelspeed, currentspeed;
362
363         currentspeed = DotProduct (PRVM_serveredictvector(host_client->edict, velocity), wishdir);
364         addspeed = wishspeed - currentspeed;
365         if (addspeed <= 0)
366                 return;
367         accelspeed = sv_accelerate.value*sv.frametime*wishspeed;
368         if (accelspeed > addspeed)
369                 accelspeed = addspeed;
370
371         for (i=0 ; i<3 ; i++)
372                 PRVM_serveredictvector(host_client->edict, velocity)[i] += accelspeed*wishdir[i];
373 }
374
375 extern cvar_t sv_gameplayfix_q2airaccelerate;
376 static void SV_AirAccelerate (vec3_t wishveloc)
377 {
378         prvm_prog_t *prog = SVVM_prog;
379         int i;
380         float addspeed, wishspd, accelspeed, currentspeed;
381
382         wishspd = VectorNormalizeLength (wishveloc);
383         if (wishspd > sv_maxairspeed.value)
384                 wishspd = sv_maxairspeed.value;
385         currentspeed = DotProduct (PRVM_serveredictvector(host_client->edict, velocity), wishveloc);
386         addspeed = wishspd - currentspeed;
387         if (addspeed <= 0)
388                 return;
389         accelspeed = (sv_airaccelerate.value < 0 ? sv_accelerate.value : sv_airaccelerate.value)*(sv_gameplayfix_q2airaccelerate.integer ? wishspd : wishspeed) * sv.frametime;
390         if (accelspeed > addspeed)
391                 accelspeed = addspeed;
392
393         for (i=0 ; i<3 ; i++)
394                 PRVM_serveredictvector(host_client->edict, velocity)[i] += accelspeed*wishveloc[i];
395 }
396
397
398 static void DropPunchAngle (void)
399 {
400         prvm_prog_t *prog = SVVM_prog;
401         vec_t len;
402         vec3_t punchangle, punchvector;
403
404         VectorCopy(PRVM_serveredictvector(host_client->edict, punchangle), punchangle);
405         VectorCopy(PRVM_serveredictvector(host_client->edict, punchvector), punchvector);
406
407         len = VectorNormalizeLength(punchangle);
408         if (len > 0)
409         {
410                 len -= 10*sv.frametime;
411                 if (len < 0)
412                         len = 0;
413                 VectorScale(punchangle, len, punchangle);
414         }
415
416         len = VectorNormalizeLength(punchvector);
417         if (len > 0)
418         {
419                 len -= 20*sv.frametime;
420                 if (len < 0)
421                         len = 0;
422                 VectorScale(punchvector, len, punchvector);
423         }
424
425         VectorCopy(punchangle, PRVM_serveredictvector(host_client->edict, punchangle));
426         VectorCopy(punchvector, PRVM_serveredictvector(host_client->edict, punchvector));
427 }
428
429 /*
430 ===================
431 SV_WaterMove
432
433 ===================
434 */
435 static void SV_WaterMove (void)
436 {
437         prvm_prog_t *prog = SVVM_prog;
438         int i;
439         vec3_t wishvel, v_angle;
440         vec_t speed, newspeed, fwishspeed, addspeed, accelspeed, temp;
441
442         // user intentions
443         VectorCopy(PRVM_serveredictvector(host_client->edict, v_angle), v_angle);
444         AngleVectors(v_angle, forward, right, up);
445
446         for (i=0 ; i<3 ; i++)
447                 wishvel[i] = forward[i]*usercmd.forwardmove + right[i]*usercmd.sidemove;
448
449         if (!usercmd.forwardmove && !usercmd.sidemove && !usercmd.upmove)
450                 wishvel[2] -= 60;               // drift towards bottom
451         else
452                 wishvel[2] += usercmd.upmove;
453
454         fwishspeed = VectorLength(wishvel);
455         if (fwishspeed > sv_maxspeed.value)
456         {
457                 temp = sv_maxspeed.value/fwishspeed;
458                 VectorScale (wishvel, temp, wishvel);
459                 fwishspeed = sv_maxspeed.value;
460         }
461         fwishspeed *= 0.7;
462
463         // water friction
464         speed = VectorLength(PRVM_serveredictvector(host_client->edict, velocity));
465         if (speed)
466         {
467                 newspeed = speed - sv.frametime * speed * (sv_waterfriction.value < 0 ? sv_friction.value : sv_waterfriction.value);
468                 if (newspeed < 0)
469                         newspeed = 0;
470                 temp = newspeed/speed;
471                 VectorScale(PRVM_serveredictvector(host_client->edict, velocity), temp, PRVM_serveredictvector(host_client->edict, velocity));
472         }
473         else
474                 newspeed = 0;
475
476         // water acceleration
477         if (!fwishspeed)
478                 return;
479
480         addspeed = fwishspeed - newspeed;
481         if (addspeed <= 0)
482                 return;
483
484         VectorNormalize (wishvel);
485         accelspeed = (sv_wateraccelerate.value < 0 ? sv_accelerate.value : sv_wateraccelerate.value) * fwishspeed * sv.frametime;
486         if (accelspeed > addspeed)
487                 accelspeed = addspeed;
488
489         for (i=0 ; i<3 ; i++)
490                 PRVM_serveredictvector(host_client->edict, velocity)[i] += accelspeed * wishvel[i];
491 }
492
493 static void SV_WaterJump (void)
494 {
495         prvm_prog_t *prog = SVVM_prog;
496         if (sv.time > PRVM_serveredictfloat(host_client->edict, teleport_time) || !PRVM_serveredictfloat(host_client->edict, waterlevel))
497         {
498                 PRVM_serveredictfloat(host_client->edict, flags) = (int)PRVM_serveredictfloat(host_client->edict, flags) & ~FL_WATERJUMP;
499                 PRVM_serveredictfloat(host_client->edict, teleport_time) = 0;
500         }
501         PRVM_serveredictvector(host_client->edict, velocity)[0] = PRVM_serveredictvector(host_client->edict, movedir)[0];
502         PRVM_serveredictvector(host_client->edict, velocity)[1] = PRVM_serveredictvector(host_client->edict, movedir)[1];
503 }
504
505
506 /*
507 ===================
508 SV_AirMove
509
510 ===================
511 */
512 static void SV_AirMove (void)
513 {
514         prvm_prog_t *prog = SVVM_prog;
515         int i;
516         vec3_t wishvel;
517         float fmove, smove, temp;
518
519         // LadyHavoc: correct quake movement speed bug when looking up/down
520         wishvel[0] = wishvel[2] = 0;
521         wishvel[1] = PRVM_serveredictvector(host_client->edict, angles)[1];
522         AngleVectors (wishvel, forward, right, up);
523
524         fmove = usercmd.forwardmove;
525         smove = usercmd.sidemove;
526
527 // hack to not let you back into teleporter
528         if (sv.time < PRVM_serveredictfloat(host_client->edict, teleport_time) && fmove < 0)
529                 fmove = 0;
530
531         for (i=0 ; i<3 ; i++)
532                 wishvel[i] = forward[i]*fmove + right[i]*smove;
533
534         if ((int)PRVM_serveredictfloat(host_client->edict, movetype) != MOVETYPE_WALK)
535                 wishvel[2] += usercmd.upmove;
536
537         VectorCopy (wishvel, wishdir);
538         wishspeed = VectorNormalizeLength(wishdir);
539         if (wishspeed > sv_maxspeed.value)
540         {
541                 temp = sv_maxspeed.value/wishspeed;
542                 VectorScale (wishvel, temp, wishvel);
543                 wishspeed = sv_maxspeed.value;
544         }
545
546         if (PRVM_serveredictfloat(host_client->edict, movetype) == MOVETYPE_NOCLIP)
547         {
548                 // noclip
549                 VectorCopy (wishvel, PRVM_serveredictvector(host_client->edict, velocity));
550         }
551         else if (onground)
552         {
553                 SV_UserFriction ();
554                 SV_Accelerate ();
555         }
556         else
557         {
558                 // not on ground, so little effect on velocity
559                 SV_AirAccelerate (wishvel);
560         }
561 }
562
563 /*
564 ===================
565 SV_PlayerPhysics
566
567 the move fields specify an intended velocity in pix/sec
568 the angle fields specify an exact angular motion in degrees
569 ===================
570 */
571 void SV_PlayerPhysics (void)
572 {
573         prvm_prog_t *prog = SVVM_prog;
574         vec3_t v_angle, angles, velocity;
575
576         //Con_Printf("clientthink for %ims\n", (int) (sv.frametime * 1000));
577
578         SV_ApplyClientMove();
579         // make sure the velocity is sane (not a NaN)
580         SV_CheckVelocity(host_client->edict);
581
582         // LadyHavoc: QuakeC replacement for SV_PlayerPhysics (player movement)
583         if (PRVM_serverfunction(SV_PlayerPhysics) && sv_playerphysicsqc.integer)
584         {
585                 PRVM_serverglobalfloat(time) = sv.time;
586                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
587                 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PlayerPhysics), "QC function SV_PlayerPhysics is missing");
588                 SV_CheckVelocity(host_client->edict);
589                 return;
590         }
591
592         if (PRVM_serveredictfloat(host_client->edict, movetype) == MOVETYPE_NONE)
593                 return;
594
595         onground = ((int)PRVM_serveredictfloat(host_client->edict, flags) & FL_ONGROUND) != 0;
596
597         DropPunchAngle ();
598
599         // if dead, behave differently
600         if (PRVM_serveredictfloat(host_client->edict, health) <= 0)
601                 return;
602
603         usercmd = host_client->cmd;
604
605         // angles
606         // show 1/3 the pitch angle and all the roll angle
607         VectorAdd (PRVM_serveredictvector(host_client->edict, v_angle), PRVM_serveredictvector(host_client->edict, punchangle), v_angle);
608         VectorCopy(PRVM_serveredictvector(host_client->edict, angles), angles);
609         VectorCopy(PRVM_serveredictvector(host_client->edict, velocity), velocity);
610         PRVM_serveredictvector(host_client->edict, angles)[ROLL] = Com_CalcRoll (angles, velocity, sv_rollangle.value, sv_rollspeed.value)*4;
611         if (!PRVM_serveredictfloat(host_client->edict, fixangle))
612         {
613                 PRVM_serveredictvector(host_client->edict, angles)[PITCH] = -v_angle[PITCH]/3;
614                 PRVM_serveredictvector(host_client->edict, angles)[YAW] = v_angle[YAW];
615         }
616
617         if ( (int)PRVM_serveredictfloat(host_client->edict, flags) & FL_WATERJUMP )
618         {
619                 SV_WaterJump ();
620                 SV_CheckVelocity(host_client->edict);
621                 return;
622         }
623
624         // walk
625         if ((PRVM_serveredictfloat(host_client->edict, waterlevel) >= 2) && (PRVM_serveredictfloat(host_client->edict, movetype) != MOVETYPE_NOCLIP))
626         {
627                 SV_WaterMove ();
628                 SV_CheckVelocity(host_client->edict);
629                 return;
630         }
631
632         SV_AirMove ();
633         SV_CheckVelocity(host_client->edict);
634 }
635
636 /*
637 ===================
638 SV_ReadClientMove
639 ===================
640 */
641 int sv_numreadmoves = 0;
642 usercmd_t sv_readmoves[CL_MAX_USERCMDS];
643 static void SV_ReadClientMove (void)
644 {
645         prvm_prog_t *prog = SVVM_prog;
646         int i;
647         usercmd_t newmove;
648         usercmd_t *move = &newmove;
649
650         memset(move, 0, sizeof(*move));
651
652         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
653
654         // read ping time
655         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)
656                 move->sequence = MSG_ReadLong(&sv_message);
657         move->time = MSG_ReadFloat(&sv_message);
658         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
659         move->receivetime = (float)sv.time;
660
661 #if DEBUGMOVES
662         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);
663 #endif
664         // limit reported time to current time
665         // (incase the client is trying to cheat)
666         move->time = min(move->time, sv.time + sv.frametime);
667
668         // read current angles
669         for (i = 0;i < 3;i++)
670         {
671                 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)
672                         move->viewangles[i] = MSG_ReadAngle8i(&sv_message);
673                 else if (sv.protocol == PROTOCOL_DARKPLACES1)
674                         move->viewangles[i] = MSG_ReadAngle16i(&sv_message);
675                 else if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
676                         move->viewangles[i] = MSG_ReadAngle32f(&sv_message);
677                 else
678                         move->viewangles[i] = MSG_ReadAngle16i(&sv_message);
679         }
680         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
681
682         // read movement
683         move->forwardmove = MSG_ReadCoord16i(&sv_message);
684         move->sidemove = MSG_ReadCoord16i(&sv_message);
685         move->upmove = MSG_ReadCoord16i(&sv_message);
686         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
687
688         // read buttons
689         // be sure to bitwise OR them into the move->buttons because we want to
690         // accumulate button presses from multiple packets per actual move
691         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)
692                 move->buttons = MSG_ReadByte(&sv_message);
693         else
694                 move->buttons = MSG_ReadLong(&sv_message);
695         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
696
697         // read impulse
698         move->impulse = MSG_ReadByte(&sv_message);
699         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
700
701         // PRYDON_CLIENTCURSOR
702         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)
703         {
704                 // 30 bytes
705                 move->cursor_screen[0] = MSG_ReadShort(&sv_message) * (1.0f / 32767.0f);
706                 move->cursor_screen[1] = MSG_ReadShort(&sv_message) * (1.0f / 32767.0f);
707                 move->cursor_start[0] = MSG_ReadFloat(&sv_message);
708                 move->cursor_start[1] = MSG_ReadFloat(&sv_message);
709                 move->cursor_start[2] = MSG_ReadFloat(&sv_message);
710                 move->cursor_impact[0] = MSG_ReadFloat(&sv_message);
711                 move->cursor_impact[1] = MSG_ReadFloat(&sv_message);
712                 move->cursor_impact[2] = MSG_ReadFloat(&sv_message);
713                 move->cursor_entitynumber = (unsigned short)MSG_ReadShort(&sv_message);
714                 if (move->cursor_entitynumber >= prog->max_edicts)
715                 {
716                         Con_DPrintf("SV_ReadClientMessage: client send bad cursor_entitynumber\n");
717                         move->cursor_entitynumber = 0;
718                 }
719                 // as requested by FrikaC, cursor_trace_ent is reset to world if the
720                 // entity is free at time of receipt
721                 if (PRVM_EDICT_NUM(move->cursor_entitynumber)->priv.server->free)
722                         move->cursor_entitynumber = 0;
723                 if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
724         }
725
726         // if the previous move has not been applied yet, we need to accumulate
727         // the impulse/buttons from it
728         if (!host_client->cmd.applied)
729         {
730                 if (!move->impulse)
731                         move->impulse = host_client->cmd.impulse;
732                 move->buttons |= host_client->cmd.buttons;
733         }
734
735         // now store this move for later execution
736         // (we have to buffer the moves because of old ones being repeated)
737         if (sv_numreadmoves < CL_MAX_USERCMDS)
738                 sv_readmoves[sv_numreadmoves++] = *move;
739
740         // movement packet loss tracking
741         // bones_was_here: checking begun prevents heavy loss detection right after a map change
742         if(move->sequence && host_client->begun)
743         {
744                 if(move->sequence > host_client->movement_highestsequence_seen)
745                 {
746                         if(host_client->movement_highestsequence_seen)
747                         {
748                                 // mark moves in between as lost
749                                 unsigned int delta = move->sequence - host_client->movement_highestsequence_seen - 1;
750                                 if(delta < NETGRAPH_PACKETS)
751                                 {
752                                         unsigned int u;
753                                         for(u = 0; u < delta; ++u)
754                                                 host_client->movement_count[(host_client->movement_highestsequence_seen + 1 + u) % NETGRAPH_PACKETS] = -1;
755                                 }
756                                 else
757                                         memset(host_client->movement_count, -1, sizeof(host_client->movement_count));
758                         }
759                         // mark THIS move as seen for the first time
760                         host_client->movement_count[move->sequence % NETGRAPH_PACKETS] = 1;
761                         // update highest sequence seen
762                         host_client->movement_highestsequence_seen = move->sequence;
763                 }
764                 else
765                         if(host_client->movement_count[move->sequence % NETGRAPH_PACKETS] >= 0)
766                                 ++host_client->movement_count[move->sequence % NETGRAPH_PACKETS];
767         }
768         else
769         {
770                 host_client->movement_highestsequence_seen = 0;
771                 memset(host_client->movement_count, 0, sizeof(host_client->movement_count));
772         }
773 }
774
775 static void SV_ExecuteAsyncMove(usercmd_t *move)
776 {
777         prvm_prog_t *prog = SVVM_prog;
778
779         double qcframetime = PRVM_serverglobalfloat(frametime);
780         double svframetime = sv.frametime;
781
782         host_client->cmd = *move;
783         host_client->movesequence = move->sequence;
784
785         if (sv_clmovement_buffer.integer)
786         {
787                 // TODO can this break when paused? should we use sys_ticrate.value instead or just check sv.frametime?
788                 // FIXME if the client has exactly half the server's framerate and never fluctuates at allow
789                 // the amount of buffered moves never decreases
790                 // happens when enabling buffer during a match with a client already running exactly half hz
791                 // hack: could do a FLT_MIN (or bigger) offset so its doing slightly more frametime on the first one ?
792                 // or just do enough extra on the first one that subsequent ones are == sv.frametime ?
793                 if (move->frametime >= 2 * sv.frametime && sv.frametime > 0.0)
794                 {
795 //                      Con_Printf("Splitting a move in %d! ", (int)floor(move->frametime / sv.frametime));
796                         host_client->cmd.frametime /= floor(move->frametime / sv.frametime);
797                         move->frametime -= host_client->cmd.frametime;
798 //                      Con_Printf("shortened frametime: %f stored remainder: %f\n", host_client->cmd.frametime, move->frametime);
799                 }
800                 else
801                         host_client->mvbuf_r++;
802
803                 host_client->frametime_accum += host_client->cmd.frametime;
804         }
805
806         // if using prediction, we need to perform moves when packets are
807         // received, even if multiple occur in one frame
808         // (they can't go beyond the current time so there is no cheat issue
809         //  with this approach, and if they don't send input for a while they
810         //  start moving anyway, so the longest 'lagaport' possible is
811         //  determined by the sv_clmovement_inputtimeout cvar)
812
813         // update ping time for qc to see while executing this move
814         host_client->ping = host_client->cmd.receivetime - host_client->cmd.time;
815         // the server and qc frametime values must be changed temporarily
816         PRVM_serverglobalfloat(frametime) = sv.frametime = host_client->cmd.frametime;
817         // if move is more than 50ms, split it into two moves (this matches QWSV behavior and the client prediction)
818         if (sv.frametime > 0.05)
819         {
820                 PRVM_serverglobalfloat(frametime) = sv.frametime = host_client->cmd.frametime * 0.5;
821                 SV_Physics_ClientMove();
822         }
823         SV_Physics_ClientMove();
824         sv.frametime = svframetime;
825         PRVM_serverglobalfloat(frametime) = qcframetime;
826         host_client->clmovement_inputtimeout = min(0.1, sv_clmovement_inputtimeout.value);
827 }
828
829 inline void SV_ExecuteBufferedAsyncMoves(void)
830 {
831         unsigned char i = 0;
832         for (host_client = &svs.clients[0]; i < svs.maxclients; i++, host_client++)
833         {
834 //              if (host_client->begun)
835 //                      Con_Printf("Buffered moves: %d\n", (unsigned char)(host_client->mvbuf_w - host_client->mvbuf_r));
836
837                 host_client->frametime_accum = 0.0;
838                 while (host_client->frametime_accum < sv.frametime && host_client->mvbuf_w != host_client->mvbuf_r)
839                         SV_ExecuteAsyncMove(&host_client->mvbuf[MVBUF_MASK(host_client->mvbuf_r)]);
840         }
841 }
842
843 static void SV_ExecuteClientMoves(void)
844 {
845         prvm_prog_t *prog = SVVM_prog;
846         int moveindex;
847 //      double moveframetime;
848 //      double oldframetime;
849 //      double oldframetime2;
850
851         if (sv_numreadmoves < 1)
852                 return;
853         // only start accepting input once the player is spawned
854         if (!host_client->begun)
855                 return;
856 #if DEBUGMOVES
857         Con_Printf("SV_ExecuteClientMoves: read %i moves at sv.time %f\n", sv_numreadmoves, (float)sv.time);
858 #endif
859
860         // update ping time
861         host_client->ping = max(sv_readmoves[sv_numreadmoves-1].receivetime - sv_readmoves[sv_numreadmoves-1].time, 0);
862
863         // disable clientside movement prediction in some cases
864         if (host_client->ping * 1000.0 < sv_clmovement_minping.value || host_client->ping > 0.3)
865                 host_client->clmovement_disabletimeout = host.realtime + sv_clmovement_minping_disabletime.value / 1000.0;
866         // several conditions govern whether clientside movement prediction is allowed
867         if (sv_readmoves[sv_numreadmoves-1].sequence && sv_clmovement_enable.integer && sv_clmovement_inputtimeout.value > 0 && host_client->clmovement_disabletimeout <= host.realtime && (PRVM_serveredictfloat(host_client->edict, disableclientprediction) == -1 || (PRVM_serveredictfloat(host_client->edict, movetype) == MOVETYPE_WALK && (!PRVM_serveredictfloat(host_client->edict, disableclientprediction)))))
868         {
869                 // process the moves in order and ignore old ones
870                 // but always trust the latest move
871                 // (this deals with bogus initial move sequences after level change,
872                 //  where the client will eventually catch up with the level change
873                 //  and reset its move sequence)
874                 for (moveindex = 0;moveindex < sv_numreadmoves;moveindex++)
875                 {
876                         usercmd_t *move = sv_readmoves + moveindex;
877                         if (host_client->movesequence < move->sequence || moveindex == sv_numreadmoves - 1)
878                         {
879                                 // this is a new move
880
881 /*                              usercmd_t *prevmove;
882                                 // TODO is it correct to check host_client->movesequence here ?!?
883                                 // movesequence set means prev executed move was async
884                                 // but not necessarily that buffered mode was enabled
885                                 // could compare movesequence to most recently read buffered move's sequence ?
886                                 if (sv_clmovement_buffer.integer && host_client->movesequence)
887                                         prevmove = &host_client->mvbuf[MVBUF_MASK(host_client->mvbuf_w - 1)];
888                                 else
889                                         prevmove = &host_client->cmd; */
890 #if DEBUGMOVES
891                                 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);
892 #endif
893 //                              if (move->time > sv.time)
894 //                                      Con_Printf("move->time exceeded sv.time by %f\n", move->time - sv.time);
895 //                              if (move->time < oldmove->time)
896 //                                      Con_Printf("time stepped back by %f\n", oldmove->time - move->time);
897
898                                 // not required as we limit to sv.time + sv.frametime in SV_ReadClientMove and fall back to sync phys if too old
899 //                              move->time = bound(sv.time - 1, move->time, sv.time); // prevent slowhack/speedhack combos
900                                 // also not required: if move->time was older than oldmove->time
901                                 // move->frametime will be < 0 and the move will be discarded
902 //                              move->time = max(move->time, oldmove->time); // prevent backstepping of time
903
904                                 // FIXME frametime of next move to arrive will be different to client's pred if we have prevented backstepping
905
906                                 move->frametime = move->time - max(host_client->cmd.time, host_client->mvbuf[MVBUF_MASK(host_client->mvbuf_w - 1)].time);
907
908 //                              if (move->frametime >= 0.05)
909 //                                      Con_Printf("Long move frametime: %f\n", move->frametime);
910
911                                 if (sv_clmovement_inputtimeout_correct.integer && host_client->clmovement_inputtimeout_accum)
912                                 {
913                                         if (move->frametime > host_client->clmovement_inputtimeout_accum)
914                                         {
915 //                                              Con_Printf("Shortening move frametime after %f inputtimeout, was %f, now %f\n", host_client->clmovement_inputtimeout_accum, move->frametime, move->frametime - host_client->clmovement_inputtimeout_accum);
916                                                 move->frametime -= host_client->clmovement_inputtimeout_accum;
917                                                 host_client->clmovement_inputtimeout_accum = 0.0f;
918                                         }
919                                         else
920                                         {
921 //                                              Con_Printf("Shortening move frametime after %f inputtimeout, was %f, now 0.0\n", host_client->clmovement_inputtimeout_accum, move->frametime);
922                                                 host_client->clmovement_inputtimeout_accum -= move->frametime;
923                                                 move->frametime = 0.0;
924                                         }
925                                 }
926
927                                 // discard (treat like lost) moves with too low distance from
928                                 // the previous one to prevent hacks using float inaccuracy
929                                 // clients will see this as packet loss in the netgraph
930                                 // this should also apply if a move cannot get
931                                 // executed because it came too late and
932                                 // already was performed serverside
933                                 if(move->frametime < 0.0005)
934                                 {
935                                         // count the move as LOST if we don't
936                                         // execute it but it has higher
937                                         // sequence count
938                                         if(host_client->movesequence)
939                                                 if(move->sequence > host_client->movesequence && sv_clmovement_noisy.integer)
940                                                         host_client->movement_count[(move->sequence) % NETGRAPH_PACKETS] = -1;
941 //                                      Con_Printf("Discarding move with frametime %f\n", move->frametime);
942                                         continue;
943                                         // TODO can we somehow apply only the impulses and buttons?
944                                         // there's code for accumulating them into the next move to arrive
945                                         // currently this only happens for explicit sync physics as it relies on the move being copied to host_client->cmd
946                                 }
947
948                                 // bones_was_here: limit moveframetime to a multiple of sv.frametime to match inputtimeout behaviour
949                                 if (!sv_clmovement_inputtimeout_correct.integer)
950                                         move->frametime = min(move->frametime, min(0.1, sys_ticrate.value > 0.0 && sv.frametime > 0.0 ? sv.frametime * ceil(sv_clmovement_inputtimeout.value / sv.frametime) : sv_clmovement_inputtimeout.value));
951                                 else
952                                         move->frametime = min(move->frametime, 0.1);
953
954                                 //Con_Printf("movesequence = %i (%i lost), moveframetime = %f\n", move->sequence, move->sequence ? move->sequence - host_client->movesequence - 1 : 0, moveframetime);
955
956                                 if (sv_clmovement_buffer.integer)
957                                 {
958                                         // if the buffer is full we are about to overwrite the oldest move
959                                         // log it as lost and increment the read index
960                                         if ((unsigned char)(host_client->mvbuf_w - host_client->mvbuf_r) >= MVBUF_SIZE)
961                                                 host_client->movement_count[(host_client->mvbuf[MVBUF_MASK(host_client->mvbuf_r++)].sequence) % NETGRAPH_PACKETS] = -1;
962
963                                         // store the move and increment the write index
964                                         host_client->mvbuf[MVBUF_MASK(host_client->mvbuf_w++)] = *move;
965
966                                         // if possible, execute the move now
967                                         if (host_client->frametime_accum < sv.frametime)
968                                                 SV_ExecuteAsyncMove(&host_client->mvbuf[MVBUF_MASK(host_client->mvbuf_r)]);
969                                 }
970                                 else
971                                         SV_ExecuteAsyncMove(move);
972
973 /*
974                                 host_client->cmd = *move;
975                                 host_client->movesequence = move->sequence;
976
977                                 // if using prediction, we need to perform moves when packets are
978                                 // received, even if multiple occur in one frame
979                                 // (they can't go beyond the current time so there is no cheat issue
980                                 //  with this approach, and if they don't send input for a while they
981                                 //  start moving anyway, so the longest 'lagaport' possible is
982                                 //  determined by the sv_clmovement_inputtimeout cvar)
983                                 oldframetime = PRVM_serverglobalfloat(frametime);
984                                 oldframetime2 = sv.frametime;
985                                 // update ping time for qc to see while executing this move
986                                 host_client->ping = host_client->cmd.receivetime - host_client->cmd.time;
987                                 // the server and qc frametime values must be changed temporarily
988                                 PRVM_serverglobalfloat(frametime) = sv.frametime = moveframetime;
989                                 // if move is more than 50ms, split it into two moves (this matches QWSV behavior and the client prediction)
990                                 if (sv.frametime > 0.05)
991                                 {
992                                         PRVM_serverglobalfloat(frametime) = sv.frametime = moveframetime * 0.5f;
993                                         SV_Physics_ClientMove();
994                                 }
995                                 SV_Physics_ClientMove();
996                                 sv.frametime = oldframetime2;
997                                 PRVM_serverglobalfloat(frametime) = oldframetime;
998                                 host_client->clmovement_inputtimeout = min(0.1, sv_clmovement_inputtimeout.value);
999 */
1000                         }
1001                 }
1002         }
1003         else
1004         {
1005                 // try to gather button bits from old moves, but only if their time is
1006                 // advancing (ones with the same timestamp can't be trusted)
1007                 for (moveindex = 0;moveindex < sv_numreadmoves-1;moveindex++)
1008                 {
1009                         usercmd_t *move = sv_readmoves + moveindex;
1010                         if (host_client->cmd.time < move->time)
1011                         {
1012                                 sv_readmoves[sv_numreadmoves-1].buttons |= move->buttons;
1013                                 if (move->impulse)
1014                                         sv_readmoves[sv_numreadmoves-1].impulse = move->impulse;
1015                         }
1016                 }
1017                 // now copy the new move
1018                 host_client->cmd = sv_readmoves[sv_numreadmoves-1];
1019 //              host_client->cmd.time = max(host_client->cmd.time, sv.time);
1020                         // physics will run up to sv.time, so allow no predicted moves
1021                         // before that otherwise, there is a speedhack by turning
1022                         // prediction on and off repeatedly on client side because the
1023                         // engine would run BOTH client and server physics for the same
1024                         // time
1025                 host_client->movesequence = 0;
1026                 // make sure that normal physics takes over immediately
1027                 host_client->clmovement_inputtimeout = 0;
1028                 // clear the async move buffer
1029                 host_client->mvbuf_r = host_client->mvbuf_w = 0;
1030                 // update ping time
1031 //              host_client->ping = host_client->cmd.receivetime - sv_readmoves[sv_numreadmoves-1].time;
1032         }
1033 }
1034
1035 void SV_ApplyClientMove (void)
1036 {
1037         prvm_prog_t *prog = SVVM_prog;
1038         usercmd_t *move = &host_client->cmd;
1039         int j, movementloss, packetloss;
1040
1041         if (!move->receivetime)
1042                 return;
1043
1044         // note: a move can be applied multiple times if the client packets are
1045         // not coming as often as the physics is executed, and the move must be
1046         // applied before running qc each time because the id1 qc had a bug where
1047         // it clears self.button2 in PlayerJump, causing pogostick behavior if
1048         // moves are not applied every time before calling qc
1049         move->applied = true;
1050
1051         // set the edict fields
1052         PRVM_serveredictfloat(host_client->edict, button0) = move->buttons & 1;
1053         PRVM_serveredictfloat(host_client->edict, button2) = (move->buttons & 2)>>1;
1054         if (move->impulse)
1055                 PRVM_serveredictfloat(host_client->edict, impulse) = move->impulse;
1056         // only send the impulse to qc once
1057         move->impulse = 0;
1058
1059         movementloss = packetloss = 0;
1060         if(host_client->netconnection)
1061         {
1062                 for (j = 0;j < NETGRAPH_PACKETS;j++)
1063                         if (host_client->netconnection->incoming_netgraph[j].unreliablebytes == NETGRAPH_LOSTPACKET)
1064                                 packetloss++;
1065                 for (j = 0;j < NETGRAPH_PACKETS;j++)
1066                         if (host_client->movement_count[j] < 0)
1067                                 movementloss++;
1068         }
1069
1070         VectorCopy(move->viewangles, PRVM_serveredictvector(host_client->edict, v_angle));
1071         PRVM_serveredictfloat(host_client->edict, button3) = ((move->buttons >> 2) & 1);
1072         PRVM_serveredictfloat(host_client->edict, button4) = ((move->buttons >> 3) & 1);
1073         PRVM_serveredictfloat(host_client->edict, button5) = ((move->buttons >> 4) & 1);
1074         PRVM_serveredictfloat(host_client->edict, button6) = ((move->buttons >> 5) & 1);
1075         PRVM_serveredictfloat(host_client->edict, button7) = ((move->buttons >> 6) & 1);
1076         PRVM_serveredictfloat(host_client->edict, button8) = ((move->buttons >> 7) & 1);
1077         PRVM_serveredictfloat(host_client->edict, button9) = ((move->buttons >> 11) & 1);
1078         PRVM_serveredictfloat(host_client->edict, button10) = ((move->buttons >> 12) & 1);
1079         PRVM_serveredictfloat(host_client->edict, button11) = ((move->buttons >> 13) & 1);
1080         PRVM_serveredictfloat(host_client->edict, button12) = ((move->buttons >> 14) & 1);
1081         PRVM_serveredictfloat(host_client->edict, button13) = ((move->buttons >> 15) & 1);
1082         PRVM_serveredictfloat(host_client->edict, button14) = ((move->buttons >> 16) & 1);
1083         PRVM_serveredictfloat(host_client->edict, button15) = ((move->buttons >> 17) & 1);
1084         PRVM_serveredictfloat(host_client->edict, button16) = ((move->buttons >> 18) & 1);
1085         PRVM_serveredictfloat(host_client->edict, buttonuse) = ((move->buttons >> 8) & 1);
1086         PRVM_serveredictfloat(host_client->edict, buttonchat) = ((move->buttons >> 9) & 1);
1087         PRVM_serveredictfloat(host_client->edict, cursor_active) = ((move->buttons >> 10) & 1);
1088         VectorSet(PRVM_serveredictvector(host_client->edict, movement), move->forwardmove, move->sidemove, move->upmove);
1089         VectorCopy(move->cursor_screen, PRVM_serveredictvector(host_client->edict, cursor_screen));
1090         VectorCopy(move->cursor_start, PRVM_serveredictvector(host_client->edict, cursor_trace_start));
1091         VectorCopy(move->cursor_impact, PRVM_serveredictvector(host_client->edict, cursor_trace_endpos));
1092         PRVM_serveredictedict(host_client->edict, cursor_trace_ent) = PRVM_EDICT_TO_PROG(PRVM_EDICT_NUM(move->cursor_entitynumber));
1093         PRVM_serveredictfloat(host_client->edict, ping) = host_client->ping * 1000.0;
1094         PRVM_serveredictfloat(host_client->edict, ping_packetloss) = packetloss / (float) NETGRAPH_PACKETS;
1095         PRVM_serveredictfloat(host_client->edict, ping_movementloss) = movementloss / (float) NETGRAPH_PACKETS;
1096 }
1097
1098 static qbool SV_FrameLost(int framenum)
1099 {
1100         if (host_client->entitydatabase5)
1101         {
1102                 if (framenum <= host_client->entitydatabase5->latestframenum)
1103                 {
1104                         EntityFrame5_LostFrame(host_client->entitydatabase5, framenum);
1105                         EntityFrameCSQC_LostFrame(host_client, framenum);
1106                         return true;
1107                 }
1108         }
1109         return false;
1110 }
1111
1112 static void SV_FrameAck(int framenum)
1113 {
1114         if (host_client->entitydatabase)
1115                 EntityFrame_AckFrame(host_client->entitydatabase, framenum);
1116         else if (host_client->entitydatabase4)
1117                 EntityFrame4_AckFrame(host_client->entitydatabase4, framenum, true);
1118         else if (host_client->entitydatabase5)
1119                 EntityFrame5_AckFrame(host_client->entitydatabase5, framenum);
1120 }
1121
1122 /*
1123 ===================
1124 SV_ReadClientMessage
1125 ===================
1126 */
1127 void SV_ReadClientMessage(void)
1128 {
1129         prvm_prog_t *prog = SVVM_prog;
1130         int netcmd, num, start;
1131         char *s, *p, *q;
1132
1133         if(sv_autodemo_perclient.integer >= 2)
1134                 SV_WriteDemoMessage(host_client, &(host_client->netconnection->message), true);
1135
1136         //MSG_BeginReading ();
1137         sv_numreadmoves = 0;
1138
1139         for(;;)
1140         {
1141                 if (!host_client->active)
1142                 {
1143                         // a command caused an error
1144                         SV_DropClient (false);
1145                         return;
1146                 }
1147
1148                 if (sv_message.badread)
1149                 {
1150                         Con_Print("SV_ReadClientMessage: badread\n");
1151                         SV_DropClient (false);
1152                         return;
1153                 }
1154
1155                 netcmd = MSG_ReadByte(&sv_message);
1156                 if (netcmd == -1)
1157                 {
1158                         // end of message
1159                         // apply the moves that were read this frame
1160                         SV_ExecuteClientMoves();
1161                         break;
1162                 }
1163
1164                 switch (netcmd)
1165                 {
1166                 default:
1167                         Con_Printf("SV_ReadClientMessage: unknown command char %i (at offset 0x%x)\n", netcmd, sv_message.readcount);
1168                         if (developer_networking.integer)
1169                                 Com_HexDumpToConsole(sv_message.data, sv_message.cursize);
1170                         SV_DropClient (false);
1171                         return;
1172
1173                 case clc_nop:
1174                         break;
1175
1176                 case clc_stringcmd:
1177                         // allow reliable messages now as the client is done with initial loading
1178                         if (host_client->sendsignon == 2)
1179                                 host_client->sendsignon = 0;
1180                         s = MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring));
1181                         q = NULL;
1182                         for(p = s; *p; ++p) switch(*p)
1183                         {
1184                                 case 10:
1185                                 case 13:
1186                                         if(!q)
1187                                                 q = p;
1188                                         break;
1189                                 default:
1190                                         if(q)
1191                                                 goto clc_stringcmd_invalid; // newline seen, THEN something else -> possible exploit
1192                                         break;
1193                         }
1194                         if(q)
1195                                 *q = 0;
1196                         if (strncasecmp(s, "spawn", 5) == 0
1197                          || strncasecmp(s, "begin", 5) == 0
1198                          || strncasecmp(s, "prespawn", 8) == 0)
1199                                 Cmd_ExecuteString (cmd_serverfromclient, s, src_client, true);
1200                         else if (PRVM_serverfunction(SV_ParseClientCommand))
1201                         {
1202                                 int restorevm_tempstringsbuf_cursize;
1203                                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
1204                                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, s);
1205                                 PRVM_serverglobalfloat(time) = sv.time;
1206                                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
1207                                 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_ParseClientCommand), "QC function SV_ParseClientCommand is missing");
1208                                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
1209                         }
1210                         else
1211                                 Cmd_ExecuteString (cmd_serverfromclient, s, src_client, true);
1212                         break;
1213
1214 clc_stringcmd_invalid:
1215                         Con_Printf("Received invalid stringcmd from %s\n", host_client->name);
1216                         if(developer.integer > 0)
1217                                 Com_HexDumpToConsole((unsigned char *) s, (int)strlen(s));
1218                         break;
1219
1220                 case clc_disconnect:
1221                         SV_DropClient (false); // client wants to disconnect
1222                         return;
1223
1224                 case clc_move:
1225                         SV_ReadClientMove();
1226                         break;
1227
1228                 case clc_ackdownloaddata:
1229                         start = MSG_ReadLong(&sv_message);
1230                         num = MSG_ReadShort(&sv_message);
1231                         if (host_client->download_file && host_client->download_started)
1232                         {
1233                                 if (host_client->download_expectedposition == start)
1234                                 {
1235                                         int size = (int)FS_FileSize(host_client->download_file);
1236                                         // a data block was successfully received by the client,
1237                                         // update the expected position on the next data block
1238                                         host_client->download_expectedposition = start + num;
1239                                         // if this was the last data block of the file, it's done
1240                                         if (host_client->download_expectedposition >= FS_FileSize(host_client->download_file))
1241                                         {
1242                                                 // tell the client that the download finished
1243                                                 // we need to calculate the crc now
1244                                                 //
1245                                                 // note: at this point the OS probably has the file
1246                                                 // entirely in memory, so this is a faster operation
1247                                                 // now than it was when the download started.
1248                                                 //
1249                                                 // it is also preferable to do this at the end of the
1250                                                 // download rather than the start because it reduces
1251                                                 // potential for Denial Of Service attacks against the
1252                                                 // server.
1253                                                 int crc;
1254                                                 unsigned char *temp;
1255                                                 FS_Seek(host_client->download_file, 0, SEEK_SET);
1256                                                 temp = (unsigned char *) Mem_Alloc(tempmempool, size);
1257                                                 FS_Read(host_client->download_file, temp, size);
1258                                                 crc = CRC_Block(temp, size);
1259                                                 Mem_Free(temp);
1260                                                 // calculated crc, send the file info to the client
1261                                                 // (so that it can verify the data)
1262                                                 SV_ClientCommands("\ncl_downloadfinished %i %i %s\n", size, crc, host_client->download_name);
1263                                                 Con_DPrintf("Download of %s by %s has finished\n", host_client->download_name, host_client->name);
1264                                                 FS_Close(host_client->download_file);
1265                                                 host_client->download_file = NULL;
1266                                                 host_client->download_name[0] = 0;
1267                                                 host_client->download_expectedposition = 0;
1268                                                 host_client->download_started = false;
1269                                         }
1270                                 }
1271                                 else
1272                                 {
1273                                         // a data block was lost, reset to the expected position
1274                                         // and resume sending from there
1275                                         FS_Seek(host_client->download_file, host_client->download_expectedposition, SEEK_SET);
1276                                 }
1277                         }
1278                         break;
1279
1280                 case clc_ackframe:
1281                         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
1282                         num = MSG_ReadLong(&sv_message);
1283                         if (sv_message.badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
1284                         if (developer_networkentities.integer >= 10)
1285                                 Con_Printf("recv clc_ackframe %i\n", num);
1286                         // if the client hasn't progressed through signons yet,
1287                         // ignore any clc_ackframes we get (they're probably from the
1288                         // previous level)
1289                         if (host_client->begun && host_client->latestframenum < num)
1290                         {
1291                                 int i;
1292                                 for (i = host_client->latestframenum + 1;i < num;i++)
1293                                         if (!SV_FrameLost(i))
1294                                                 break;
1295                                 SV_FrameAck(num);
1296                                 host_client->latestframenum = num;
1297                         }
1298                         break;
1299                 }
1300         }
1301 }
1302