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