colormod values above 1 1 1 should work properly with r_glsl now
[divverent/darkplaces.git] / cl_parse.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 // cl_parse.c  -- parse a message received from the server
21
22 #include "quakedef.h"
23 #include "cdaudio.h"
24 #include "cl_collision.h"
25 #include "csprogs.h"
26 #include "libcurl.h"
27
28 char *svc_strings[128] =
29 {
30         "svc_bad",
31         "svc_nop",
32         "svc_disconnect",
33         "svc_updatestat",
34         "svc_version",          // [int] server version
35         "svc_setview",          // [short] entity number
36         "svc_sound",                    // <see code>
37         "svc_time",                     // [float] server time
38         "svc_print",                    // [string] null terminated string
39         "svc_stufftext",                // [string] stuffed into client's console buffer
40                                                 // the string should be \n terminated
41         "svc_setangle",         // [vec3] set the view angle to this absolute value
42
43         "svc_serverinfo",               // [int] version
44                                                 // [string] signon string
45                                                 // [string]..[0]model cache [string]...[0]sounds cache
46                                                 // [string]..[0]item cache
47         "svc_lightstyle",               // [byte] [string]
48         "svc_updatename",               // [byte] [string]
49         "svc_updatefrags",      // [byte] [short]
50         "svc_clientdata",               // <shortbits + data>
51         "svc_stopsound",                // <see code>
52         "svc_updatecolors",     // [byte] [byte]
53         "svc_particle",         // [vec3] <variable>
54         "svc_damage",                   // [byte] impact [byte] blood [vec3] from
55
56         "svc_spawnstatic",
57         "OBSOLETE svc_spawnbinary",
58         "svc_spawnbaseline",
59
60         "svc_temp_entity",              // <variable>
61         "svc_setpause",
62         "svc_signonnum",
63         "svc_centerprint",
64         "svc_killedmonster",
65         "svc_foundsecret",
66         "svc_spawnstaticsound",
67         "svc_intermission",
68         "svc_finale",                   // [string] music [string] text
69         "svc_cdtrack",                  // [byte] track [byte] looptrack
70         "svc_sellscreen",
71         "svc_cutscene",
72         "svc_showlmp",  // [string] iconlabel [string] lmpfile [short] x [short] y
73         "svc_hidelmp",  // [string] iconlabel
74         "svc_skybox", // [string] skyname
75         "", // 38
76         "", // 39
77         "", // 40
78         "", // 41
79         "", // 42
80         "", // 43
81         "", // 44
82         "", // 45
83         "", // 46
84         "", // 47
85         "", // 48
86         "", // 49
87         "svc_downloaddata", //                          50              // [int] start [short] size [variable length] data
88         "svc_updatestatubyte", //                       51              // [byte] stat [byte] value
89         "svc_effect", //                        52              // [vector] org [byte] modelindex [byte] startframe [byte] framecount [byte] framerate
90         "svc_effect2", //                       53              // [vector] org [short] modelindex [short] startframe [byte] framecount [byte] framerate
91         "svc_sound2", //                        54              // short soundindex instead of byte
92         "svc_spawnbaseline2", //        55              // short modelindex instead of byte
93         "svc_spawnstatic2", //          56              // short modelindex instead of byte
94         "svc_entities", //                      57              // [int] deltaframe [int] thisframe [float vector] eye [variable length] entitydata
95         "svc_csqcentities", //          58              // [short] entnum [variable length] entitydata ... [short] 0x0000
96         "svc_spawnstaticsound2", //     59              // [coord3] [short] samp [byte] vol [byte] aten
97 };
98
99 char *qw_svc_strings[128] =
100 {
101         "qw_svc_bad",                                   // 0
102         "qw_svc_nop",                                   // 1
103         "qw_svc_disconnect",                    // 2
104         "qw_svc_updatestat",                    // 3    // [byte] [byte]
105         "",                                                             // 4
106         "qw_svc_setview",                               // 5    // [short] entity number
107         "qw_svc_sound",                                 // 6    // <see code>
108         "",                                                             // 7
109         "qw_svc_print",                                 // 8    // [byte] id [string] null terminated string
110         "qw_svc_stufftext",                             // 9    // [string] stuffed into client's console buffer
111         "qw_svc_setangle",                              // 10   // [angle3] set the view angle to this absolute value
112         "qw_svc_serverdata",                    // 11   // [long] protocol ...
113         "qw_svc_lightstyle",                    // 12   // [byte] [string]
114         "",                                                             // 13
115         "qw_svc_updatefrags",                   // 14   // [byte] [short]
116         "",                                                             // 15
117         "qw_svc_stopsound",                             // 16   // <see code>
118         "",                                                             // 17
119         "",                                                             // 18
120         "qw_svc_damage",                                // 19
121         "qw_svc_spawnstatic",                   // 20
122         "",                                                             // 21
123         "qw_svc_spawnbaseline",                 // 22
124         "qw_svc_temp_entity",                   // 23   // variable
125         "qw_svc_setpause",                              // 24   // [byte] on / off
126         "",                                                             // 25
127         "qw_svc_centerprint",                   // 26   // [string] to put in center of the screen
128         "qw_svc_killedmonster",                 // 27
129         "qw_svc_foundsecret",                   // 28
130         "qw_svc_spawnstaticsound",              // 29   // [coord3] [byte] samp [byte] vol [byte] aten
131         "qw_svc_intermission",                  // 30           // [vec3_t] origin [vec3_t] angle
132         "qw_svc_finale",                                // 31           // [string] text
133         "qw_svc_cdtrack",                               // 32           // [byte] track
134         "qw_svc_sellscreen",                    // 33
135         "qw_svc_smallkick",                             // 34           // set client punchangle to 2
136         "qw_svc_bigkick",                               // 35           // set client punchangle to 4
137         "qw_svc_updateping",                    // 36           // [byte] [short]
138         "qw_svc_updateentertime",               // 37           // [byte] [float]
139         "qw_svc_updatestatlong",                // 38           // [byte] [long]
140         "qw_svc_muzzleflash",                   // 39           // [short] entity
141         "qw_svc_updateuserinfo",                // 40           // [byte] slot [long] uid
142         "qw_svc_download",                              // 41           // [short] size [size bytes]
143         "qw_svc_playerinfo",                    // 42           // variable
144         "qw_svc_nails",                                 // 43           // [byte] num [48 bits] xyzpy 12 12 12 4 8
145         "qw_svc_chokecount",                    // 44           // [byte] packets choked
146         "qw_svc_modellist",                             // 45           // [strings]
147         "qw_svc_soundlist",                             // 46           // [strings]
148         "qw_svc_packetentities",                // 47           // [...]
149         "qw_svc_deltapacketentities",   // 48           // [...]
150         "qw_svc_maxspeed",                              // 49           // maxspeed change, for prediction
151         "qw_svc_entgravity",                    // 50           // gravity change, for prediction
152         "qw_svc_setinfo",                               // 51           // setinfo on a client
153         "qw_svc_serverinfo",                    // 52           // serverinfo
154         "qw_svc_updatepl",                              // 53           // [byte] [byte]
155 };
156
157 //=============================================================================
158
159 cvar_t demo_nehahra = {0, "demo_nehahra", "0", "reads all quake demos as nehahra movie protocol"};
160 cvar_t developer_networkentities = {0, "developer_networkentities", "0", "prints received entities, value is 0-4 (higher for more info)"};
161 cvar_t cl_gameplayfix_soundsmovewithentities = {0, "cl_gameplayfix_soundsmovewithentities", "1", "causes sounds made by lifts, players, projectiles, and any other entities, to move with the entity, so for example a rocket noise follows the rocket rather than staying at the starting position"};
162 cvar_t cl_sound_wizardhit = {0, "cl_sound_wizardhit", "wizard/hit.wav", "sound to play during TE_WIZSPIKE (empty cvar disables sound)"};
163 cvar_t cl_sound_hknighthit = {0, "cl_sound_hknighthit", "hknight/hit.wav", "sound to play during TE_KNIGHTSPIKE (empty cvar disables sound)"};
164 cvar_t cl_sound_tink1 = {0, "cl_sound_tink1", "weapons/tink1.wav", "sound to play with 80% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
165 cvar_t cl_sound_ric1 = {0, "cl_sound_ric1", "weapons/ric1.wav", "sound to play with 5% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
166 cvar_t cl_sound_ric2 = {0, "cl_sound_ric2", "weapons/ric2.wav", "sound to play with 5% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
167 cvar_t cl_sound_ric3 = {0, "cl_sound_ric3", "weapons/ric3.wav", "sound to play with 10% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
168
169 #define RIC_GUNSHOT             1
170 #define RIC_GUNSHOTQUAD 2
171 cvar_t cl_sound_ric_gunshot = {0, "cl_sound_ric_gunshot", "0", "specifies if and when the related cl_sound_ric and cl_sound_tink sounds apply to TE_GUNSHOT/TE_GUNSHOTQUAD, 0 = no sound, 1 = TE_GUNSHOT, 2 = TE_GUNSHOTQUAD, 3 = TE_GUNSHOT and TE_GUNSHOTQUAD"};
172 cvar_t cl_sound_r_exp3 = {0, "cl_sound_r_exp3", "weapons/r_exp3.wav", "sound to play during TE_EXPLOSION and related effects (empty cvar disables sound)"};
173 cvar_t cl_serverextension_download = {0, "cl_serverextension_download", "0", "indicates whether the server supports the download command"};
174 cvar_t cl_joinbeforedownloadsfinish = {CVAR_SAVE, "cl_joinbeforedownloadsfinish", "1", "if non-zero the game will begin after the map is loaded before other downloads finish"};
175 cvar_t cl_nettimesyncfactor = {CVAR_SAVE, "cl_nettimesyncfactor", "0", "rate at which client time adapts to match server time, 1 = instantly, 0.125 = slowly, 0 = not at all (bounding still applies)"};
176 cvar_t cl_nettimesyncboundmode = {CVAR_SAVE, "cl_nettimesyncboundmode", "6", "method of restricting client time to valid values, 0 = no correction, 1 = tight bounding (jerky with packet loss), 2 = loose bounding (corrects it if out of bounds), 3 = leniant bounding (ignores temporary errors due to varying framerate), 4 = slow adjustment method from Quake3, 5 = slighttly nicer version of Quake3 method, 6 = bounding + Quake3"};
177 cvar_t cl_nettimesyncboundtolerance = {CVAR_SAVE, "cl_nettimesyncboundtolerance", "0.25", "how much error is tolerated by bounding check, as a fraction of frametime, 0.25 = up to 25% margin of error tolerated, 1 = use only new time, 0 = use only old time (same effect as setting cl_nettimesyncfactor to 1)"};
178 cvar_t cl_iplog_name = {CVAR_SAVE, "cl_iplog_name", "darkplaces_iplog.txt", "name of iplog file containing player addresses for iplog_list command and automatic ip logging when parsing status command"};
179
180 static qboolean QW_CL_CheckOrDownloadFile(const char *filename);
181 static void QW_CL_RequestNextDownload(void);
182 static void QW_CL_NextUpload(void);
183 void QW_CL_StartUpload(unsigned char *data, int size);
184 //static qboolean QW_CL_IsUploading(void);
185 static void QW_CL_StopUpload(void);
186 void CL_VM_UpdateIntermissionState(int intermission);
187 qboolean CL_VM_Event_Sound(int sound_num, int volume, int channel, float attenuation, int ent, vec3_t pos);
188
189 /*
190 ==================
191 CL_ParseStartSoundPacket
192 ==================
193 */
194 void CL_ParseStartSoundPacket(int largesoundindex)
195 {
196         vec3_t  pos;
197         int     channel, ent;
198         int     sound_num;
199         int     volume;
200         int     field_mask;
201         float   attenuation;
202
203         if (cls.protocol == PROTOCOL_QUAKEWORLD)
204         {
205                 channel = MSG_ReadShort();
206
207                 if (channel & (1<<15))
208                         volume = MSG_ReadByte ();
209                 else
210                         volume = DEFAULT_SOUND_PACKET_VOLUME;
211
212                 if (channel & (1<<14))
213                         attenuation = MSG_ReadByte () / 64.0;
214                 else
215                         attenuation = DEFAULT_SOUND_PACKET_ATTENUATION;
216
217                 ent = (channel>>3)&1023;
218                 channel &= 7;
219
220                 sound_num = MSG_ReadByte ();
221         }
222         else
223         {
224                 field_mask = MSG_ReadByte();
225
226                 if (field_mask & SND_VOLUME)
227                         volume = MSG_ReadByte ();
228                 else
229                         volume = DEFAULT_SOUND_PACKET_VOLUME;
230
231                 if (field_mask & SND_ATTENUATION)
232                         attenuation = MSG_ReadByte () / 64.0;
233                 else
234                         attenuation = DEFAULT_SOUND_PACKET_ATTENUATION;
235
236                 if (field_mask & SND_LARGEENTITY)
237                 {
238                         ent = (unsigned short) MSG_ReadShort ();
239                         channel = MSG_ReadByte ();
240                 }
241                 else
242                 {
243                         channel = (unsigned short) MSG_ReadShort ();
244                         ent = channel >> 3;
245                         channel &= 7;
246                 }
247
248                 if (largesoundindex || (field_mask & SND_LARGESOUND) || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
249                         sound_num = (unsigned short) MSG_ReadShort ();
250                 else
251                         sound_num = MSG_ReadByte ();
252         }
253
254         MSG_ReadVector(pos, cls.protocol);
255
256         if (sound_num >= MAX_SOUNDS)
257         {
258                 Con_Printf("CL_ParseStartSoundPacket: sound_num (%i) >= MAX_SOUNDS (%i)\n", sound_num, MAX_SOUNDS);
259                 return;
260         }
261
262         if (ent >= MAX_EDICTS)
263         {
264                 Con_Printf("CL_ParseStartSoundPacket: ent = %i", ent);
265                 return;
266         }
267
268         if (ent >= cl.max_entities)
269                 CL_ExpandEntities(ent);
270
271         if( !CL_VM_Event_Sound(sound_num, volume / 255.0f, channel, attenuation, ent, pos) )
272                 S_StartSound (ent, channel, cl.sound_precache[sound_num], pos, volume/255.0f, attenuation);
273 }
274
275 /*
276 ==================
277 CL_KeepaliveMessage
278
279 When the client is taking a long time to load stuff, send keepalive messages
280 so the server doesn't disconnect.
281 ==================
282 */
283
284 static unsigned char olddata[NET_MAXMESSAGE];
285 void CL_KeepaliveMessage (qboolean readmessages)
286 {
287         float time;
288         static double nextmsg = -1;
289         int oldreadcount;
290         qboolean oldbadread;
291         sizebuf_t old;
292
293         // no need if server is local and definitely not if this is a demo
294         if (!cls.netcon || cls.protocol == PROTOCOL_QUAKEWORLD)
295                 return;
296
297         if (readmessages)
298         {
299                 // read messages from server, should just be nops
300                 oldreadcount = msg_readcount;
301                 oldbadread = msg_badread;
302                 old = net_message;
303                 memcpy(olddata, net_message.data, net_message.cursize);
304
305                 NetConn_ClientFrame();
306
307                 msg_readcount = oldreadcount;
308                 msg_badread = oldbadread;
309                 net_message = old;
310                 memcpy(net_message.data, olddata, net_message.cursize);
311         }
312
313         if (cls.netcon && (time = Sys_DoubleTime()) >= nextmsg)
314         {
315                 sizebuf_t       msg;
316                 unsigned char           buf[4];
317                 nextmsg = time + 5;
318                 // write out a nop
319                 // LordHavoc: must use unreliable because reliable could kill the sigon message!
320                 Con_Print("--> client to server keepalive\n");
321                 memset(&msg, 0, sizeof(msg));
322                 msg.data = buf;
323                 msg.maxsize = sizeof(buf);
324                 MSG_WriteChar(&msg, clc_nop);
325                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
326         }
327 }
328
329 void CL_ParseEntityLump(char *entdata)
330 {
331         const char *data;
332         char key[128], value[MAX_INPUTLINE];
333         FOG_clear(); // LordHavoc: no fog until set
334         // LordHavoc: default to the map's sky (q3 shader parsing sets this)
335         R_SetSkyBox(cl.worldmodel->brush.skybox);
336         data = entdata;
337         if (!data)
338                 return;
339         if (!COM_ParseToken_Simple(&data, false, false))
340                 return; // error
341         if (com_token[0] != '{')
342                 return; // error
343         while (1)
344         {
345                 if (!COM_ParseToken_Simple(&data, false, false))
346                         return; // error
347                 if (com_token[0] == '}')
348                         break; // end of worldspawn
349                 if (com_token[0] == '_')
350                         strlcpy (key, com_token + 1, sizeof (key));
351                 else
352                         strlcpy (key, com_token, sizeof (key));
353                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
354                         key[strlen(key)-1] = 0;
355                 if (!COM_ParseToken_Simple(&data, false, false))
356                         return; // error
357                 strlcpy (value, com_token, sizeof (value));
358                 if (!strcmp("sky", key))
359                         R_SetSkyBox(value);
360                 else if (!strcmp("skyname", key)) // non-standard, introduced by QuakeForge... sigh.
361                         R_SetSkyBox(value);
362                 else if (!strcmp("qlsky", key)) // non-standard, introduced by QuakeLives (EEK)
363                         R_SetSkyBox(value);
364                 else if (!strcmp("fog", key))
365                 {
366                         r_refdef.fog_start = 0;
367                         r_refdef.fog_alpha = 1;
368                         sscanf(value, "%f %f %f %f %f %f %f", &r_refdef.fog_density, &r_refdef.fog_red, &r_refdef.fog_green, &r_refdef.fog_blue, &r_refdef.fog_alpha, &r_refdef.fog_start, &r_refdef.fog_end);
369                 }
370                 else if (!strcmp("fog_density", key))
371                         r_refdef.fog_density = atof(value);
372                 else if (!strcmp("fog_red", key))
373                         r_refdef.fog_red = atof(value);
374                 else if (!strcmp("fog_green", key))
375                         r_refdef.fog_green = atof(value);
376                 else if (!strcmp("fog_blue", key))
377                         r_refdef.fog_blue = atof(value);
378                 else if (!strcmp("fog_alpha", key))
379                         r_refdef.fog_alpha = atof(value);
380                 else if (!strcmp("fog_start", key))
381                         r_refdef.fog_start = atof(value);
382                 else if (!strcmp("fog_end", key))
383                         r_refdef.fog_end = atof(value);
384         }
385 }
386
387 extern void CL_Locs_Reload_f(void);
388 extern void CL_VM_Init (void);
389 static void CL_SetupWorldModel(void)
390 {
391         // update the world model
392         cl.entities[0].render.model = cl.worldmodel = cl.model_precache[1];
393         CL_UpdateRenderEntity(&cl.entities[0].render);
394
395         // set up csqc world for collision culling
396         if (cl.worldmodel)
397         {
398                 VectorCopy(cl.worldmodel->normalmins, cl.world.areagrid_mins);
399                 VectorCopy(cl.worldmodel->normalmaxs, cl.world.areagrid_maxs);
400         }
401         else
402         {
403                 VectorSet(cl.world.areagrid_mins, -4096, -4096, -4096);
404                 VectorSet(cl.world.areagrid_maxs, 4096, 4096, 4096);
405         }
406         World_Clear(&cl.world);
407
408         // load or reload .loc file for team chat messages
409         CL_Locs_Reload_f();
410
411         // reset particles and other per-level things
412         R_Modules_NewMap();
413
414         // load the team chat beep if possible
415         cl.foundtalk2wav = FS_FileExists("sound/misc/talk2.wav");
416
417         // check memory integrity
418         Mem_CheckSentinelsGlobal();
419
420         // load the csqc now
421         if (cl.loadcsqc)
422         {
423                 cl.loadcsqc = false;
424                 CL_VM_Init();
425         }
426 }
427
428 static qboolean QW_CL_CheckOrDownloadFile(const char *filename)
429 {
430         qfile_t *file;
431
432         // see if the file already exists
433         file = FS_Open(filename, "rb", true, false);
434         if (file)
435         {
436                 FS_Close(file);
437                 return true;
438         }
439
440         // download messages in a demo would be bad
441         if (cls.demorecording)
442         {
443                 Con_Printf("Unable to download \"%s\" when recording.\n", filename);
444                 return true;
445         }
446
447         // don't try to download when playing a demo
448         if (!cls.netcon)
449                 return true;
450
451         strlcpy(cls.qw_downloadname, filename, sizeof(cls.qw_downloadname));
452         Con_Printf("Downloading %s\n", filename);
453
454         if (!cls.qw_downloadmemory)
455         {
456                 cls.qw_downloadmemory = NULL;
457                 cls.qw_downloadmemorycursize = 0;
458                 cls.qw_downloadmemorymaxsize = 1024*1024; // start out with a 1MB buffer
459         }
460
461         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
462         MSG_WriteString(&cls.netcon->message, va("download %s", filename));
463
464         cls.qw_downloadnumber++;
465         cls.qw_downloadpercent = 0;
466         cls.qw_downloadmemorycursize = 0;
467
468         return false;
469 }
470
471 static void QW_CL_ProcessUserInfo(int slot);
472 static void QW_CL_RequestNextDownload(void)
473 {
474         int i;
475
476         // clear name of file that just finished
477         cls.qw_downloadname[0] = 0;
478
479         switch (cls.qw_downloadtype)
480         {
481         case dl_single:
482                 break;
483         case dl_skin:
484                 if (cls.qw_downloadnumber == 0)
485                         Con_Printf("Checking skins...\n");
486                 for (;cls.qw_downloadnumber < cl.maxclients;cls.qw_downloadnumber++)
487                 {
488                         if (!cl.scores[cls.qw_downloadnumber].name[0])
489                                 continue;
490                         // check if we need to download the file, and return if so
491                         if (!QW_CL_CheckOrDownloadFile(va("skins/%s.pcx", cl.scores[cls.qw_downloadnumber].qw_skin)))
492                                 return;
493                 }
494
495                 cls.qw_downloadtype = dl_none;
496
497                 // load any newly downloaded skins
498                 for (i = 0;i < cl.maxclients;i++)
499                         QW_CL_ProcessUserInfo(i);
500
501                 // if we're still in signon stages, request the next one
502                 if (cls.signon != SIGNONS)
503                 {
504                         cls.signon = SIGNONS-1;
505                         // we'll go to SIGNONS when the first entity update is received
506                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
507                         MSG_WriteString(&cls.netcon->message, va("begin %i", cl.qw_servercount));
508                 }
509                 break;
510         case dl_model:
511                 if (cls.qw_downloadnumber == 0)
512                 {
513                         Con_Printf("Checking models...\n");
514                         cls.qw_downloadnumber = 1;
515                 }
516
517                 for (;cls.qw_downloadnumber < MAX_MODELS && cl.model_name[cls.qw_downloadnumber][0];cls.qw_downloadnumber++)
518                 {
519                         // skip submodels
520                         if (cl.model_name[cls.qw_downloadnumber][0] == '*')
521                                 continue;
522                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/spike.mdl"))
523                                 cl.qw_modelindex_spike = cls.qw_downloadnumber;
524                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/player.mdl"))
525                                 cl.qw_modelindex_player = cls.qw_downloadnumber;
526                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/flag.mdl"))
527                                 cl.qw_modelindex_flag = cls.qw_downloadnumber;
528                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/s_explod.spr"))
529                                 cl.qw_modelindex_s_explod = cls.qw_downloadnumber;
530                         // check if we need to download the file, and return if so
531                         if (!QW_CL_CheckOrDownloadFile(cl.model_name[cls.qw_downloadnumber]))
532                                 return;
533                 }
534
535                 cls.qw_downloadtype = dl_none;
536
537                 // touch all of the precached models that are still loaded so we can free
538                 // anything that isn't needed
539                 if (!sv.active)
540                         Mod_ClearUsed();
541                 for (i = 1;i < MAX_MODELS && cl.model_name[i][0];i++)
542                         Mod_FindName(cl.model_name[i]);
543                 // precache any models used by the client (this also marks them used)
544                 cl.model_bolt = Mod_ForName("progs/bolt.mdl", false, false, false);
545                 cl.model_bolt2 = Mod_ForName("progs/bolt2.mdl", false, false, false);
546                 cl.model_bolt3 = Mod_ForName("progs/bolt3.mdl", false, false, false);
547                 cl.model_beam = Mod_ForName("progs/beam.mdl", false, false, false);
548                 Mod_PurgeUnused();
549
550                 // now we try to load everything that is new
551
552                 // world model
553                 cl.model_precache[1] = Mod_ForName(cl.model_name[1], false, false, true);
554                 if (cl.model_precache[1]->Draw == NULL)
555                         Con_Printf("Map %s could not be found or downloaded\n", cl.model_name[1]);
556
557                 // normal models
558                 for (i = 2;i < MAX_MODELS && cl.model_name[i][0];i++)
559                         if ((cl.model_precache[i] = Mod_ForName(cl.model_name[i], false, false, false))->Draw == NULL)
560                                 Con_Printf("Model %s could not be found or downloaded\n", cl.model_name[i]);
561
562                 // check memory integrity
563                 Mem_CheckSentinelsGlobal();
564
565                 // now that we have a world model, set up the world entity, renderer
566                 // modules and csqc
567                 CL_SetupWorldModel();
568
569                 // add pmodel/emodel CRCs to userinfo
570                 CL_SetInfo("pmodel", va("%i", FS_CRCFile("progs/player.mdl", NULL)), true, true, true, true);
571                 CL_SetInfo("emodel", va("%i", FS_CRCFile("progs/eyes.mdl", NULL)), true, true, true, true);
572
573                 // done checking sounds and models, send a prespawn command now
574                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
575                 MSG_WriteString(&cls.netcon->message, va("prespawn %i 0 %i", cl.qw_servercount, cl.model_precache[1]->brush.qw_md4sum2));
576
577                 if (cls.qw_downloadmemory)
578                 {
579                         Mem_Free(cls.qw_downloadmemory);
580                         cls.qw_downloadmemory = NULL;
581                 }
582
583                 // done loading
584                 cl.loadfinished = true;
585                 break;
586         case dl_sound:
587                 if (cls.qw_downloadnumber == 0)
588                 {
589                         Con_Printf("Checking sounds...\n");
590                         cls.qw_downloadnumber = 1;
591                 }
592
593                 for (;cl.sound_name[cls.qw_downloadnumber][0];cls.qw_downloadnumber++)
594                 {
595                         // check if we need to download the file, and return if so
596                         if (!QW_CL_CheckOrDownloadFile(va("sound/%s", cl.sound_name[cls.qw_downloadnumber])))
597                                 return;
598                 }
599
600                 cls.qw_downloadtype = dl_none;
601
602                 // load new sounds and unload old ones
603                 // FIXME: S_ServerSounds does not know about cl.sfx_ sounds
604                 S_ServerSounds(cl.sound_name, cls.qw_downloadnumber);
605
606                 // precache any sounds used by the client
607                 cl.sfx_wizhit = S_PrecacheSound(cl_sound_wizardhit.string, false, true);
608                 cl.sfx_knighthit = S_PrecacheSound(cl_sound_hknighthit.string, false, true);
609                 cl.sfx_tink1 = S_PrecacheSound(cl_sound_tink1.string, false, true);
610                 cl.sfx_ric1 = S_PrecacheSound(cl_sound_ric1.string, false, true);
611                 cl.sfx_ric2 = S_PrecacheSound(cl_sound_ric2.string, false, true);
612                 cl.sfx_ric3 = S_PrecacheSound(cl_sound_ric3.string, false, true);
613                 cl.sfx_r_exp3 = S_PrecacheSound(cl_sound_r_exp3.string, false, true);
614
615                 // sounds
616                 for (i = 1;i < MAX_SOUNDS && cl.sound_name[i][0];i++)
617                 {
618                         // Don't lock the sfx here, S_ServerSounds already did that
619                         cl.sound_precache[i] = S_PrecacheSound(cl.sound_name[i], true, false);
620                 }
621
622                 // check memory integrity
623                 Mem_CheckSentinelsGlobal();
624
625                 // done with sound downloads, next we check models
626                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
627                 MSG_WriteString(&cls.netcon->message, va("modellist %i %i", cl.qw_servercount, 0));
628                 break;
629         case dl_none:
630         default:
631                 Con_Printf("Unknown download type.\n");
632         }
633 }
634
635 static void QW_CL_ParseDownload(void)
636 {
637         int size = (signed short)MSG_ReadShort();
638         int percent = MSG_ReadByte();
639
640         //Con_Printf("download %i %i%% (%i/%i)\n", size, percent, cls.qw_downloadmemorycursize, cls.qw_downloadmemorymaxsize);
641
642         // skip the download fragment if playing a demo
643         if (!cls.netcon)
644         {
645                 if (size > 0)
646                         msg_readcount += size;
647                 return;
648         }
649
650         if (size == -1)
651         {
652                 Con_Printf("File not found.\n");
653                 QW_CL_RequestNextDownload();
654                 return;
655         }
656
657         if (msg_readcount + (unsigned short)size > net_message.cursize)
658                 Host_Error("corrupt download message\n");
659
660         // make sure the buffer is big enough to include this new fragment
661         if (!cls.qw_downloadmemory || cls.qw_downloadmemorymaxsize < cls.qw_downloadmemorycursize + size)
662         {
663                 unsigned char *old;
664                 while (cls.qw_downloadmemorymaxsize < cls.qw_downloadmemorycursize + size)
665                         cls.qw_downloadmemorymaxsize *= 2;
666                 old = cls.qw_downloadmemory;
667                 cls.qw_downloadmemory = (unsigned char *)Mem_Alloc(cls.permanentmempool, cls.qw_downloadmemorymaxsize);
668                 if (old)
669                 {
670                         memcpy(cls.qw_downloadmemory, old, cls.qw_downloadmemorycursize);
671                         Mem_Free(old);
672                 }
673         }
674
675         // read the fragment out of the packet
676         MSG_ReadBytes(size, cls.qw_downloadmemory + cls.qw_downloadmemorycursize);
677         cls.qw_downloadmemorycursize += size;
678         cls.qw_downloadspeedcount += size;
679
680         cls.qw_downloadpercent = percent;
681
682         if (percent != 100)
683         {
684                 // request next fragment
685                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
686                 MSG_WriteString(&cls.netcon->message, "nextdl");
687         }
688         else
689         {
690                 // finished file
691                 Con_Printf("Downloaded \"%s\"\n", cls.qw_downloadname);
692
693                 FS_WriteFile(cls.qw_downloadname, cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
694
695                 cls.qw_downloadpercent = 0;
696
697                 // start downloading the next file (or join the game)
698                 QW_CL_RequestNextDownload();
699         }
700 }
701
702 static void QW_CL_ParseModelList(void)
703 {
704         int n;
705         int nummodels = MSG_ReadByte();
706         char *str;
707
708         // parse model precache list
709         for (;;)
710         {
711                 str = MSG_ReadString();
712                 if (!str[0])
713                         break;
714                 nummodels++;
715                 if (nummodels==MAX_MODELS)
716                         Host_Error("Server sent too many model precaches");
717                 if (strlen(str) >= MAX_QPATH)
718                         Host_Error("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
719                 strlcpy(cl.model_name[nummodels], str, sizeof (cl.model_name[nummodels]));
720         }
721
722         n = MSG_ReadByte();
723         if (n)
724         {
725                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
726                 MSG_WriteString(&cls.netcon->message, va("modellist %i %i", cl.qw_servercount, n));
727                 return;
728         }
729
730         cls.signon = 2;
731         cls.qw_downloadnumber = 0;
732         cls.qw_downloadtype = dl_model;
733         QW_CL_RequestNextDownload();
734 }
735
736 static void QW_CL_ParseSoundList(void)
737 {
738         int n;
739         int numsounds = MSG_ReadByte();
740         char *str;
741
742         // parse sound precache list
743         for (;;)
744         {
745                 str = MSG_ReadString();
746                 if (!str[0])
747                         break;
748                 numsounds++;
749                 if (numsounds==MAX_SOUNDS)
750                         Host_Error("Server sent too many sound precaches");
751                 if (strlen(str) >= MAX_QPATH)
752                         Host_Error("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
753                 strlcpy(cl.sound_name[numsounds], str, sizeof (cl.sound_name[numsounds]));
754         }
755
756         n = MSG_ReadByte();
757
758         if (n)
759         {
760                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
761                 MSG_WriteString(&cls.netcon->message, va("soundlist %i %i", cl.qw_servercount, n));
762                 return;
763         }
764
765         cls.signon = 2;
766         cls.qw_downloadnumber = 0;
767         cls.qw_downloadtype = dl_sound;
768         QW_CL_RequestNextDownload();
769 }
770
771 static void QW_CL_Skins_f(void)
772 {
773         cls.qw_downloadnumber = 0;
774         cls.qw_downloadtype = dl_skin;
775         QW_CL_RequestNextDownload();
776 }
777
778 static void QW_CL_Changing_f(void)
779 {
780         if (cls.qw_downloadmemory)  // don't change when downloading
781                 return;
782
783         S_StopAllSounds();
784         cl.intermission = 0;
785         cls.signon = 1; // not active anymore, but not disconnected
786         Con_Printf("\nChanging map...\n");
787 }
788
789 void QW_CL_NextUpload(void)
790 {
791         int r, percent, size;
792
793         if (!cls.qw_uploaddata)
794                 return;
795
796         r = cls.qw_uploadsize - cls.qw_uploadpos;
797         if (r > 768)
798                 r = 768;
799         size = min(1, cls.qw_uploadsize);
800         percent = (cls.qw_uploadpos+r)*100/size;
801
802         MSG_WriteByte(&cls.netcon->message, qw_clc_upload);
803         MSG_WriteShort(&cls.netcon->message, r);
804         MSG_WriteByte(&cls.netcon->message, percent);
805         SZ_Write(&cls.netcon->message, cls.qw_uploaddata + cls.qw_uploadpos, r);
806
807         Con_DPrintf("UPLOAD: %6d: %d written\n", cls.qw_uploadpos, r);
808
809         cls.qw_uploadpos += r;
810
811         if (cls.qw_uploadpos < cls.qw_uploadsize)
812                 return;
813
814         Con_Printf("Upload completed\n");
815
816         QW_CL_StopUpload();
817 }
818
819 void QW_CL_StartUpload(unsigned char *data, int size)
820 {
821         // do nothing in demos or if not connected
822         if (!cls.netcon)
823                 return;
824
825         // abort existing upload if in progress
826         QW_CL_StopUpload();
827
828         Con_DPrintf("Starting upload of %d bytes...\n", size);
829
830         cls.qw_uploaddata = (unsigned char *)Mem_Alloc(cls.permanentmempool, size);
831         memcpy(cls.qw_uploaddata, data, size);
832         cls.qw_uploadsize = size;
833         cls.qw_uploadpos = 0;
834
835         QW_CL_NextUpload();
836 }
837
838 #if 0
839 qboolean QW_CL_IsUploading(void)
840 {
841         return cls.qw_uploaddata != NULL;
842 }
843 #endif
844
845 void QW_CL_StopUpload(void)
846 {
847         if (cls.qw_uploaddata)
848                 Mem_Free(cls.qw_uploaddata);
849         cls.qw_uploaddata = NULL;
850         cls.qw_uploadsize = 0;
851         cls.qw_uploadpos = 0;
852 }
853
854 static void QW_CL_ProcessUserInfo(int slot)
855 {
856         int topcolor, bottomcolor;
857         char temp[2048];
858         InfoString_GetValue(cl.scores[slot].qw_userinfo, "name", cl.scores[slot].name, sizeof(cl.scores[slot].name));
859         InfoString_GetValue(cl.scores[slot].qw_userinfo, "topcolor", temp, sizeof(temp));topcolor = atoi(temp);
860         InfoString_GetValue(cl.scores[slot].qw_userinfo, "bottomcolor", temp, sizeof(temp));bottomcolor = atoi(temp);
861         cl.scores[slot].colors = topcolor * 16 + bottomcolor;
862         InfoString_GetValue(cl.scores[slot].qw_userinfo, "*spectator", temp, sizeof(temp));
863         cl.scores[slot].qw_spectator = temp[0] != 0;
864         InfoString_GetValue(cl.scores[slot].qw_userinfo, "team", cl.scores[slot].qw_team, sizeof(cl.scores[slot].qw_team));
865         InfoString_GetValue(cl.scores[slot].qw_userinfo, "skin", cl.scores[slot].qw_skin, sizeof(cl.scores[slot].qw_skin));
866         if (!cl.scores[slot].qw_skin[0])
867                 strlcpy(cl.scores[slot].qw_skin, "base", sizeof(cl.scores[slot].qw_skin));
868         // TODO: skin cache
869 }
870
871 static void QW_CL_UpdateUserInfo(void)
872 {
873         int slot;
874         slot = MSG_ReadByte();
875         if (slot >= cl.maxclients)
876         {
877                 Con_Printf("svc_updateuserinfo >= cl.maxclients\n");
878                 MSG_ReadLong();
879                 MSG_ReadString();
880                 return;
881         }
882         cl.scores[slot].qw_userid = MSG_ReadLong();
883         strlcpy(cl.scores[slot].qw_userinfo, MSG_ReadString(), sizeof(cl.scores[slot].qw_userinfo));
884
885         QW_CL_ProcessUserInfo(slot);
886 }
887
888 static void QW_CL_SetInfo(void)
889 {
890         int slot;
891         char key[2048];
892         char value[2048];
893         slot = MSG_ReadByte();
894         strlcpy(key, MSG_ReadString(), sizeof(key));
895         strlcpy(value, MSG_ReadString(), sizeof(value));
896         if (slot >= cl.maxclients)
897         {
898                 Con_Printf("svc_setinfo >= cl.maxclients\n");
899                 return;
900         }
901         InfoString_SetValue(cl.scores[slot].qw_userinfo, sizeof(cl.scores[slot].qw_userinfo), key, value);
902
903         QW_CL_ProcessUserInfo(slot);
904 }
905
906 static void QW_CL_ServerInfo(void)
907 {
908         char key[2048];
909         char value[2048];
910         char temp[32];
911         strlcpy(key, MSG_ReadString(), sizeof(key));
912         strlcpy(value, MSG_ReadString(), sizeof(value));
913         Con_DPrintf("SERVERINFO: %s=%s\n", key, value);
914         InfoString_SetValue(cl.qw_serverinfo, sizeof(cl.qw_serverinfo), key, value);
915         InfoString_GetValue(cl.qw_serverinfo, "teamplay", temp, sizeof(temp));
916         cl.qw_teamplay = atoi(temp);
917 }
918
919 static void QW_CL_ParseNails(void)
920 {
921         int i, j;
922         int numnails = MSG_ReadByte();
923         vec_t *v;
924         unsigned char bits[6];
925         for (i = 0;i < numnails;i++)
926         {
927                 for (j = 0;j < 6;j++)
928                         bits[j] = MSG_ReadByte();
929                 if (cl.qw_num_nails > 255)
930                         continue;
931                 v = cl.qw_nails[cl.qw_num_nails++];
932                 v[0] = ( ( bits[0] + ((bits[1]&15)<<8) ) <<1) - 4096;
933                 v[1] = ( ( (bits[1]>>4) + (bits[2]<<4) ) <<1) - 4096;
934                 v[2] = ( ( bits[3] + ((bits[4]&15)<<8) ) <<1) - 4096;
935                 v[3] = -360*(bits[4]>>4)/16;
936                 v[4] = 360*bits[5]/256;
937                 v[5] = 0;
938         }
939 }
940
941 static void CL_UpdateItemsAndWeapon(void)
942 {
943         int j;
944         // check for important changes
945
946         // set flash times
947         if (cl.olditems != cl.stats[STAT_ITEMS])
948                 for (j = 0;j < 32;j++)
949                         if ((cl.stats[STAT_ITEMS] & (1<<j)) && !(cl.olditems & (1<<j)))
950                                 cl.item_gettime[j] = cl.time;
951         cl.olditems = cl.stats[STAT_ITEMS];
952
953         // GAME_NEXUIZ hud needs weapon change time
954         if (cl.activeweapon != cl.stats[STAT_ACTIVEWEAPON])
955                 cl.weapontime = cl.time;
956         cl.activeweapon = cl.stats[STAT_ACTIVEWEAPON];
957 }
958
959 void CL_BeginDownloads(qboolean aborteddownload)
960 {
961         // quakeworld works differently
962         if (cls.protocol == PROTOCOL_QUAKEWORLD)
963                 return;
964
965         // this would be a good place to do curl downloads
966         if(Curl_Have_forthismap())
967         {
968                 Curl_Register_predownload(); // come back later
969                 return;
970         }
971
972         // if we got here...
973         // curl is done, so let's start with the business
974         cl.loadbegun = true;
975
976         // if already downloading something from the previous level, don't stop it
977         if (cls.qw_downloadname[0])
978                 return;
979
980         if (cl.downloadcsqc)
981         {
982                 size_t progsize;
983                 cl.downloadcsqc = false;
984                 if (cls.netcon
985                  && !sv.active
986                  && csqc_progname.string
987                  && csqc_progname.string[0]
988                  && csqc_progcrc.integer >= 0
989                  && cl_serverextension_download.integer
990                  && (FS_CRCFile(csqc_progname.string, &progsize) != csqc_progcrc.integer || ((int)progsize != csqc_progsize.integer && csqc_progsize.integer != -1))
991                  && !FS_FileExists(va("dlcache/%s.%i.%i", csqc_progname.string, csqc_progsize.integer, csqc_progcrc.integer)))
992                 {
993                         Con_Printf("Downloading new CSQC code to dlcache/%s.%i.%i\n", csqc_progname.string, csqc_progsize.integer, csqc_progcrc.integer);
994                         Cmd_ForwardStringToServer(va("download %s", csqc_progname.string));
995                         return;
996                 }
997         }
998
999         if (cl.loadmodel_current < cl.loadmodel_total)
1000         {
1001                 // loading models
1002
1003                 for (;cl.loadmodel_current < cl.loadmodel_total;cl.loadmodel_current++)
1004                 {
1005                         if (cl.model_precache[cl.loadmodel_current] && cl.model_precache[cl.loadmodel_current]->Draw)
1006                                 continue;
1007                         if (cls.signon < SIGNONS)
1008                                 CL_KeepaliveMessage(true);
1009                         cl.model_precache[cl.loadmodel_current] = Mod_ForName(cl.model_name[cl.loadmodel_current], false, false, cl.loadmodel_current == 1);
1010                         if (cl.model_precache[cl.loadmodel_current] && cl.model_precache[cl.loadmodel_current]->Draw && cl.loadmodel_current == 1)
1011                         {
1012                                 // we now have the worldmodel so we can set up the game world
1013                                 CL_SetupWorldModel();
1014                                 if (!cl.loadfinished && cl_joinbeforedownloadsfinish.integer)
1015                                 {
1016                                         cl.loadfinished = true;
1017                                         // now issue the spawn to move on to signon 2 like normal
1018                                         if (cls.netcon)
1019                                                 Cmd_ForwardStringToServer("prespawn");
1020                                 }
1021                         }
1022                 }
1023
1024                 // finished loading models
1025         }
1026
1027         if (cl.loadsound_current < cl.loadsound_total)
1028         {
1029                 // loading sounds
1030
1031                 for (;cl.loadsound_current < cl.loadsound_total;cl.loadsound_current++)
1032                 {
1033                         if (cl.sound_precache[cl.loadsound_current] && S_IsSoundPrecached(cl.sound_precache[cl.loadsound_current]))
1034                                 continue;
1035                         if (cls.signon < SIGNONS)
1036                                 CL_KeepaliveMessage(true);
1037                         // Don't lock the sfx here, S_ServerSounds already did that
1038                         cl.sound_precache[cl.loadsound_current] = S_PrecacheSound(cl.sound_name[cl.loadsound_current], false, false);
1039                 }
1040
1041                 // finished loading sounds
1042         }
1043
1044         // note: the reason these loops skip already-loaded things is that it
1045         // enables this command to be issued during the game if desired
1046
1047         if (cl.downloadmodel_current < cl.loadmodel_total)
1048         {
1049                 // loading models
1050
1051                 for (;cl.downloadmodel_current < cl.loadmodel_total;cl.downloadmodel_current++)
1052                 {
1053                         if (aborteddownload)
1054                         {
1055                                 if (cl.downloadmodel_current == 1)
1056                                 {
1057                                         // the worldmodel failed, but we need to set up anyway
1058                                         CL_SetupWorldModel();
1059                                         if (!cl.loadfinished && cl_joinbeforedownloadsfinish.integer)
1060                                         {
1061                                                 cl.loadfinished = true;
1062                                                 // now issue the spawn to move on to signon 2 like normal
1063                                                 if (cls.netcon)
1064                                                         Cmd_ForwardStringToServer("prespawn");
1065                                         }
1066                                 }
1067                                 aborteddownload = false;
1068                                 continue;
1069                         }
1070                         if (cl.model_precache[cl.downloadmodel_current] && cl.model_precache[cl.downloadmodel_current]->Draw)
1071                                 continue;
1072                         if (cls.signon < SIGNONS)
1073                                 CL_KeepaliveMessage(true);
1074                         if (!FS_FileExists(cl.model_name[cl.downloadmodel_current]))
1075                         {
1076                                 if (cl.downloadmodel_current == 1)
1077                                         Con_Printf("Map %s not found\n", cl.model_name[cl.downloadmodel_current]);
1078                                 else
1079                                         Con_Printf("Model %s not found\n", cl.model_name[cl.downloadmodel_current]);
1080                                 // regarding the * check: don't try to download submodels
1081                                 if (cl_serverextension_download.integer && cls.netcon && cl.model_name[cl.downloadmodel_current][0] != '*' && !sv.active)
1082                                 {
1083                                         Cmd_ForwardStringToServer(va("download %s", cl.model_name[cl.downloadmodel_current]));
1084                                         // we'll try loading again when the download finishes
1085                                         return;
1086                                 }
1087                         }
1088                         cl.model_precache[cl.downloadmodel_current] = Mod_ForName(cl.model_name[cl.downloadmodel_current], false, false, cl.downloadmodel_current == 1);
1089                         if (cl.downloadmodel_current == 1)
1090                         {
1091                                 // we now have the worldmodel so we can set up the game world
1092                                 CL_SetupWorldModel();
1093                                 if (!cl.loadfinished && cl_joinbeforedownloadsfinish.integer)
1094                                 {
1095                                         cl.loadfinished = true;
1096                                         // now issue the spawn to move on to signon 2 like normal
1097                                         if (cls.netcon)
1098                                                 Cmd_ForwardStringToServer("prespawn");
1099                                 }
1100                         }
1101                 }
1102
1103                 // finished loading models
1104         }
1105
1106         if (cl.downloadsound_current < cl.loadsound_total)
1107         {
1108                 // loading sounds
1109
1110                 for (;cl.downloadsound_current < cl.loadsound_total;cl.downloadsound_current++)
1111                 {
1112                         char soundname[MAX_QPATH];
1113                         if (aborteddownload)
1114                         {
1115                                 aborteddownload = false;
1116                                 continue;
1117                         }
1118                         if (cl.sound_precache[cl.downloadsound_current] && S_IsSoundPrecached(cl.sound_precache[cl.downloadsound_current]))
1119                                 continue;
1120                         if (cls.signon < SIGNONS)
1121                                 CL_KeepaliveMessage(true);
1122                         dpsnprintf(soundname, sizeof(soundname), "sound/%s", cl.sound_name[cl.downloadsound_current]);
1123                         if (!FS_FileExists(soundname) && !FS_FileExists(cl.sound_name[cl.downloadsound_current]))
1124                         {
1125                                 Con_Printf("Sound %s not found\n", soundname);
1126                                 if (cl_serverextension_download.integer && cls.netcon && !sv.active)
1127                                 {
1128                                         Cmd_ForwardStringToServer(va("download %s", soundname));
1129                                         // we'll try loading again when the download finishes
1130                                         return;
1131                                 }
1132                         }
1133                         // Don't lock the sfx here, S_ServerSounds already did that
1134                         cl.sound_precache[cl.downloadsound_current] = S_PrecacheSound(cl.sound_name[cl.downloadsound_current], false, false);
1135                 }
1136
1137                 // finished loading sounds
1138         }
1139
1140         if (!cl.loadfinished)
1141         {
1142                 cl.loadfinished = true;
1143
1144                 // check memory integrity
1145                 Mem_CheckSentinelsGlobal();
1146
1147                 // now issue the spawn to move on to signon 2 like normal
1148                 if (cls.netcon)
1149                         Cmd_ForwardStringToServer("prespawn");
1150         }
1151 }
1152
1153 void CL_BeginDownloads_f(void)
1154 {
1155         // prevent cl_begindownloads from being issued multiple times in one match
1156         // to prevent accidentally cancelled downloads
1157         if(cl.loadbegun)
1158                 Con_DPrintf("cl_begindownloads is only valid once per match\n");
1159         else
1160                 CL_BeginDownloads(false);
1161 }
1162
1163 void CL_StopDownload(int size, int crc)
1164 {
1165         if (cls.qw_downloadmemory && cls.qw_downloadmemorycursize == size && CRC_Block(cls.qw_downloadmemory, cls.qw_downloadmemorycursize) == crc)
1166         {
1167                 int existingcrc;
1168                 size_t existingsize;
1169                 const char *extension;
1170
1171                 // finished file
1172                 // save to disk only if we don't already have it
1173                 // (this is mainly for playing back demos)
1174                 existingcrc = FS_CRCFile(cls.qw_downloadname, &existingsize);
1175                 if (existingsize)
1176                 {
1177                         if ((int)existingsize != size || existingcrc != crc)
1178                         {
1179                                 // we have a mismatching file, pick another name for it
1180                                 char name[MAX_QPATH*2];
1181                                 dpsnprintf(name, sizeof(name), "dlcache/%s.%i.%i", cls.qw_downloadname, size, crc);
1182                                 if (!FS_FileExists(name))
1183                                 {
1184                                         Con_Printf("Downloaded \"%s\" (%i bytes, %i CRC)\n", name, size, crc);
1185                                         FS_WriteFile(name, cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
1186                                 }
1187                         }
1188                 }
1189                 else
1190                 {
1191                         // we either don't have it or have a mismatching file...
1192                         // so it's time to accept the file
1193                         // but if we already have a mismatching file we need to rename
1194                         // this new one, and if we already have this file in renamed form,
1195                         // we do nothing
1196                         Con_Printf("Downloaded \"%s\" (%i bytes, %i CRC)\n", cls.qw_downloadname, size, crc);
1197                         FS_WriteFile(cls.qw_downloadname, cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
1198                         extension = FS_FileExtension(cls.qw_downloadname);
1199                         if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3"))
1200                                 FS_Rescan();
1201                 }
1202         }
1203         else if (cls.qw_downloadmemory && size)
1204         {
1205                 Con_Printf("Download \"%s\" is corrupt (%i bytes, %i CRC, should be %i bytes, %i CRC), discarding\n", cls.qw_downloadname, size, crc, (int)cls.qw_downloadmemorycursize, (int)CRC_Block(cls.qw_downloadmemory, cls.qw_downloadmemorycursize));
1206                 CL_BeginDownloads(true);
1207         }
1208
1209         if (cls.qw_downloadmemory)
1210                 Mem_Free(cls.qw_downloadmemory);
1211         cls.qw_downloadmemory = NULL;
1212         cls.qw_downloadname[0] = 0;
1213         cls.qw_downloadmemorymaxsize = 0;
1214         cls.qw_downloadmemorycursize = 0;
1215         cls.qw_downloadpercent = 0;
1216 }
1217
1218 void CL_ParseDownload(void)
1219 {
1220         int i, start, size;
1221         unsigned char data[65536];
1222         start = MSG_ReadLong();
1223         size = (unsigned short)MSG_ReadShort();
1224
1225         // record the start/size information to ack in the next input packet
1226         for (i = 0;i < CL_MAX_DOWNLOADACKS;i++)
1227         {
1228                 if (!cls.dp_downloadack[i].start && !cls.dp_downloadack[i].size)
1229                 {
1230                         cls.dp_downloadack[i].start = start;
1231                         cls.dp_downloadack[i].size = size;
1232                         break;
1233                 }
1234         }
1235
1236         MSG_ReadBytes(size, data);
1237
1238         if (!cls.qw_downloadname[0])
1239         {
1240                 if (size > 0)
1241                         Con_Printf("CL_ParseDownload: received %i bytes with no download active\n", size);
1242                 return;
1243         }
1244
1245         if (start + size > cls.qw_downloadmemorymaxsize)
1246                 Host_Error("corrupt download message\n");
1247
1248         // only advance cursize if the data is at the expected position
1249         // (gaps are unacceptable)
1250         memcpy(cls.qw_downloadmemory + start, data, size);
1251         cls.qw_downloadmemorycursize = start + size;
1252         cls.qw_downloadpercent = (int)floor((start+size) * 100.0 / cls.qw_downloadmemorymaxsize);
1253         cls.qw_downloadpercent = bound(0, cls.qw_downloadpercent, 100);
1254         cls.qw_downloadspeedcount += size;
1255 }
1256
1257 void CL_DownloadBegin_f(void)
1258 {
1259         int size = atoi(Cmd_Argv(1));
1260
1261         if (size < 0 || size > 1<<30 || FS_CheckNastyPath(Cmd_Argv(2), false))
1262         {
1263                 Con_Printf("cl_downloadbegin: received bogus information\n");
1264                 CL_StopDownload(0, 0);
1265                 return;
1266         }
1267
1268         if (cls.qw_downloadname[0])
1269                 Con_Printf("Download of %s aborted\n", cls.qw_downloadname);
1270
1271         CL_StopDownload(0, 0);
1272
1273         // we're really beginning a download now, so initialize stuff
1274         strlcpy(cls.qw_downloadname, Cmd_Argv(2), sizeof(cls.qw_downloadname));
1275         cls.qw_downloadmemorymaxsize = size;
1276         cls.qw_downloadmemory = Mem_Alloc(cls.permanentmempool, cls.qw_downloadmemorymaxsize);
1277         cls.qw_downloadnumber++;
1278
1279         Cmd_ForwardStringToServer("sv_startdownload");
1280 }
1281
1282 void CL_StopDownload_f(void)
1283 {
1284         if (cls.qw_downloadname[0])
1285         {
1286                 Con_Printf("Download of %s aborted\n", cls.qw_downloadname);
1287                 CL_StopDownload(0, 0);
1288         }
1289         CL_BeginDownloads(true);
1290 }
1291
1292 void CL_DownloadFinished_f(void)
1293 {
1294         if (Cmd_Argc() < 3)
1295         {
1296                 Con_Printf("Malformed cl_downloadfinished command\n");
1297                 return;
1298         }
1299         CL_StopDownload(atoi(Cmd_Argv(1)), atoi(Cmd_Argv(2)));
1300         CL_BeginDownloads(false);
1301 }
1302
1303 static void CL_SendPlayerInfo(void)
1304 {
1305         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1306         MSG_WriteString (&cls.netcon->message, va("name \"%s\"", cl_name.string));
1307
1308         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1309         MSG_WriteString (&cls.netcon->message, va("color %i %i", cl_color.integer >> 4, cl_color.integer & 15));
1310
1311         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1312         MSG_WriteString (&cls.netcon->message, va("rate %i", cl_rate.integer));
1313
1314         if (cl_pmodel.integer)
1315         {
1316                 MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1317                 MSG_WriteString (&cls.netcon->message, va("pmodel %i", cl_pmodel.integer));
1318         }
1319         if (*cl_playermodel.string)
1320         {
1321                 MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1322                 MSG_WriteString (&cls.netcon->message, va("playermodel %s", cl_playermodel.string));
1323         }
1324         if (*cl_playerskin.string)
1325         {
1326                 MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1327                 MSG_WriteString (&cls.netcon->message, va("playerskin %s", cl_playerskin.string));
1328         }
1329 }
1330
1331 /*
1332 =====================
1333 CL_SignonReply
1334
1335 An svc_signonnum has been received, perform a client side setup
1336 =====================
1337 */
1338 static void CL_SignonReply (void)
1339 {
1340         Con_DPrintf("CL_SignonReply: %i\n", cls.signon);
1341
1342         switch (cls.signon)
1343         {
1344         case 1:
1345                 if (cls.netcon)
1346                 {
1347                         // send player info before we begin downloads
1348                         // (so that the server can see the player name while downloading)
1349                         CL_SendPlayerInfo();
1350
1351                         // execute cl_begindownloads next frame
1352                         // (after any commands added by svc_stufftext have been executed)
1353                         // when done with downloads the "prespawn" will be sent
1354                         Cbuf_AddText("\ncl_begindownloads\n");
1355
1356                         //MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1357                         //MSG_WriteString (&cls.netcon->message, "prespawn");
1358                 }
1359                 else // playing a demo...  make sure loading occurs as soon as possible
1360                         CL_BeginDownloads(false);
1361                 break;
1362
1363         case 2:
1364                 if (cls.netcon)
1365                 {
1366                         // LordHavoc: quake sent the player info here but due to downloads
1367                         // it is sent earlier instead
1368                         // CL_SendPlayerInfo();
1369
1370                         // LordHavoc: changed to begin a loading stage and issue this when done
1371                         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1372                         MSG_WriteString (&cls.netcon->message, "spawn");
1373                 }
1374                 break;
1375
1376         case 3:
1377                 if (cls.netcon)
1378                 {
1379                         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1380                         MSG_WriteString (&cls.netcon->message, "begin");
1381                 }
1382                 break;
1383
1384         case 4:
1385                 Con_ClearNotify();
1386                 if (COM_CheckParm("-profilegameonly"))
1387                         Sys_AllowProfiling(true);
1388                 break;
1389         }
1390 }
1391
1392 /*
1393 ==================
1394 CL_ParseServerInfo
1395 ==================
1396 */
1397 void CL_ParseServerInfo (void)
1398 {
1399         char *str;
1400         int i;
1401         protocolversion_t protocol;
1402         int nummodels, numsounds;
1403
1404         Con_DPrint("Serverinfo packet received.\n");
1405
1406         // if server is active, we already began a loading plaque
1407         if (!sv.active)
1408         {
1409                 SCR_BeginLoadingPlaque();
1410                 S_StopAllSounds();
1411         }
1412
1413         // check memory integrity
1414         Mem_CheckSentinelsGlobal();
1415
1416         // clear cl_serverextension cvars
1417         Cvar_SetValueQuick(&cl_serverextension_download, 0);
1418
1419 //
1420 // wipe the client_state_t struct
1421 //
1422         CL_ClearState ();
1423
1424 // parse protocol version number
1425         i = MSG_ReadLong ();
1426         protocol = Protocol_EnumForNumber(i);
1427         if (protocol == PROTOCOL_UNKNOWN)
1428         {
1429                 Host_Error("CL_ParseServerInfo: Server is unrecognized protocol number (%i)", i);
1430                 return;
1431         }
1432         // hack for unmarked Nehahra movie demos which had a custom protocol
1433         if (protocol == PROTOCOL_QUAKEDP && cls.demoplayback && demo_nehahra.integer)
1434                 protocol = PROTOCOL_NEHAHRAMOVIE;
1435         cls.protocol = protocol;
1436         Con_DPrintf("Server protocol is %s\n", Protocol_NameForEnum(cls.protocol));
1437
1438         cl.num_entities = 1;
1439
1440         if (protocol == PROTOCOL_QUAKEWORLD)
1441         {
1442                 char gamedir[1][MAX_QPATH];
1443
1444                 cl.qw_servercount = MSG_ReadLong();
1445
1446                 str = MSG_ReadString();
1447                 Con_Printf("server gamedir is %s\n", str);
1448                 strlcpy(gamedir[0], str, sizeof(gamedir[0]));
1449
1450                 // change gamedir if needed
1451                 if (!FS_ChangeGameDirs(1, gamedir, true, false))
1452                         Host_Error("CL_ParseServerInfo: unable to switch to server specified gamedir");
1453
1454                 cl.gametype = GAME_DEATHMATCH;
1455                 cl.maxclients = 32;
1456
1457                 // parse player number
1458                 i = MSG_ReadByte();
1459                 // cl.qw_spectator is an unneeded flag, cl.scores[cl.playerentity].qw_spectator works better (it can be updated by the server during the game)
1460                 //cl.qw_spectator = (i & 128) != 0;
1461                 cl.realplayerentity = cl.playerentity = cl.viewentity = (i & 127) + 1;
1462                 cl.scores = (scoreboard_t *)Mem_Alloc(cls.levelmempool, cl.maxclients*sizeof(*cl.scores));
1463
1464                 // get the full level name
1465                 str = MSG_ReadString ();
1466                 strlcpy (cl.levelname, str, sizeof(cl.levelname));
1467
1468                 // get the movevars that are defined in the qw protocol
1469                 cl.movevars_gravity            = MSG_ReadFloat();
1470                 cl.movevars_stopspeed          = MSG_ReadFloat();
1471                 cl.movevars_maxspeed           = MSG_ReadFloat();
1472                 cl.movevars_spectatormaxspeed  = MSG_ReadFloat();
1473                 cl.movevars_accelerate         = MSG_ReadFloat();
1474                 cl.movevars_airaccelerate      = MSG_ReadFloat();
1475                 cl.movevars_wateraccelerate    = MSG_ReadFloat();
1476                 cl.movevars_friction           = MSG_ReadFloat();
1477                 cl.movevars_waterfriction      = MSG_ReadFloat();
1478                 cl.movevars_entgravity         = MSG_ReadFloat();
1479
1480                 // other movevars not in the protocol...
1481                 cl.movevars_wallfriction = 0;
1482                 cl.movevars_timescale = 1;
1483                 cl.movevars_jumpvelocity = 270;
1484                 cl.movevars_edgefriction = 2;
1485                 cl.movevars_maxairspeed = 30;
1486                 cl.movevars_stepheight = 18;
1487                 cl.movevars_airaccel_qw = 1;
1488                 cl.movevars_airaccel_sideways_friction = 0;
1489
1490                 // seperate the printfs so the server message can have a color
1491                 Con_Printf("\n\n\35\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\37\n\n\2%s\n", str);
1492
1493                 // check memory integrity
1494                 Mem_CheckSentinelsGlobal();
1495
1496                 if (cls.netcon)
1497                 {
1498                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1499                         MSG_WriteString(&cls.netcon->message, va("soundlist %i %i", cl.qw_servercount, 0));
1500                 }
1501
1502                 cl.loadbegun = false;
1503                 cl.loadfinished = false;
1504
1505                 cls.state = ca_connected;
1506                 cls.signon = 1;
1507
1508                 // note: on QW protocol we can't set up the gameworld until after
1509                 // downloads finish...
1510                 // (we don't even know the name of the map yet)
1511         }
1512         else
1513         {
1514         // parse maxclients
1515                 cl.maxclients = MSG_ReadByte ();
1516                 if (cl.maxclients < 1 || cl.maxclients > MAX_SCOREBOARD)
1517                 {
1518                         Host_Error("Bad maxclients (%u) from server", cl.maxclients);
1519                         return;
1520                 }
1521                 cl.scores = (scoreboard_t *)Mem_Alloc(cls.levelmempool, cl.maxclients*sizeof(*cl.scores));
1522
1523         // parse gametype
1524                 cl.gametype = MSG_ReadByte ();
1525
1526         // parse signon message
1527                 str = MSG_ReadString ();
1528                 strlcpy (cl.levelname, str, sizeof(cl.levelname));
1529
1530         // seperate the printfs so the server message can have a color
1531                 if (cls.protocol != PROTOCOL_NEHAHRAMOVIE) // no messages when playing the Nehahra movie
1532                         Con_Printf("\n\n\35\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\37\n\n\2%s\n", str);
1533
1534                 // check memory integrity
1535                 Mem_CheckSentinelsGlobal();
1536
1537                 // parse model precache list
1538                 for (nummodels=1 ; ; nummodels++)
1539                 {
1540                         str = MSG_ReadString();
1541                         if (!str[0])
1542                                 break;
1543                         if (nummodels==MAX_MODELS)
1544                                 Host_Error ("Server sent too many model precaches");
1545                         if (strlen(str) >= MAX_QPATH)
1546                                 Host_Error ("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
1547                         strlcpy (cl.model_name[nummodels], str, sizeof (cl.model_name[nummodels]));
1548                 }
1549                 // parse sound precache list
1550                 for (numsounds=1 ; ; numsounds++)
1551                 {
1552                         str = MSG_ReadString();
1553                         if (!str[0])
1554                                 break;
1555                         if (numsounds==MAX_SOUNDS)
1556                                 Host_Error("Server sent too many sound precaches");
1557                         if (strlen(str) >= MAX_QPATH)
1558                                 Host_Error("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
1559                         strlcpy (cl.sound_name[numsounds], str, sizeof (cl.sound_name[numsounds]));
1560                 }
1561
1562                 // touch all of the precached models that are still loaded so we can free
1563                 // anything that isn't needed
1564                 if (!sv.active)
1565                         Mod_ClearUsed();
1566                 for (i = 1;i < nummodels;i++)
1567                         Mod_FindName(cl.model_name[i]);
1568                 // precache any models used by the client (this also marks them used)
1569                 cl.model_bolt = Mod_ForName("progs/bolt.mdl", false, false, false);
1570                 cl.model_bolt2 = Mod_ForName("progs/bolt2.mdl", false, false, false);
1571                 cl.model_bolt3 = Mod_ForName("progs/bolt3.mdl", false, false, false);
1572                 cl.model_beam = Mod_ForName("progs/beam.mdl", false, false, false);
1573                 Mod_PurgeUnused();
1574
1575                 // do the same for sounds
1576                 // FIXME: S_ServerSounds does not know about cl.sfx_ sounds
1577                 S_ServerSounds (cl.sound_name, numsounds);
1578
1579                 // precache any sounds used by the client
1580                 cl.sfx_wizhit = S_PrecacheSound(cl_sound_wizardhit.string, false, true);
1581                 cl.sfx_knighthit = S_PrecacheSound(cl_sound_hknighthit.string, false, true);
1582                 cl.sfx_tink1 = S_PrecacheSound(cl_sound_tink1.string, false, true);
1583                 cl.sfx_ric1 = S_PrecacheSound(cl_sound_ric1.string, false, true);
1584                 cl.sfx_ric2 = S_PrecacheSound(cl_sound_ric2.string, false, true);
1585                 cl.sfx_ric3 = S_PrecacheSound(cl_sound_ric3.string, false, true);
1586                 cl.sfx_r_exp3 = S_PrecacheSound(cl_sound_r_exp3.string, false, true);
1587
1588                 // now we try to load everything that is new
1589                 cl.loadmodel_current = 1;
1590                 cl.downloadmodel_current = 1;
1591                 cl.loadmodel_total = nummodels;
1592                 cl.loadsound_current = 1;
1593                 cl.downloadsound_current = 1;
1594                 cl.loadsound_total = numsounds;
1595                 cl.downloadcsqc = true;
1596                 cl.loadbegun = false;
1597                 cl.loadfinished = false;
1598                 cl.loadcsqc = true;
1599         }
1600
1601         // check memory integrity
1602         Mem_CheckSentinelsGlobal();
1603
1604 // if cl_autodemo is set, automatically start recording a demo if one isn't being recorded already
1605         if (cl_autodemo.integer && cls.netcon && cls.protocol != PROTOCOL_QUAKEWORLD)
1606         {
1607                 char demofile[MAX_OSPATH];
1608                 char levelname[MAX_QPATH];
1609
1610                 if (cls.demorecording)
1611                 {
1612                         // finish the previous level's demo file
1613                         CL_Stop_f();
1614                 }
1615
1616                 // start a new demo file
1617                 strlcpy(levelname, FS_FileWithoutPath(cl.model_name[1]), sizeof(levelname));
1618                 if (strrchr(levelname, '.'))
1619                         *(strrchr(levelname, '.')) = 0;
1620                 dpsnprintf (demofile, sizeof(demofile), "%s_%s.dem", Sys_TimeString (cl_autodemo_nameformat.string), levelname);
1621
1622                 Con_Printf ("Auto-recording to %s.\n", demofile);
1623
1624                 cls.demofile = FS_Open (demofile, "wb", false, false);
1625                 if (cls.demofile)
1626                 {
1627                         cls.forcetrack = -1;
1628                         FS_Printf (cls.demofile, "%i\n", cls.forcetrack);
1629                         cls.demorecording = true;
1630                 }
1631                 else
1632                         Con_Print ("ERROR: couldn't open.\n");
1633         }
1634 }
1635
1636 void CL_ValidateState(entity_state_t *s)
1637 {
1638         model_t *model;
1639
1640         if (!s->active)
1641                 return;
1642
1643         if (s->modelindex >= MAX_MODELS)
1644                 Host_Error("CL_ValidateState: modelindex (%i) >= MAX_MODELS (%i)\n", s->modelindex, MAX_MODELS);
1645
1646         // these warnings are only warnings, no corrections are made to the state
1647         // because states are often copied for decoding, which otherwise would
1648         // propogate some of the corrections accidentally
1649         // (this used to happen, sometimes affecting skin and frame)
1650
1651         // colormap is client index + 1
1652         if ((!s->flags & RENDER_COLORMAPPED) && s->colormap > cl.maxclients)
1653                 Con_DPrintf("CL_ValidateState: colormap (%i) > cl.maxclients (%i)\n", s->colormap, cl.maxclients);
1654
1655         model = cl.model_precache[s->modelindex];
1656         if (model && model->type && s->frame >= model->numframes)
1657                 Con_DPrintf("CL_ValidateState: no such frame %i in \"%s\" (which has %i frames)\n", s->frame, model->name, model->numframes);
1658         if (model && model->type && s->skin > 0 && s->skin >= model->numskins && !(s->lightpflags & PFLAGS_FULLDYNAMIC))
1659                 Con_DPrintf("CL_ValidateState: no such skin %i in \"%s\" (which has %i skins)\n", s->skin, model->name, model->numskins);
1660 }
1661
1662 void CL_MoveLerpEntityStates(entity_t *ent)
1663 {
1664         float odelta[3], adelta[3];
1665         VectorSubtract(ent->state_current.origin, ent->persistent.neworigin, odelta);
1666         VectorSubtract(ent->state_current.angles, ent->persistent.newangles, adelta);
1667         if (!ent->state_previous.active || ent->state_previous.modelindex != ent->state_current.modelindex)
1668         {
1669                 // reset all persistent stuff if this is a new entity
1670                 ent->persistent.lerpdeltatime = 0;
1671                 ent->persistent.lerpstarttime = cl.mtime[1];
1672                 VectorCopy(ent->state_current.origin, ent->persistent.oldorigin);
1673                 VectorCopy(ent->state_current.angles, ent->persistent.oldangles);
1674                 VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
1675                 VectorCopy(ent->state_current.angles, ent->persistent.newangles);
1676                 // reset animation interpolation as well
1677                 ent->render.frame1 = ent->render.frame2 = ent->state_current.frame;
1678                 ent->render.frame1time = ent->render.frame2time = cl.time;
1679                 ent->render.framelerp = 1;
1680                 // reset various persistent stuff
1681                 ent->persistent.muzzleflash = 0;
1682                 ent->persistent.trail_allowed = false;
1683         }
1684         else if (DotProduct(odelta, odelta) > 1000*1000 || (cl.fixangle[0] && !cl.fixangle[1]))
1685         {
1686                 // don't interpolate the move
1687                 // (the fixangle[] check detects teleports, but not constant fixangles
1688                 //  such as when spectating)
1689                 ent->persistent.lerpdeltatime = 0;
1690                 ent->persistent.lerpstarttime = cl.mtime[1];
1691                 VectorCopy(ent->state_current.origin, ent->persistent.oldorigin);
1692                 VectorCopy(ent->state_current.angles, ent->persistent.oldangles);
1693                 VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
1694                 VectorCopy(ent->state_current.angles, ent->persistent.newangles);
1695                 ent->persistent.trail_allowed = false;
1696         }
1697         else if (ent->state_current.flags & RENDER_STEP)
1698         {
1699                 // monster interpolation
1700                 if (DotProduct(odelta, odelta) + DotProduct(adelta, adelta) > 0.01)
1701                 {
1702                         ent->persistent.lerpdeltatime = bound(0, cl.mtime[1] - ent->persistent.lerpstarttime, 0.1);
1703                         ent->persistent.lerpstarttime = cl.mtime[1];
1704                         VectorCopy(ent->persistent.neworigin, ent->persistent.oldorigin);
1705                         VectorCopy(ent->persistent.newangles, ent->persistent.oldangles);
1706                         VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
1707                         VectorCopy(ent->state_current.angles, ent->persistent.newangles);
1708                 }
1709         }
1710         else
1711         {
1712                 // not a monster
1713                 ent->persistent.lerpstarttime = ent->state_previous.time;
1714                 // no lerp if it's singleplayer
1715                 if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
1716                         ent->persistent.lerpdeltatime = 0;
1717                 else
1718                         ent->persistent.lerpdeltatime = bound(0, ent->state_current.time - ent->state_previous.time, 0.1);
1719                 VectorCopy(ent->persistent.neworigin, ent->persistent.oldorigin);
1720                 VectorCopy(ent->persistent.newangles, ent->persistent.oldangles);
1721                 VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
1722                 VectorCopy(ent->state_current.angles, ent->persistent.newangles);
1723         }
1724         // trigger muzzleflash effect if necessary
1725         if (ent->state_current.effects & EF_MUZZLEFLASH)
1726                 ent->persistent.muzzleflash = 1;
1727 }
1728
1729 /*
1730 ==================
1731 CL_ParseBaseline
1732 ==================
1733 */
1734 void CL_ParseBaseline (entity_t *ent, int large)
1735 {
1736         int i;
1737
1738         ent->state_baseline = defaultstate;
1739         // FIXME: set ent->state_baseline.number?
1740         ent->state_baseline.active = true;
1741         if (large)
1742         {
1743                 ent->state_baseline.modelindex = (unsigned short) MSG_ReadShort ();
1744                 ent->state_baseline.frame = (unsigned short) MSG_ReadShort ();
1745         }
1746         else if (cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
1747         {
1748                 ent->state_baseline.modelindex = (unsigned short) MSG_ReadShort ();
1749                 ent->state_baseline.frame = MSG_ReadByte ();
1750         }
1751         else
1752         {
1753                 ent->state_baseline.modelindex = MSG_ReadByte ();
1754                 ent->state_baseline.frame = MSG_ReadByte ();
1755         }
1756         ent->state_baseline.colormap = MSG_ReadByte();
1757         ent->state_baseline.skin = MSG_ReadByte();
1758         for (i = 0;i < 3;i++)
1759         {
1760                 ent->state_baseline.origin[i] = MSG_ReadCoord(cls.protocol);
1761                 ent->state_baseline.angles[i] = MSG_ReadAngle(cls.protocol);
1762         }
1763         ent->state_previous = ent->state_current = ent->state_baseline;
1764 }
1765
1766
1767 /*
1768 ==================
1769 CL_ParseClientdata
1770
1771 Server information pertaining to this client only
1772 ==================
1773 */
1774 void CL_ParseClientdata (void)
1775 {
1776         int i, bits;
1777
1778         VectorCopy (cl.mpunchangle[0], cl.mpunchangle[1]);
1779         VectorCopy (cl.mpunchvector[0], cl.mpunchvector[1]);
1780         VectorCopy (cl.mvelocity[0], cl.mvelocity[1]);
1781         cl.mviewzoom[1] = cl.mviewzoom[0];
1782
1783         if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4 || cls.protocol == PROTOCOL_DARKPLACES5)
1784         {
1785                 cl.stats[STAT_VIEWHEIGHT] = DEFAULT_VIEWHEIGHT;
1786                 cl.stats[STAT_ITEMS] = 0;
1787                 cl.stats[STAT_VIEWZOOM] = 255;
1788         }
1789         cl.idealpitch = 0;
1790         cl.mpunchangle[0][0] = 0;
1791         cl.mpunchangle[0][1] = 0;
1792         cl.mpunchangle[0][2] = 0;
1793         cl.mpunchvector[0][0] = 0;
1794         cl.mpunchvector[0][1] = 0;
1795         cl.mpunchvector[0][2] = 0;
1796         cl.mvelocity[0][0] = 0;
1797         cl.mvelocity[0][1] = 0;
1798         cl.mvelocity[0][2] = 0;
1799         cl.mviewzoom[0] = 1;
1800
1801         bits = (unsigned short) MSG_ReadShort ();
1802         if (bits & SU_EXTEND1)
1803                 bits |= (MSG_ReadByte() << 16);
1804         if (bits & SU_EXTEND2)
1805                 bits |= (MSG_ReadByte() << 24);
1806
1807         if (bits & SU_VIEWHEIGHT)
1808                 cl.stats[STAT_VIEWHEIGHT] = MSG_ReadChar ();
1809
1810         if (bits & SU_IDEALPITCH)
1811                 cl.idealpitch = MSG_ReadChar ();
1812
1813         for (i = 0;i < 3;i++)
1814         {
1815                 if (bits & (SU_PUNCH1<<i) )
1816                 {
1817                         if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
1818                                 cl.mpunchangle[0][i] = MSG_ReadChar();
1819                         else
1820                                 cl.mpunchangle[0][i] = MSG_ReadAngle16i();
1821                 }
1822                 if (bits & (SU_PUNCHVEC1<<i))
1823                 {
1824                         if (cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
1825                                 cl.mpunchvector[0][i] = MSG_ReadCoord16i();
1826                         else
1827                                 cl.mpunchvector[0][i] = MSG_ReadCoord32f();
1828                 }
1829                 if (bits & (SU_VELOCITY1<<i) )
1830                 {
1831                         if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
1832                                 cl.mvelocity[0][i] = MSG_ReadChar()*16;
1833                         else
1834                                 cl.mvelocity[0][i] = MSG_ReadCoord32f();
1835                 }
1836         }
1837
1838         // LordHavoc: hipnotic demos don't have this bit set but should
1839         if (bits & SU_ITEMS || cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4 || cls.protocol == PROTOCOL_DARKPLACES5)
1840                 cl.stats[STAT_ITEMS] = MSG_ReadLong ();
1841
1842         cl.onground = (bits & SU_ONGROUND) != 0;
1843         cl.inwater = (bits & SU_INWATER) != 0;
1844
1845         if (cls.protocol == PROTOCOL_DARKPLACES5)
1846         {
1847                 cl.stats[STAT_WEAPONFRAME] = (bits & SU_WEAPONFRAME) ? MSG_ReadShort() : 0;
1848                 cl.stats[STAT_ARMOR] = (bits & SU_ARMOR) ? MSG_ReadShort() : 0;
1849                 cl.stats[STAT_WEAPON] = (bits & SU_WEAPON) ? MSG_ReadShort() : 0;
1850                 cl.stats[STAT_HEALTH] = MSG_ReadShort();
1851                 cl.stats[STAT_AMMO] = MSG_ReadShort();
1852                 cl.stats[STAT_SHELLS] = MSG_ReadShort();
1853                 cl.stats[STAT_NAILS] = MSG_ReadShort();
1854                 cl.stats[STAT_ROCKETS] = MSG_ReadShort();
1855                 cl.stats[STAT_CELLS] = MSG_ReadShort();
1856                 cl.stats[STAT_ACTIVEWEAPON] = (unsigned short) MSG_ReadShort ();
1857         }
1858         else if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
1859         {
1860                 cl.stats[STAT_WEAPONFRAME] = (bits & SU_WEAPONFRAME) ? MSG_ReadByte() : 0;
1861                 cl.stats[STAT_ARMOR] = (bits & SU_ARMOR) ? MSG_ReadByte() : 0;
1862                 if (cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
1863                         cl.stats[STAT_WEAPON] = (bits & SU_WEAPON) ? (unsigned short)MSG_ReadShort() : 0;
1864                 else
1865                         cl.stats[STAT_WEAPON] = (bits & SU_WEAPON) ? MSG_ReadByte() : 0;
1866                 cl.stats[STAT_HEALTH] = MSG_ReadShort();
1867                 cl.stats[STAT_AMMO] = MSG_ReadByte();
1868                 cl.stats[STAT_SHELLS] = MSG_ReadByte();
1869                 cl.stats[STAT_NAILS] = MSG_ReadByte();
1870                 cl.stats[STAT_ROCKETS] = MSG_ReadByte();
1871                 cl.stats[STAT_CELLS] = MSG_ReadByte();
1872                 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
1873                         cl.stats[STAT_ACTIVEWEAPON] = (1<<MSG_ReadByte ());
1874                 else
1875                         cl.stats[STAT_ACTIVEWEAPON] = MSG_ReadByte ();
1876         }
1877
1878         if (bits & SU_VIEWZOOM)
1879         {
1880                 if (cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
1881                         cl.stats[STAT_VIEWZOOM] = MSG_ReadByte();
1882                 else
1883                         cl.stats[STAT_VIEWZOOM] = (unsigned short) MSG_ReadShort();
1884         }
1885
1886         // viewzoom interpolation
1887         cl.mviewzoom[0] = (float) max(cl.stats[STAT_VIEWZOOM], 2) * (1.0f / 255.0f);
1888 }
1889
1890 /*
1891 =====================
1892 CL_ParseStatic
1893 =====================
1894 */
1895 void CL_ParseStatic (int large)
1896 {
1897         entity_t *ent;
1898
1899         if (cl.num_static_entities >= cl.max_static_entities)
1900                 Host_Error ("Too many static entities");
1901         ent = &cl.static_entities[cl.num_static_entities++];
1902         CL_ParseBaseline (ent, large);
1903
1904         if (ent->state_baseline.modelindex == 0)
1905         {
1906                 Con_DPrintf("svc_parsestatic: static entity without model at %f %f %f\n", ent->state_baseline.origin[0], ent->state_baseline.origin[1], ent->state_baseline.origin[2]);
1907                 cl.num_static_entities--;
1908                 // This is definitely a cheesy way to conserve resources...
1909                 return;
1910         }
1911
1912 // copy it to the current state
1913         ent->render.model = cl.model_precache[ent->state_baseline.modelindex];
1914         ent->render.frame1 = ent->render.frame2 = ent->state_baseline.frame;
1915         ent->render.framelerp = 0;
1916         // make torchs play out of sync
1917         ent->render.frame1time = ent->render.frame2time = lhrandom(-10, -1);
1918         ent->render.skinnum = ent->state_baseline.skin;
1919         ent->render.effects = ent->state_baseline.effects;
1920         ent->render.alpha = 1;
1921
1922         //VectorCopy (ent->state_baseline.origin, ent->render.origin);
1923         //VectorCopy (ent->state_baseline.angles, ent->render.angles);
1924
1925         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, ent->state_baseline.origin[0], ent->state_baseline.origin[1], ent->state_baseline.origin[2], ent->state_baseline.angles[0], ent->state_baseline.angles[1], ent->state_baseline.angles[2], 1);
1926         CL_UpdateRenderEntity(&ent->render);
1927 }
1928
1929 /*
1930 ===================
1931 CL_ParseStaticSound
1932 ===================
1933 */
1934 void CL_ParseStaticSound (int large)
1935 {
1936         vec3_t          org;
1937         int                     sound_num, vol, atten;
1938
1939         MSG_ReadVector(org, cls.protocol);
1940         if (large || cls.protocol == PROTOCOL_NEHAHRABJP2)
1941                 sound_num = (unsigned short) MSG_ReadShort ();
1942         else
1943                 sound_num = MSG_ReadByte ();
1944         vol = MSG_ReadByte ();
1945         atten = MSG_ReadByte ();
1946
1947         S_StaticSound (cl.sound_precache[sound_num], org, vol/255.0f, atten);
1948 }
1949
1950 void CL_ParseEffect (void)
1951 {
1952         vec3_t          org;
1953         int                     modelindex, startframe, framecount, framerate;
1954
1955         MSG_ReadVector(org, cls.protocol);
1956         modelindex = MSG_ReadByte ();
1957         startframe = MSG_ReadByte ();
1958         framecount = MSG_ReadByte ();
1959         framerate = MSG_ReadByte ();
1960
1961         CL_Effect(org, modelindex, startframe, framecount, framerate);
1962 }
1963
1964 void CL_ParseEffect2 (void)
1965 {
1966         vec3_t          org;
1967         int                     modelindex, startframe, framecount, framerate;
1968
1969         MSG_ReadVector(org, cls.protocol);
1970         modelindex = (unsigned short) MSG_ReadShort ();
1971         startframe = (unsigned short) MSG_ReadShort ();
1972         framecount = MSG_ReadByte ();
1973         framerate = MSG_ReadByte ();
1974
1975         CL_Effect(org, modelindex, startframe, framecount, framerate);
1976 }
1977
1978 void CL_NewBeam (int ent, vec3_t start, vec3_t end, model_t *m, int lightning)
1979 {
1980         int i;
1981         beam_t *b = NULL;
1982
1983         if (ent >= MAX_EDICTS)
1984         {
1985                 Con_Printf("CL_NewBeam: invalid entity number %i\n", ent);
1986                 ent = 0;
1987         }
1988
1989         if (ent >= cl.max_entities)
1990                 CL_ExpandEntities(ent);
1991
1992         // override any beam with the same entity
1993         i = cl.max_beams;
1994         if (ent)
1995                 for (i = 0, b = cl.beams;i < cl.max_beams;i++, b++)
1996                         if (b->entity == ent)
1997                                 break;
1998         // if the entity was not found then just replace an unused beam
1999         if (i == cl.max_beams)
2000                 for (i = 0, b = cl.beams;i < cl.max_beams;i++, b++)
2001                         if (!b->model)
2002                                 break;
2003         if (i < cl.max_beams)
2004         {
2005                 cl.num_beams = max(cl.num_beams, i + 1);
2006                 b->entity = ent;
2007                 b->lightning = lightning;
2008                 b->model = m;
2009                 b->endtime = cl.mtime[0] + 0.2;
2010                 VectorCopy (start, b->start);
2011                 VectorCopy (end, b->end);
2012         }
2013         else
2014                 Con_Print("beam list overflow!\n");
2015 }
2016
2017 void CL_ParseBeam (model_t *m, int lightning)
2018 {
2019         int ent;
2020         vec3_t start, end;
2021
2022         ent = (unsigned short) MSG_ReadShort ();
2023         MSG_ReadVector(start, cls.protocol);
2024         MSG_ReadVector(end, cls.protocol);
2025
2026         if (ent >= MAX_EDICTS)
2027         {
2028                 Con_Printf("CL_ParseBeam: invalid entity number %i\n", ent);
2029                 ent = 0;
2030         }
2031
2032         CL_NewBeam(ent, start, end, m, lightning);
2033 }
2034
2035 void CL_ParseTempEntity(void)
2036 {
2037         int type;
2038         vec3_t pos, pos2;
2039         vec3_t vel1, vel2;
2040         vec3_t dir;
2041         vec3_t color;
2042         int rnd;
2043         int colorStart, colorLength, count;
2044         float velspeed, radius;
2045         unsigned char *tempcolor;
2046         matrix4x4_t tempmatrix;
2047
2048         if (cls.protocol == PROTOCOL_QUAKEWORLD)
2049         {
2050                 type = MSG_ReadByte();
2051                 switch (type)
2052                 {
2053                 case QW_TE_WIZSPIKE:
2054                         // spike hitting wall
2055                         MSG_ReadVector(pos, cls.protocol);
2056                         CL_FindNonSolidLocation(pos, pos, 4);
2057                         CL_ParticleEffect(EFFECT_TE_WIZSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2058                         S_StartSound(-1, 0, cl.sfx_wizhit, pos, 1, 1);
2059                         break;
2060
2061                 case QW_TE_KNIGHTSPIKE:
2062                         // spike hitting wall
2063                         MSG_ReadVector(pos, cls.protocol);
2064                         CL_FindNonSolidLocation(pos, pos, 4);
2065                         CL_ParticleEffect(EFFECT_TE_KNIGHTSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2066                         S_StartSound(-1, 0, cl.sfx_knighthit, pos, 1, 1);
2067                         break;
2068
2069                 case QW_TE_SPIKE:
2070                         // spike hitting wall
2071                         MSG_ReadVector(pos, cls.protocol);
2072                         CL_FindNonSolidLocation(pos, pos, 4);
2073                         CL_ParticleEffect(EFFECT_TE_SPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2074                         if (rand() % 5)
2075                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2076                         else
2077                         {
2078                                 rnd = rand() & 3;
2079                                 if (rnd == 1)
2080                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2081                                 else if (rnd == 2)
2082                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2083                                 else
2084                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2085                         }
2086                         break;
2087                 case QW_TE_SUPERSPIKE:
2088                         // super spike hitting wall
2089                         MSG_ReadVector(pos, cls.protocol);
2090                         CL_FindNonSolidLocation(pos, pos, 4);
2091                         CL_ParticleEffect(EFFECT_TE_SUPERSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2092                         if (rand() % 5)
2093                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2094                         else
2095                         {
2096                                 rnd = rand() & 3;
2097                                 if (rnd == 1)
2098                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2099                                 else if (rnd == 2)
2100                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2101                                 else
2102                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2103                         }
2104                         break;
2105
2106                 case QW_TE_EXPLOSION:
2107                         // rocket explosion
2108                         MSG_ReadVector(pos, cls.protocol);
2109                         CL_FindNonSolidLocation(pos, pos, 10);
2110                         CL_ParticleEffect(EFFECT_TE_EXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2111                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2112                         CL_Effect(pos, cl.qw_modelindex_s_explod, 0, 6, 10);
2113                         break;
2114
2115                 case QW_TE_TAREXPLOSION:
2116                         // tarbaby explosion
2117                         MSG_ReadVector(pos, cls.protocol);
2118                         CL_FindNonSolidLocation(pos, pos, 10);
2119                         CL_ParticleEffect(EFFECT_TE_TAREXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2120                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2121                         break;
2122
2123                 case QW_TE_LIGHTNING1:
2124                         // lightning bolts
2125                         CL_ParseBeam(cl.model_bolt, true);
2126                         break;
2127
2128                 case QW_TE_LIGHTNING2:
2129                         // lightning bolts
2130                         CL_ParseBeam(cl.model_bolt2, true);
2131                         break;
2132
2133                 case QW_TE_LIGHTNING3:
2134                         // lightning bolts
2135                         CL_ParseBeam(cl.model_bolt3, false);
2136                         break;
2137
2138                 case QW_TE_LAVASPLASH:
2139                         MSG_ReadVector(pos, cls.protocol);
2140                         CL_ParticleEffect(EFFECT_TE_LAVASPLASH, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2141                         break;
2142
2143                 case QW_TE_TELEPORT:
2144                         MSG_ReadVector(pos, cls.protocol);
2145                         CL_ParticleEffect(EFFECT_TE_TELEPORT, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2146                         break;
2147
2148                 case QW_TE_GUNSHOT:
2149                         // bullet hitting wall
2150                         radius = MSG_ReadByte();
2151                         MSG_ReadVector(pos, cls.protocol);
2152                         CL_FindNonSolidLocation(pos, pos, 4);
2153                         VectorSet(pos2, pos[0] + radius, pos[1] + radius, pos[2] + radius);
2154                         VectorSet(pos, pos[0] - radius, pos[1] - radius, pos[2] - radius);
2155                         CL_ParticleEffect(EFFECT_TE_GUNSHOT, radius, pos, pos2, vec3_origin, vec3_origin, NULL, 0);
2156                         if(cl_sound_ric_gunshot.integer & RIC_GUNSHOT)
2157                         {
2158                                 if (rand() % 5)
2159                                         S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2160                                 else
2161                                 {
2162                                         rnd = rand() & 3;
2163                                         if (rnd == 1)
2164                                                 S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2165                                         else if (rnd == 2)
2166                                                 S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2167                                         else
2168                                                 S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2169                                 }
2170                         }
2171                         break;
2172
2173                 case QW_TE_BLOOD:
2174                         count = MSG_ReadByte();
2175                         MSG_ReadVector(pos, cls.protocol);
2176                         CL_FindNonSolidLocation(pos, pos, 4);
2177                         CL_ParticleEffect(EFFECT_TE_BLOOD, count, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2178                         break;
2179
2180                 case QW_TE_LIGHTNINGBLOOD:
2181                         MSG_ReadVector(pos, cls.protocol);
2182                         CL_FindNonSolidLocation(pos, pos, 4);
2183                         CL_ParticleEffect(EFFECT_TE_BLOOD, 2.5, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2184                         break;
2185
2186                 default:
2187                         Host_Error("CL_ParseTempEntity: bad type %d (hex %02X)", type, type);
2188                 }
2189         }
2190         else
2191         {
2192                 type = MSG_ReadByte();
2193                 switch (type)
2194                 {
2195                 case TE_WIZSPIKE:
2196                         // spike hitting wall
2197                         MSG_ReadVector(pos, cls.protocol);
2198                         CL_FindNonSolidLocation(pos, pos, 4);
2199                         CL_ParticleEffect(EFFECT_TE_WIZSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2200                         S_StartSound(-1, 0, cl.sfx_wizhit, pos, 1, 1);
2201                         break;
2202
2203                 case TE_KNIGHTSPIKE:
2204                         // spike hitting wall
2205                         MSG_ReadVector(pos, cls.protocol);
2206                         CL_FindNonSolidLocation(pos, pos, 4);
2207                         CL_ParticleEffect(EFFECT_TE_KNIGHTSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2208                         S_StartSound(-1, 0, cl.sfx_knighthit, pos, 1, 1);
2209                         break;
2210
2211                 case TE_SPIKE:
2212                         // spike hitting wall
2213                         MSG_ReadVector(pos, cls.protocol);
2214                         CL_FindNonSolidLocation(pos, pos, 4);
2215                         CL_ParticleEffect(EFFECT_TE_SPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2216                         if (rand() % 5)
2217                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2218                         else
2219                         {
2220                                 rnd = rand() & 3;
2221                                 if (rnd == 1)
2222                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2223                                 else if (rnd == 2)
2224                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2225                                 else
2226                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2227                         }
2228                         break;
2229                 case TE_SPIKEQUAD:
2230                         // quad spike hitting wall
2231                         MSG_ReadVector(pos, cls.protocol);
2232                         CL_FindNonSolidLocation(pos, pos, 4);
2233                         CL_ParticleEffect(EFFECT_TE_SPIKEQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2234                         if (rand() % 5)
2235                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2236                         else
2237                         {
2238                                 rnd = rand() & 3;
2239                                 if (rnd == 1)
2240                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2241                                 else if (rnd == 2)
2242                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2243                                 else
2244                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2245                         }
2246                         break;
2247                 case TE_SUPERSPIKE:
2248                         // super spike hitting wall
2249                         MSG_ReadVector(pos, cls.protocol);
2250                         CL_FindNonSolidLocation(pos, pos, 4);
2251                         CL_ParticleEffect(EFFECT_TE_SUPERSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2252                         if (rand() % 5)
2253                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2254                         else
2255                         {
2256                                 rnd = rand() & 3;
2257                                 if (rnd == 1)
2258                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2259                                 else if (rnd == 2)
2260                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2261                                 else
2262                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2263                         }
2264                         break;
2265                 case TE_SUPERSPIKEQUAD:
2266                         // quad super spike hitting wall
2267                         MSG_ReadVector(pos, cls.protocol);
2268                         CL_FindNonSolidLocation(pos, pos, 4);
2269                         CL_ParticleEffect(EFFECT_TE_SUPERSPIKEQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2270                         if (rand() % 5)
2271                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2272                         else
2273                         {
2274                                 rnd = rand() & 3;
2275                                 if (rnd == 1)
2276                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2277                                 else if (rnd == 2)
2278                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2279                                 else
2280                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2281                         }
2282                         break;
2283                         // LordHavoc: added for improved blood splatters
2284                 case TE_BLOOD:
2285                         // blood puff
2286                         MSG_ReadVector(pos, cls.protocol);
2287                         CL_FindNonSolidLocation(pos, pos, 4);
2288                         dir[0] = MSG_ReadChar();
2289                         dir[1] = MSG_ReadChar();
2290                         dir[2] = MSG_ReadChar();
2291                         count = MSG_ReadByte();
2292                         CL_ParticleEffect(EFFECT_TE_BLOOD, count, pos, pos, dir, dir, NULL, 0);
2293                         break;
2294                 case TE_SPARK:
2295                         // spark shower
2296                         MSG_ReadVector(pos, cls.protocol);
2297                         CL_FindNonSolidLocation(pos, pos, 4);
2298                         dir[0] = MSG_ReadChar();
2299                         dir[1] = MSG_ReadChar();
2300                         dir[2] = MSG_ReadChar();
2301                         count = MSG_ReadByte();
2302                         CL_ParticleEffect(EFFECT_TE_SPARK, count, pos, pos, dir, dir, NULL, 0);
2303                         break;
2304                 case TE_PLASMABURN:
2305                         MSG_ReadVector(pos, cls.protocol);
2306                         CL_FindNonSolidLocation(pos, pos, 4);
2307                         CL_ParticleEffect(EFFECT_TE_PLASMABURN, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2308                         break;
2309                         // LordHavoc: added for improved gore
2310                 case TE_BLOODSHOWER:
2311                         // vaporized body
2312                         MSG_ReadVector(pos, cls.protocol); // mins
2313                         MSG_ReadVector(pos2, cls.protocol); // maxs
2314                         velspeed = MSG_ReadCoord(cls.protocol); // speed
2315                         count = (unsigned short) MSG_ReadShort(); // number of particles
2316                         vel1[0] = -velspeed;
2317                         vel1[1] = -velspeed;
2318                         vel1[2] = -velspeed;
2319                         vel2[0] = velspeed;
2320                         vel2[1] = velspeed;
2321                         vel2[2] = velspeed;
2322                         CL_ParticleEffect(EFFECT_TE_BLOOD, count, pos, pos2, vel1, vel2, NULL, 0);
2323                         break;
2324
2325                 case TE_PARTICLECUBE:
2326                         // general purpose particle effect
2327                         MSG_ReadVector(pos, cls.protocol); // mins
2328                         MSG_ReadVector(pos2, cls.protocol); // maxs
2329                         MSG_ReadVector(dir, cls.protocol); // dir
2330                         count = (unsigned short) MSG_ReadShort(); // number of particles
2331                         colorStart = MSG_ReadByte(); // color
2332                         colorLength = MSG_ReadByte(); // gravity (1 or 0)
2333                         velspeed = MSG_ReadCoord(cls.protocol); // randomvel
2334                         CL_ParticleCube(pos, pos2, dir, count, colorStart, colorLength != 0, velspeed);
2335                         break;
2336
2337                 case TE_PARTICLERAIN:
2338                         // general purpose particle effect
2339                         MSG_ReadVector(pos, cls.protocol); // mins
2340                         MSG_ReadVector(pos2, cls.protocol); // maxs
2341                         MSG_ReadVector(dir, cls.protocol); // dir
2342                         count = (unsigned short) MSG_ReadShort(); // number of particles
2343                         colorStart = MSG_ReadByte(); // color
2344                         CL_ParticleRain(pos, pos2, dir, count, colorStart, 0);
2345                         break;
2346
2347                 case TE_PARTICLESNOW:
2348                         // general purpose particle effect
2349                         MSG_ReadVector(pos, cls.protocol); // mins
2350                         MSG_ReadVector(pos2, cls.protocol); // maxs
2351                         MSG_ReadVector(dir, cls.protocol); // dir
2352                         count = (unsigned short) MSG_ReadShort(); // number of particles
2353                         colorStart = MSG_ReadByte(); // color
2354                         CL_ParticleRain(pos, pos2, dir, count, colorStart, 1);
2355                         break;
2356
2357                 case TE_GUNSHOT:
2358                         // bullet hitting wall
2359                         MSG_ReadVector(pos, cls.protocol);
2360                         CL_FindNonSolidLocation(pos, pos, 4);
2361                         CL_ParticleEffect(EFFECT_TE_GUNSHOT, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2362                         if(cl_sound_ric_gunshot.integer & RIC_GUNSHOT)
2363                         {
2364                                 if (rand() % 5)
2365                                         S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2366                                 else
2367                                 {
2368                                         rnd = rand() & 3;
2369                                         if (rnd == 1)
2370                                                 S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2371                                         else if (rnd == 2)
2372                                                 S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2373                                         else
2374                                                 S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2375                                 }
2376                         }
2377                         break;
2378
2379                 case TE_GUNSHOTQUAD:
2380                         // quad bullet hitting wall
2381                         MSG_ReadVector(pos, cls.protocol);
2382                         CL_FindNonSolidLocation(pos, pos, 4);
2383                         CL_ParticleEffect(EFFECT_TE_GUNSHOTQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2384                         if(cl_sound_ric_gunshot.integer & RIC_GUNSHOTQUAD)
2385                         {
2386                                 if (rand() % 5)
2387                                         S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2388                                 else
2389                                 {
2390                                         rnd = rand() & 3;
2391                                         if (rnd == 1)
2392                                                 S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2393                                         else if (rnd == 2)
2394                                                 S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2395                                         else
2396                                                 S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2397                                 }
2398                         }
2399                         break;
2400
2401                 case TE_EXPLOSION:
2402                         // rocket explosion
2403                         MSG_ReadVector(pos, cls.protocol);
2404                         CL_FindNonSolidLocation(pos, pos, 10);
2405                         CL_ParticleEffect(EFFECT_TE_EXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2406                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2407                         break;
2408
2409                 case TE_EXPLOSIONQUAD:
2410                         // quad rocket explosion
2411                         MSG_ReadVector(pos, cls.protocol);
2412                         CL_FindNonSolidLocation(pos, pos, 10);
2413                         CL_ParticleEffect(EFFECT_TE_EXPLOSIONQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2414                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2415                         break;
2416
2417                 case TE_EXPLOSION3:
2418                         // Nehahra movie colored lighting explosion
2419                         MSG_ReadVector(pos, cls.protocol);
2420                         CL_FindNonSolidLocation(pos, pos, 10);
2421                         color[0] = MSG_ReadCoord(cls.protocol) * (2.0f / 1.0f);
2422                         color[1] = MSG_ReadCoord(cls.protocol) * (2.0f / 1.0f);
2423                         color[2] = MSG_ReadCoord(cls.protocol) * (2.0f / 1.0f);
2424                         CL_ParticleExplosion(pos);
2425                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2426                         CL_AllocLightFlash(NULL, &tempmatrix, 350, color[0], color[1], color[2], 700, 0.5, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2427                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2428                         break;
2429
2430                 case TE_EXPLOSIONRGB:
2431                         // colored lighting explosion
2432                         MSG_ReadVector(pos, cls.protocol);
2433                         CL_FindNonSolidLocation(pos, pos, 10);
2434                         CL_ParticleExplosion(pos);
2435                         color[0] = MSG_ReadByte() * (2.0f / 255.0f);
2436                         color[1] = MSG_ReadByte() * (2.0f / 255.0f);
2437                         color[2] = MSG_ReadByte() * (2.0f / 255.0f);
2438                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2439                         CL_AllocLightFlash(NULL, &tempmatrix, 350, color[0], color[1], color[2], 700, 0.5, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2440                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2441                         break;
2442
2443                 case TE_TAREXPLOSION:
2444                         // tarbaby explosion
2445                         MSG_ReadVector(pos, cls.protocol);
2446                         CL_FindNonSolidLocation(pos, pos, 10);
2447                         CL_ParticleEffect(EFFECT_TE_TAREXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2448                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2449                         break;
2450
2451                 case TE_SMALLFLASH:
2452                         MSG_ReadVector(pos, cls.protocol);
2453                         CL_FindNonSolidLocation(pos, pos, 10);
2454                         CL_ParticleEffect(EFFECT_TE_SMALLFLASH, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2455                         break;
2456
2457                 case TE_CUSTOMFLASH:
2458                         MSG_ReadVector(pos, cls.protocol);
2459                         CL_FindNonSolidLocation(pos, pos, 4);
2460                         radius = (MSG_ReadByte() + 1) * 8;
2461                         velspeed = (MSG_ReadByte() + 1) * (1.0 / 256.0);
2462                         color[0] = MSG_ReadByte() * (2.0f / 255.0f);
2463                         color[1] = MSG_ReadByte() * (2.0f / 255.0f);
2464                         color[2] = MSG_ReadByte() * (2.0f / 255.0f);
2465                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2466                         CL_AllocLightFlash(NULL, &tempmatrix, radius, color[0], color[1], color[2], radius / velspeed, velspeed, 0, -1, true, 1, 0.25, 1, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2467                         break;
2468
2469                 case TE_FLAMEJET:
2470                         MSG_ReadVector(pos, cls.protocol);
2471                         MSG_ReadVector(dir, cls.protocol);
2472                         count = MSG_ReadByte();
2473                         CL_ParticleEffect(EFFECT_TE_FLAMEJET, count, pos, pos, dir, dir, NULL, 0);
2474                         break;
2475
2476                 case TE_LIGHTNING1:
2477                         // lightning bolts
2478                         CL_ParseBeam(cl.model_bolt, true);
2479                         break;
2480
2481                 case TE_LIGHTNING2:
2482                         // lightning bolts
2483                         CL_ParseBeam(cl.model_bolt2, true);
2484                         break;
2485
2486                 case TE_LIGHTNING3:
2487                         // lightning bolts
2488                         CL_ParseBeam(cl.model_bolt3, false);
2489                         break;
2490
2491         // PGM 01/21/97
2492                 case TE_BEAM:
2493                         // grappling hook beam
2494                         CL_ParseBeam(cl.model_beam, false);
2495                         break;
2496         // PGM 01/21/97
2497
2498         // LordHavoc: for compatibility with the Nehahra movie...
2499                 case TE_LIGHTNING4NEH:
2500                         CL_ParseBeam(Mod_ForName(MSG_ReadString(), true, false, false), false);
2501                         break;
2502
2503                 case TE_LAVASPLASH:
2504                         MSG_ReadVector(pos, cls.protocol);
2505                         CL_ParticleEffect(EFFECT_TE_LAVASPLASH, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2506                         break;
2507
2508                 case TE_TELEPORT:
2509                         MSG_ReadVector(pos, cls.protocol);
2510                         CL_ParticleEffect(EFFECT_TE_TELEPORT, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2511                         break;
2512
2513                 case TE_EXPLOSION2:
2514                         // color mapped explosion
2515                         MSG_ReadVector(pos, cls.protocol);
2516                         CL_FindNonSolidLocation(pos, pos, 10);
2517                         colorStart = MSG_ReadByte();
2518                         colorLength = MSG_ReadByte();
2519                         CL_ParticleExplosion2(pos, colorStart, colorLength);
2520                         tempcolor = palette_rgb[(rand()%colorLength) + colorStart];
2521                         color[0] = tempcolor[0] * (2.0f / 255.0f);
2522                         color[1] = tempcolor[1] * (2.0f / 255.0f);
2523                         color[2] = tempcolor[2] * (2.0f / 255.0f);
2524                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2525                         CL_AllocLightFlash(NULL, &tempmatrix, 350, color[0], color[1], color[2], 700, 0.5, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2526                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2527                         break;
2528
2529                 case TE_TEI_G3:
2530                         MSG_ReadVector(pos, cls.protocol);
2531                         MSG_ReadVector(pos2, cls.protocol);
2532                         MSG_ReadVector(dir, cls.protocol);
2533                         CL_ParticleEffect(EFFECT_TE_TEI_G3, 1, pos, pos2, dir, dir, NULL, 0);
2534                         break;
2535
2536                 case TE_TEI_SMOKE:
2537                         MSG_ReadVector(pos, cls.protocol);
2538                         MSG_ReadVector(dir, cls.protocol);
2539                         count = MSG_ReadByte();
2540                         CL_FindNonSolidLocation(pos, pos, 4);
2541                         CL_ParticleEffect(EFFECT_TE_TEI_SMOKE, count, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2542                         break;
2543
2544                 case TE_TEI_BIGEXPLOSION:
2545                         MSG_ReadVector(pos, cls.protocol);
2546                         CL_FindNonSolidLocation(pos, pos, 10);
2547                         CL_ParticleEffect(EFFECT_TE_TEI_BIGEXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2548                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2549                         break;
2550
2551                 case TE_TEI_PLASMAHIT:
2552                         MSG_ReadVector(pos, cls.protocol);
2553                         MSG_ReadVector(dir, cls.protocol);
2554                         count = MSG_ReadByte();
2555                         CL_FindNonSolidLocation(pos, pos, 5);
2556                         CL_ParticleEffect(EFFECT_TE_TEI_PLASMAHIT, count, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2557                         break;
2558
2559                 default:
2560                         Host_Error("CL_ParseTempEntity: bad type %d (hex %02X)", type, type);
2561                 }
2562         }
2563 }
2564
2565 void CL_ParseTrailParticles(void)
2566 {
2567         int entityindex;
2568         int effectindex;
2569         vec3_t start, end;
2570         entityindex = (unsigned short)MSG_ReadShort();
2571         if (entityindex >= MAX_EDICTS)
2572                 entityindex = 0;
2573         if (entityindex >= cl.max_entities)
2574                 CL_ExpandEntities(entityindex);
2575         effectindex = (unsigned short)MSG_ReadShort();
2576         MSG_ReadVector(start, cls.protocol);
2577         MSG_ReadVector(end, cls.protocol);
2578         CL_ParticleEffect(effectindex, VectorDistance(start, end), start, end, vec3_origin, vec3_origin, entityindex > 0 ? cl.entities + entityindex : NULL, 0);
2579 }
2580
2581 void CL_ParsePointParticles(void)
2582 {
2583         int effectindex, count;
2584         vec3_t origin, velocity;
2585         effectindex = (unsigned short)MSG_ReadShort();
2586         MSG_ReadVector(origin, cls.protocol);
2587         MSG_ReadVector(velocity, cls.protocol);
2588         count = (unsigned short)MSG_ReadShort();
2589         CL_ParticleEffect(effectindex, count, origin, origin, velocity, velocity, NULL, 0);
2590 }
2591
2592 void CL_ParsePointParticles1(void)
2593 {
2594         int effectindex;
2595         vec3_t origin;
2596         effectindex = (unsigned short)MSG_ReadShort();
2597         MSG_ReadVector(origin, cls.protocol);
2598         CL_ParticleEffect(effectindex, 1, origin, origin, vec3_origin, vec3_origin, NULL, 0);
2599 }
2600
2601 typedef struct cl_iplog_item_s
2602 {
2603         char *address;
2604         char *name;
2605 }
2606 cl_iplog_item_t;
2607
2608 static qboolean cl_iplog_loaded = false;
2609 static int cl_iplog_numitems = 0;
2610 static int cl_iplog_maxitems = 0;
2611 static cl_iplog_item_t *cl_iplog_items;
2612
2613 static void CL_IPLog_Load(void);
2614 static void CL_IPLog_Add(const char *address, const char *name, qboolean checkexisting, qboolean addtofile)
2615 {
2616         int i;
2617         if (!address || !address[0] || !name || !name[0])
2618                 return;
2619         if (!cl_iplog_loaded)
2620                 CL_IPLog_Load();
2621         if (developer.integer >= 100)
2622                 Con_Printf("CL_IPLog_Add(\"%s\", \"%s\", %i, %i);\n", address, name, checkexisting, addtofile);
2623         // see if it already exists
2624         if (checkexisting)
2625         {
2626                 for (i = 0;i < cl_iplog_numitems;i++)
2627                 {
2628                         if (!strcmp(cl_iplog_items[i].address, address) && !strcmp(cl_iplog_items[i].name, name))
2629                         {
2630                                 if (developer.integer >= 100)
2631                                         Con_Printf("... found existing \"%s\" \"%s\"\n", cl_iplog_items[i].address, cl_iplog_items[i].name);
2632                                 return;
2633                         }
2634                 }
2635         }
2636         // it does not already exist in the iplog, so add it
2637         if (cl_iplog_maxitems <= cl_iplog_numitems || !cl_iplog_items)
2638         {
2639                 cl_iplog_item_t *olditems = cl_iplog_items;
2640                 cl_iplog_maxitems = max(1024, cl_iplog_maxitems + 256);
2641                 cl_iplog_items = Mem_Alloc(cls.permanentmempool, cl_iplog_maxitems * sizeof(cl_iplog_item_t));
2642                 if (olditems)
2643                 {
2644                         if (cl_iplog_numitems)
2645                                 memcpy(cl_iplog_items, olditems, cl_iplog_numitems * sizeof(cl_iplog_item_t));
2646                         Mem_Free(olditems);
2647                 }
2648         }
2649         cl_iplog_items[cl_iplog_numitems].address = Mem_Alloc(cls.permanentmempool, strlen(address) + 1);
2650         cl_iplog_items[cl_iplog_numitems].name = Mem_Alloc(cls.permanentmempool, strlen(name) + 1);
2651         strlcpy(cl_iplog_items[cl_iplog_numitems].address, address, strlen(address) + 1);
2652         // TODO: maybe it would be better to strip weird characters from name when
2653         // copying it here rather than using a straight strcpy?
2654         strlcpy(cl_iplog_items[cl_iplog_numitems].name, name, strlen(name) + 1);
2655         cl_iplog_numitems++;
2656         if (addtofile)
2657         {
2658                 // add it to the iplog.txt file
2659                 // TODO: this ought to open the one in the userpath version of the base
2660                 // gamedir, not the current gamedir
2661                 Log_Printf(cl_iplog_name.string, "%s %s\n", address, name);
2662                 if (developer.integer >= 100)
2663                         Con_Printf("CL_IPLog_Add: appending this line to %s: %s %s\n", cl_iplog_name.string, address, name);
2664         }
2665 }
2666
2667 static void CL_IPLog_Load(void)
2668 {
2669         int i, len, linenumber;
2670         char *text, *textend;
2671         unsigned char *filedata;
2672         fs_offset_t filesize;
2673         char line[MAX_INPUTLINE];
2674         char address[MAX_INPUTLINE];
2675         cl_iplog_loaded = true;
2676         // TODO: this ought to open the one in the userpath version of the base
2677         // gamedir, not the current gamedir
2678         filedata = FS_LoadFile(cl_iplog_name.string, tempmempool, true, &filesize);
2679         if (!filedata)
2680                 return;
2681         text = (char *)filedata;
2682         textend = text + filesize;
2683         for (linenumber = 1;text < textend;linenumber++)
2684         {
2685                 for (len = 0;text < textend && *text != '\r' && *text != '\n';text++)
2686                         if (len < (int)sizeof(line) - 1)
2687                                 line[len++] = *text;
2688                 line[len] = 0;
2689                 if (text < textend && *text == '\r' && text[1] == '\n')
2690                         text++;
2691                 if (text < textend && *text == '\n')
2692                         text++;
2693                 if (line[0] == '/' && line[1] == '/')
2694                         continue; // skip comments if anyone happens to add them
2695                 for (i = 0;i < len && line[i] > ' ';i++)
2696                         address[i] = line[i];
2697                 address[i] = 0;
2698                 // skip exactly one space character
2699                 i++;
2700                 // address contains the address with termination,
2701                 // line + i contains the name with termination
2702                 if (address[0] && line[i])
2703                         CL_IPLog_Add(address, line + i, false, false);
2704                 else
2705                         Con_Printf("%s:%i: could not parse address and name:\n%s\n", cl_iplog_name.string, linenumber, line);
2706         }
2707 }
2708
2709 static void CL_IPLog_List_f(void)
2710 {
2711         int i, j;
2712         const char *addressprefix;
2713         if (Cmd_Argc() > 2)
2714         {
2715                 Con_Printf("usage: %s 123.456.789.\n", Cmd_Argv(0));
2716                 return;
2717         }
2718         addressprefix = "";
2719         if (Cmd_Argc() >= 2)
2720                 addressprefix = Cmd_Argv(1);
2721         if (!cl_iplog_loaded)
2722                 CL_IPLog_Load();
2723         if (addressprefix && addressprefix[0])
2724                 Con_Printf("Listing iplog addresses beginning with %s\n", addressprefix);
2725         else
2726                 Con_Printf("Listing all iplog entries\n");
2727         Con_Printf("address         name\n");
2728         for (i = 0;i < cl_iplog_numitems;i++)
2729         {
2730                 if (addressprefix && addressprefix[0])
2731                 {
2732                         for (j = 0;addressprefix[j];j++)
2733                                 if (addressprefix[j] != cl_iplog_items[i].address[j])
2734                                         break;
2735                         // if this address does not begin with the addressprefix string
2736                         // simply omit it from the output
2737                         if (addressprefix[j])
2738                                 continue;
2739                 }
2740                 // if name is less than 15 characters, left justify it and pad
2741                 // if name is more than 15 characters, print all of it, not worrying
2742                 // about the fact it will misalign the columns
2743                 if (strlen(cl_iplog_items[i].address) < 15)
2744                         Con_Printf("%-15s %s\n", cl_iplog_items[i].address, cl_iplog_items[i].name);
2745                 else
2746                         Con_Printf("%5s %s\n", cl_iplog_items[i].address, cl_iplog_items[i].name);
2747         }
2748 }
2749
2750 // look for anything interesting like player IP addresses or ping reports
2751 qboolean CL_ExaminePrintString(const char *text)
2752 {
2753         int len;
2754         const char *t;
2755         char temp[MAX_INPUTLINE];
2756         if (!strcmp(text, "Client ping times:\n"))
2757         {
2758                 cl.parsingtextmode = CL_PARSETEXTMODE_PING;
2759                 // hide ping reports in demos
2760                 if (cls.demoplayback)
2761                         cl.parsingtextexpectingpingforscores = 1;
2762                 for(cl.parsingtextplayerindex = 0; cl.parsingtextplayerindex < cl.maxclients && !cl.scores[cl.parsingtextplayerindex].name[0]; cl.parsingtextplayerindex++)
2763                         ;
2764                 if (cl.parsingtextplayerindex >= cl.maxclients) // should never happen, since the client itself should be in cl.scores
2765                 {
2766                         Con_Printf("ping reply but empty scoreboard?!?\n");
2767                         cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
2768                         cl.parsingtextexpectingpingforscores = 0;
2769                 }
2770                 cl.parsingtextexpectingpingforscores = cl.parsingtextexpectingpingforscores ? 2 : 0;
2771                 return !cl.parsingtextexpectingpingforscores;
2772         }
2773         if (!strncmp(text, "host:    ", 9))
2774         {
2775                 // cl.parsingtextexpectingpingforscores = false; // really?
2776                 cl.parsingtextmode = CL_PARSETEXTMODE_STATUS;
2777                 cl.parsingtextplayerindex = 0;
2778                 return true;
2779         }
2780         if (cl.parsingtextmode == CL_PARSETEXTMODE_PING)
2781         {
2782                 // if anything goes wrong, we'll assume this is not a ping report
2783                 qboolean expected = cl.parsingtextexpectingpingforscores;
2784                 cl.parsingtextexpectingpingforscores = 0;
2785                 cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
2786                 t = text;
2787                 while (*t == ' ')
2788                         t++;
2789                 if ((*t >= '0' && *t <= '9') || *t == '-')
2790                 {
2791                         int ping = atoi(t);
2792                         while ((*t >= '0' && *t <= '9') || *t == '-')
2793                                 t++;
2794                         if (*t == ' ')
2795                         {
2796                                 int charindex = 0;
2797                                 t++;
2798                                 if(cl.parsingtextplayerindex < cl.maxclients)
2799                                 {
2800                                         for (charindex = 0;cl.scores[cl.parsingtextplayerindex].name[charindex] == t[charindex];charindex++)
2801                                                 ;
2802                                         // note: the matching algorithm stops at the end of the player name because some servers append text such as " READY" after the player name in the scoreboard but not in the ping report
2803                                         //if (cl.scores[cl.parsingtextplayerindex].name[charindex] == 0 && t[charindex] == '\n')
2804                                         if (t[charindex] == '\n')
2805                                         {
2806                                                 cl.scores[cl.parsingtextplayerindex].qw_ping = bound(0, ping, 9999);
2807                                                 for (cl.parsingtextplayerindex++;cl.parsingtextplayerindex < cl.maxclients && !cl.scores[cl.parsingtextplayerindex].name[0];cl.parsingtextplayerindex++)
2808                                                         ;
2809                                                 //if (cl.parsingtextplayerindex < cl.maxclients) // we could still get unconnecteds!
2810                                                 {
2811                                                         // we parsed a valid ping entry, so expect another to follow
2812                                                         cl.parsingtextmode = CL_PARSETEXTMODE_PING;
2813                                                         cl.parsingtextexpectingpingforscores = expected;
2814                                                 }
2815                                                 return !expected;
2816                                         }
2817                                 }
2818                                 if (!strncmp(t, "unconnected\n", 12))
2819                                 {
2820                                         // just ignore
2821                                         cl.parsingtextmode = CL_PARSETEXTMODE_PING;
2822                                         cl.parsingtextexpectingpingforscores = expected;
2823                                         return !expected;
2824                                 }
2825                                 else
2826                                         Con_DPrintf("player names '%s' and '%s' didn't match\n", cl.scores[cl.parsingtextplayerindex].name, t);
2827                         }
2828                 }
2829         }
2830         if (cl.parsingtextmode == CL_PARSETEXTMODE_STATUS)
2831         {
2832                 if (!strncmp(text, "players: ", 9))
2833                 {
2834                         cl.parsingtextmode = CL_PARSETEXTMODE_STATUS_PLAYERID;
2835                         cl.parsingtextplayerindex = 0;
2836                         return true;
2837                 }
2838                 else if (!strstr(text, ": "))
2839                 {
2840                         cl.parsingtextmode = CL_PARSETEXTMODE_NONE; // status report ended
2841                         return true;
2842                 }
2843         }
2844         if (cl.parsingtextmode == CL_PARSETEXTMODE_STATUS_PLAYERID)
2845         {
2846                 // if anything goes wrong, we'll assume this is not a status report
2847                 cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
2848                 if (text[0] == '#' && text[1] >= '0' && text[1] <= '9')
2849                 {
2850                         t = text + 1;
2851                         cl.parsingtextplayerindex = atoi(t) - 1;
2852                         while (*t >= '0' && *t <= '9')
2853                                 t++;
2854                         if (*t == ' ')
2855                         {
2856                                 cl.parsingtextmode = CL_PARSETEXTMODE_STATUS_PLAYERIP;
2857                                 return true;
2858                         }
2859                         // the player name follows here, along with frags and time
2860                 }
2861         }
2862         if (cl.parsingtextmode == CL_PARSETEXTMODE_STATUS_PLAYERIP)
2863         {
2864                 // if anything goes wrong, we'll assume this is not a status report
2865                 cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
2866                 if (text[0] == ' ')
2867                 {
2868                         t = text;
2869                         while (*t == ' ')
2870                                 t++;
2871                         for (len = 0;*t && *t != '\n';t++)
2872                                 if (len < (int)sizeof(temp) - 1)
2873                                         temp[len++] = *t;
2874                         temp[len] = 0;
2875                         // botclient is perfectly valid, but we don't care about bots
2876                         // also don't try to look up the name of an invalid player index
2877                         if (strcmp(temp, "botclient")
2878                          && cl.parsingtextplayerindex >= 0
2879                          && cl.parsingtextplayerindex < cl.maxclients
2880                          && cl.scores[cl.parsingtextplayerindex].name[0])
2881                         {
2882                                 // log the player name and IP address string
2883                                 // (this operates entirely on strings to avoid issues with the
2884                                 //  nature of a network address)
2885                                 CL_IPLog_Add(temp, cl.scores[cl.parsingtextplayerindex].name, true, true);
2886                         }
2887                         cl.parsingtextmode = CL_PARSETEXTMODE_STATUS_PLAYERID;
2888                         return true;
2889                 }
2890         }
2891         return true;
2892 }
2893
2894 extern cvar_t slowmo;
2895 static void CL_NetworkTimeReceived(double newtime)
2896 {
2897         double timehigh;
2898         cl.mtime[1] = cl.mtime[0];
2899         cl.mtime[0] = newtime;
2900         if (cls.timedemo || (cl.islocalgame && !sv_fixedframeratesingleplayer.integer) || cl.mtime[1] == cl.mtime[0] || cls.signon < SIGNONS)
2901                 cl.time = cl.mtime[1] = newtime;
2902         else if (cls.demoplayback)
2903         {
2904                 // when time falls behind during demo playback it means the cl.mtime[1] was altered
2905                 // due to a large time gap, so treat it as an instant change in time
2906                 // (this can also happen during heavy packet loss in the demo)
2907                 if (cl.time < newtime - 0.1)
2908                         cl.mtime[1] = cl.time = newtime;
2909         }
2910         else if (cls.protocol != PROTOCOL_QUAKEWORLD)
2911         {
2912                 cl.mtime[1] = max(cl.mtime[1], cl.mtime[0] - 0.1);
2913                 if (developer.integer >= 100 && vid_activewindow)
2914                 {
2915                         if (cl.time < cl.mtime[1] - (cl.mtime[0] - cl.mtime[1]))
2916                                 Con_Printf("--- cl.time < cl.mtime[1] (%f < %f ... %f)\n", cl.time, cl.mtime[1], cl.mtime[0]);
2917                         else if (cl.time > cl.mtime[0] + (cl.mtime[0] - cl.mtime[1]))
2918                                 Con_Printf("--- cl.time > cl.mtime[0] (%f > %f ... %f)\n", cl.time, cl.mtime[1], cl.mtime[0]);
2919                 }
2920                 cl.time += (cl.mtime[1] - cl.time) * bound(0, cl_nettimesyncfactor.value, 1);
2921                 timehigh = cl.mtime[1] + (cl.mtime[0] - cl.mtime[1]) * cl_nettimesyncboundtolerance.value;
2922                 if (cl_nettimesyncboundmode.integer == 1)
2923                         cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
2924                 else if (cl_nettimesyncboundmode.integer == 2)
2925                 {
2926                         if (cl.time < cl.mtime[1] || cl.time > timehigh)
2927                                 cl.time = cl.mtime[1];
2928                 }
2929                 else if (cl_nettimesyncboundmode.integer == 3)
2930                 {
2931                         if ((cl.time < cl.mtime[1] && cl.oldtime < cl.mtime[1]) || (cl.time > timehigh && cl.oldtime > timehigh))
2932                                 cl.time = cl.mtime[1];
2933                 }
2934                 else if (cl_nettimesyncboundmode.integer == 4)
2935                 {
2936                         if (fabs(cl.time - cl.mtime[1]) > 0.5)
2937                                 cl.time = cl.mtime[1]; // reset
2938                         else if (fabs(cl.time - cl.mtime[1]) > 0.1)
2939                                 cl.time += 0.5 * (cl.mtime[1] - cl.time); // fast
2940                         else if (cl.time > cl.mtime[1])
2941                                 cl.time -= 0.002 * cl.movevars_timescale; // fall into the past by 2ms
2942                         else
2943                                 cl.time += 0.001 * cl.movevars_timescale; // creep forward 1ms
2944                 }
2945                 else if (cl_nettimesyncboundmode.integer == 5)
2946                 {
2947                         if (fabs(cl.time - cl.mtime[1]) > 0.5)
2948                                 cl.time = cl.mtime[1]; // reset
2949                         else if (fabs(cl.time - cl.mtime[1]) > 0.1)
2950                                 cl.time += 0.5 * (cl.mtime[1] - cl.time); // fast
2951                         else
2952                                 cl.time = bound(cl.time - 0.002 * cl.movevars_timescale, cl.mtime[1], cl.time + 0.001 * cl.movevars_timescale);
2953                 }
2954                 else if (cl_nettimesyncboundmode.integer == 6)
2955                 {
2956                         cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
2957                         cl.time = bound(cl.time - 0.002 * cl.movevars_timescale, cl.mtime[1], cl.time + 0.001 * cl.movevars_timescale);
2958                 }
2959         }
2960         // this packet probably contains a player entity update, so we will need
2961         // to update the prediction
2962         cl.movement_needupdate = true;
2963         // this may get updated later in parsing by svc_clientdata
2964         cl.onground = false;
2965         // if true the cl.viewangles are interpolated from cl.mviewangles[]
2966         // during this frame
2967         // (makes spectating players much smoother and prevents mouse movement from turning)
2968         cl.fixangle[1] = cl.fixangle[0];
2969         cl.fixangle[0] = false;
2970         if (!cls.demoplayback)
2971                 VectorCopy(cl.mviewangles[0], cl.mviewangles[1]);
2972 }
2973
2974 #define SHOWNET(x) if(cl_shownet.integer==2)Con_Printf("%3i:%s\n", msg_readcount-1, x);
2975
2976 //[515]: csqc
2977 qboolean CL_VM_Parse_TempEntity (void);
2978 void CL_VM_Parse_StuffCmd (const char *msg);
2979 void CL_VM_Parse_CenterPrint (const char *msg);
2980 void CSQC_AddPrintText (const char *msg);
2981 void CSQC_ReadEntities (void);
2982
2983 /*
2984 =====================
2985 CL_ParseServerMessage
2986 =====================
2987 */
2988 int parsingerror = false;
2989 extern void CL_UpdateMoveVars(void);
2990 void CL_ParseServerMessage(void)
2991 {
2992         int                     cmd;
2993         int                     i;
2994         protocolversion_t protocol;
2995         unsigned char           cmdlog[32];
2996         char            *cmdlogname[32], *temp;
2997         int                     cmdindex, cmdcount = 0;
2998         qboolean        qwplayerupdatereceived;
2999
3000         // LordHavoc: moved demo message writing from before the packet parse to
3001         // after the packet parse so that CL_Stop_f can be called by cl_autodemo
3002         // code in CL_ParseServerinfo
3003         //if (cls.demorecording)
3004         //      CL_WriteDemoMessage (&net_message);
3005
3006         cl.last_received_message = realtime;
3007
3008         if (cls.netcon && cls.signon < SIGNONS)
3009                 CL_KeepaliveMessage(false);
3010
3011 //
3012 // if recording demos, copy the message out
3013 //
3014         if (cl_shownet.integer == 1)
3015                 Con_Printf("%f %i\n", realtime, net_message.cursize);
3016         else if (cl_shownet.integer == 2)
3017                 Con_Print("------------------\n");
3018
3019 //
3020 // parse the message
3021 //
3022         //MSG_BeginReading ();
3023
3024         parsingerror = true;
3025
3026         if (cls.protocol == PROTOCOL_QUAKEWORLD)
3027         {
3028                 CL_NetworkTimeReceived(realtime); // qw has no clock
3029
3030                 // kill all qw nails
3031                 cl.qw_num_nails = 0;
3032
3033                 // fade weapon view kick
3034                 cl.qw_weaponkick = min(cl.qw_weaponkick + 10 * bound(0, cl.time - cl.oldtime, 0.1), 0);
3035
3036                 cls.servermovesequence = cls.netcon->qw.incoming_sequence;
3037
3038                 qwplayerupdatereceived = false;
3039
3040                 while (1)
3041                 {
3042                         if (msg_badread)
3043                                 Host_Error ("CL_ParseServerMessage: Bad QW server message");
3044
3045                         cmd = MSG_ReadByte ();
3046
3047                         if (cmd == -1)
3048                         {
3049                                 SHOWNET("END OF MESSAGE");
3050                                 break;          // end of message
3051                         }
3052
3053                         cmdindex = cmdcount & 31;
3054                         cmdcount++;
3055                         cmdlog[cmdindex] = cmd;
3056
3057                         SHOWNET(qw_svc_strings[cmd]);
3058                         cmdlogname[cmdindex] = qw_svc_strings[cmd];
3059                         if (!cmdlogname[cmdindex])
3060                         {
3061                                 // LordHavoc: fix for bizarre problem in MSVC that I do not understand (if I assign the string pointer directly it ends up storing a NULL pointer)
3062                                 temp = "<unknown>";
3063                                 cmdlogname[cmdindex] = temp;
3064                         }
3065
3066                         // other commands
3067                         switch (cmd)
3068                         {
3069                         default:
3070                                 {
3071                                         char description[32*64], temp[64];
3072                                         int count;
3073                                         strlcpy(description, "packet dump: ", sizeof(description));
3074                                         i = cmdcount - 32;
3075                                         if (i < 0)
3076                                                 i = 0;
3077                                         count = cmdcount - i;
3078                                         i &= 31;
3079                                         while(count > 0)
3080                                         {
3081                                                 dpsnprintf(temp, sizeof(temp), "%3i:%s ", cmdlog[i], cmdlogname[i]);
3082                                                 strlcat(description, temp, sizeof(description));
3083                                                 count--;
3084                                                 i++;
3085                                                 i &= 31;
3086                                         }
3087                                         description[strlen(description)-1] = '\n'; // replace the last space with a newline
3088                                         Con_Print(description);
3089                                         Host_Error("CL_ParseServerMessage: Illegible server message");
3090                                 }
3091                                 break;
3092
3093                         case qw_svc_nop:
3094                                 //Con_Printf("qw_svc_nop\n");
3095                                 break;
3096
3097                         case qw_svc_disconnect:
3098                                 Con_Printf("Server disconnected\n");
3099                                 if (cls.demonum != -1)
3100                                         CL_NextDemo();
3101                                 else
3102                                         CL_Disconnect();
3103                                 return;
3104
3105                         case qw_svc_print:
3106                                 i = MSG_ReadByte();
3107                                 temp = MSG_ReadString();
3108                                 if (CL_ExaminePrintString(temp)) // look for anything interesting like player IP addresses or ping reports
3109                                 {
3110                                         if (i == 3) // chat
3111                                                 CSQC_AddPrintText(va("\1%s", temp));    //[515]: csqc
3112                                         else
3113                                                 CSQC_AddPrintText(temp);
3114                                 }
3115                                 break;
3116
3117                         case qw_svc_centerprint:
3118                                 CL_VM_Parse_CenterPrint(MSG_ReadString ());     //[515]: csqc
3119                                 break;
3120
3121                         case qw_svc_stufftext:
3122                                 CL_VM_Parse_StuffCmd(MSG_ReadString ());        //[515]: csqc
3123                                 break;
3124
3125                         case qw_svc_damage:
3126                                 // svc_damage protocol is identical to nq
3127                                 V_ParseDamage ();
3128                                 break;
3129
3130                         case qw_svc_serverdata:
3131                                 //Cbuf_Execute(); // make sure any stuffed commands are done
3132                                 CL_ParseServerInfo();
3133                                 break;
3134
3135                         case qw_svc_setangle:
3136                                 for (i=0 ; i<3 ; i++)
3137                                         cl.viewangles[i] = MSG_ReadAngle (cls.protocol);
3138                                 if (!cls.demoplayback)
3139                                 {
3140                                         cl.fixangle[0] = true;
3141                                         VectorCopy(cl.viewangles, cl.mviewangles[0]);
3142                                         // disable interpolation if this is new
3143                                         if (!cl.fixangle[1])
3144                                                 VectorCopy(cl.viewangles, cl.mviewangles[1]);
3145                                 }
3146                                 break;
3147
3148                         case qw_svc_lightstyle:
3149                                 i = MSG_ReadByte ();
3150                                 if (i >= cl.max_lightstyle)
3151                                 {
3152                                         Con_Printf ("svc_lightstyle >= MAX_LIGHTSTYLES");
3153                                         break;
3154                                 }
3155                                 strlcpy (cl.lightstyle[i].map,  MSG_ReadString(), sizeof (cl.lightstyle[i].map));
3156                                 cl.lightstyle[i].map[MAX_STYLESTRING - 1] = 0;
3157                                 cl.lightstyle[i].length = (int)strlen(cl.lightstyle[i].map);
3158                                 break;
3159
3160                         case qw_svc_sound:
3161                                 CL_ParseStartSoundPacket(false);
3162                                 break;
3163
3164                         case qw_svc_stopsound:
3165                                 i = (unsigned short) MSG_ReadShort();
3166                                 S_StopSound(i>>3, i&7);
3167                                 break;
3168
3169                         case qw_svc_updatefrags:
3170                                 i = MSG_ReadByte();
3171                                 if (i >= cl.maxclients)
3172                                         Host_Error("CL_ParseServerMessage: svc_updatefrags >= cl.maxclients");
3173                                 cl.scores[i].frags = (signed short) MSG_ReadShort();
3174                                 break;
3175
3176                         case qw_svc_updateping:
3177                                 i = MSG_ReadByte();
3178                                 if (i >= cl.maxclients)
3179                                         Host_Error("CL_ParseServerMessage: svc_updateping >= cl.maxclients");
3180                                 cl.scores[i].qw_ping = MSG_ReadShort();
3181                                 break;
3182
3183                         case qw_svc_updatepl:
3184                                 i = MSG_ReadByte();
3185                                 if (i >= cl.maxclients)
3186                                         Host_Error("CL_ParseServerMessage: svc_updatepl >= cl.maxclients");
3187                                 cl.scores[i].qw_packetloss = MSG_ReadByte();
3188                                 break;
3189
3190                         case qw_svc_updateentertime:
3191                                 i = MSG_ReadByte();
3192                                 if (i >= cl.maxclients)
3193                                         Host_Error("CL_ParseServerMessage: svc_updateentertime >= cl.maxclients");
3194                                 // seconds ago
3195                                 cl.scores[i].qw_entertime = cl.time - MSG_ReadFloat();
3196                                 break;
3197
3198                         case qw_svc_spawnbaseline:
3199                                 i = (unsigned short) MSG_ReadShort();
3200                                 if (i < 0 || i >= MAX_EDICTS)
3201                                         Host_Error ("CL_ParseServerMessage: svc_spawnbaseline: invalid entity number %i", i);
3202                                 if (i >= cl.max_entities)
3203                                         CL_ExpandEntities(i);
3204                                 CL_ParseBaseline(cl.entities + i, false);
3205                                 break;
3206                         case qw_svc_spawnstatic:
3207                                 CL_ParseStatic(false);
3208                                 break;
3209                         case qw_svc_temp_entity:
3210                                 if(!CL_VM_Parse_TempEntity())
3211                                         CL_ParseTempEntity ();
3212                                 break;
3213
3214                         case qw_svc_killedmonster:
3215                                 cl.stats[STAT_MONSTERS]++;
3216                                 break;
3217
3218                         case qw_svc_foundsecret:
3219                                 cl.stats[STAT_SECRETS]++;
3220                                 break;
3221
3222                         case qw_svc_updatestat:
3223                                 i = MSG_ReadByte ();
3224                                 if (i < 0 || i >= MAX_CL_STATS)
3225                                         Host_Error ("svc_updatestat: %i is invalid", i);
3226                                 cl.stats[i] = MSG_ReadByte ();
3227                                 break;
3228
3229                         case qw_svc_updatestatlong:
3230                                 i = MSG_ReadByte ();
3231                                 if (i < 0 || i >= MAX_CL_STATS)
3232                                         Host_Error ("svc_updatestatlong: %i is invalid", i);
3233                                 cl.stats[i] = MSG_ReadLong ();
3234                                 break;
3235
3236                         case qw_svc_spawnstaticsound:
3237                                 CL_ParseStaticSound (false);
3238                                 break;
3239
3240                         case qw_svc_cdtrack:
3241                                 cl.cdtrack = cl.looptrack = MSG_ReadByte ();
3242                                 if ( (cls.demoplayback || cls.demorecording) && (cls.forcetrack != -1) )
3243                                         CDAudio_Play ((unsigned char)cls.forcetrack, true);
3244                                 else
3245                                         CDAudio_Play ((unsigned char)cl.cdtrack, true);
3246                                 break;
3247
3248                         case qw_svc_intermission:
3249                                 if(!cl.intermission)
3250                                         cl.completed_time = cl.time;
3251                                 cl.intermission = 1;
3252                                 MSG_ReadVector(cl.qw_intermission_origin, cls.protocol);
3253                                 for (i = 0;i < 3;i++)
3254                                         cl.qw_intermission_angles[i] = MSG_ReadAngle(cls.protocol);
3255                                 break;
3256
3257                         case qw_svc_finale:
3258                                 if(!cl.intermission)
3259                                         cl.completed_time = cl.time;
3260                                 cl.intermission = 2;
3261                                 SCR_CenterPrint(MSG_ReadString ());
3262                                 break;
3263
3264                         case qw_svc_sellscreen:
3265                                 Cmd_ExecuteString ("help", src_command);
3266                                 break;
3267
3268                         case qw_svc_smallkick:
3269                                 cl.qw_weaponkick = -2;
3270                                 break;
3271                         case qw_svc_bigkick:
3272                                 cl.qw_weaponkick = -4;
3273                                 break;
3274
3275                         case qw_svc_muzzleflash:
3276                                 i = (unsigned short) MSG_ReadShort();
3277                                 // NOTE: in QW this only worked on clients
3278                                 if (i < 0 || i >= MAX_EDICTS)
3279                                         Host_Error("CL_ParseServerMessage: svc_spawnbaseline: invalid entity number %i", i);
3280                                 if (i >= cl.max_entities)
3281                                         CL_ExpandEntities(i);
3282                                 cl.entities[i].persistent.muzzleflash = 1.0f;
3283                                 break;
3284
3285                         case qw_svc_updateuserinfo:
3286                                 QW_CL_UpdateUserInfo();
3287                                 break;
3288
3289                         case qw_svc_setinfo:
3290                                 QW_CL_SetInfo();
3291                                 break;
3292
3293                         case qw_svc_serverinfo:
3294                                 QW_CL_ServerInfo();
3295                                 break;
3296
3297                         case qw_svc_download:
3298                                 QW_CL_ParseDownload();
3299                                 break;
3300
3301                         case qw_svc_playerinfo:
3302                                 // slightly kill qw player entities now that we know there is
3303                                 // an update of player entities this frame...
3304                                 if (!qwplayerupdatereceived)
3305                                 {
3306                                         qwplayerupdatereceived = true;
3307                                         for (i = 1;i < cl.maxclients;i++)
3308                                                 cl.entities_active[i] = false;
3309                                 }
3310                                 EntityStateQW_ReadPlayerUpdate();
3311                                 break;
3312
3313                         case qw_svc_nails:
3314                                 QW_CL_ParseNails();
3315                                 break;
3316
3317                         case qw_svc_chokecount:
3318                                 i = MSG_ReadByte();
3319                                 // FIXME: apply to netgraph
3320                                 //for (j = 0;j < i;j++)
3321                                 //      cl.frames[(cls.netcon->qw.incoming_acknowledged-1-j)&QW_UPDATE_MASK].receivedtime = -2;
3322                                 break;
3323
3324                         case qw_svc_modellist:
3325                                 QW_CL_ParseModelList();
3326                                 break;
3327
3328                         case qw_svc_soundlist:
3329                                 QW_CL_ParseSoundList();
3330                                 break;
3331
3332                         case qw_svc_packetentities:
3333                                 EntityFrameQW_CL_ReadFrame(false);
3334                                 // first update is the final signon stage
3335                                 if (cls.signon == SIGNONS - 1)
3336                                         cls.signon = SIGNONS;
3337                                 break;
3338
3339                         case qw_svc_deltapacketentities:
3340                                 EntityFrameQW_CL_ReadFrame(true);
3341                                 // first update is the final signon stage
3342                                 if (cls.signon == SIGNONS - 1)
3343                                         cls.signon = SIGNONS;
3344                                 break;
3345
3346                         case qw_svc_maxspeed:
3347                                 cl.movevars_maxspeed = MSG_ReadFloat();
3348                                 break;
3349
3350                         case qw_svc_entgravity:
3351                                 cl.movevars_entgravity = MSG_ReadFloat();
3352                                 if (!cl.movevars_entgravity)
3353                                         cl.movevars_entgravity = 1.0f;
3354                                 break;
3355
3356                         case qw_svc_setpause:
3357                                 cl.paused = MSG_ReadByte ();
3358                                 if (cl.paused)
3359                                         CDAudio_Pause ();
3360                                 else
3361                                         CDAudio_Resume ();
3362                                 S_PauseGameSounds (cl.paused);
3363                                 break;
3364                         }
3365                 }
3366
3367                 if (qwplayerupdatereceived)
3368                 {
3369                         // fully kill any player entities that were not updated this frame
3370                         for (i = 1;i <= cl.maxclients;i++)
3371                                 if (!cl.entities_active[i])
3372                                         cl.entities[i].state_current.active = false;
3373                 }
3374         }
3375         else
3376         {
3377                 while (1)
3378                 {
3379                         if (msg_badread)
3380                                 Host_Error ("CL_ParseServerMessage: Bad server message");
3381
3382                         cmd = MSG_ReadByte ();
3383
3384                         if (cmd == -1)
3385                         {
3386                                 SHOWNET("END OF MESSAGE");
3387                                 break;          // end of message
3388                         }
3389
3390                         cmdindex = cmdcount & 31;
3391                         cmdcount++;
3392                         cmdlog[cmdindex] = cmd;
3393
3394                         // if the high bit of the command byte is set, it is a fast update
3395                         if (cmd & 128)
3396                         {
3397                                 // LordHavoc: fix for bizarre problem in MSVC that I do not understand (if I assign the string pointer directly it ends up storing a NULL pointer)
3398                                 temp = "entity";
3399                                 cmdlogname[cmdindex] = temp;
3400                                 SHOWNET("fast update");
3401                                 if (cls.signon == SIGNONS - 1)
3402                                 {
3403                                         // first update is the final signon stage
3404                                         cls.signon = SIGNONS;
3405                                         CL_SignonReply ();
3406                                 }
3407                                 EntityFrameQuake_ReadEntity (cmd&127);
3408                                &nbs