fixed stair smoothing code so it no longer jitters when riding lifts
[divverent/darkplaces.git] / cl_main.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_main.c  -- client main loop
21
22 #include "quakedef.h"
23 #include "cl_collision.h"
24 #include "cl_video.h"
25 #include "image.h"
26 #include "csprogs.h"
27 #include "r_shadow.h"
28 #include "libcurl.h"
29
30 // we need to declare some mouse variables here, because the menu system
31 // references them even when on a unix system.
32
33 cvar_t csqc_progname = {0, "csqc_progname","csprogs.dat","name of csprogs.dat file to load"};   //[515]: csqc crc check and right csprogs name according to progs.dat
34 cvar_t csqc_progcrc = {CVAR_READONLY, "csqc_progcrc","-1","CRC of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"};
35 cvar_t csqc_progsize = {CVAR_READONLY, "csqc_progsize","-1","file size of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"};
36
37 cvar_t cl_shownet = {0, "cl_shownet","0","1 = print packet size, 2 = print packet message list"};
38 cvar_t cl_nolerp = {0, "cl_nolerp", "0","network update smoothing"};
39
40 cvar_t cl_itembobheight = {0, "cl_itembobheight", "0","how much items bob up and down (try 8)"};
41 cvar_t cl_itembobspeed = {0, "cl_itembobspeed", "0.5","how frequently items bob up and down"};
42
43 cvar_t lookspring = {CVAR_SAVE, "lookspring","0","returns pitch to level with the floor when no longer holding a pitch key"};
44 cvar_t lookstrafe = {CVAR_SAVE, "lookstrafe","0","move instead of turning"};
45 cvar_t sensitivity = {CVAR_SAVE, "sensitivity","3","mouse speed multiplier"};
46
47 cvar_t m_pitch = {CVAR_SAVE, "m_pitch","0.022","mouse pitch speed multiplier"};
48 cvar_t m_yaw = {CVAR_SAVE, "m_yaw","0.022","mouse yaw speed multiplier"};
49 cvar_t m_forward = {CVAR_SAVE, "m_forward","1","mouse forward speed multiplier"};
50 cvar_t m_side = {CVAR_SAVE, "m_side","0.8","mouse side speed multiplier"};
51
52 cvar_t freelook = {CVAR_SAVE, "freelook", "1","mouse controls pitch instead of forward/back"};
53
54 #ifdef AUTODEMO_BROKEN
55 cvar_t cl_autodemo = {0, "cl_autodemo", "0", "records every game played, using the date/time and map name to name the demo file" };
56 cvar_t cl_autodemo_nameformat = {0, "cl_autodemo_nameformat", "%Y-%m-%d_%H-%M", "The format of the cl_autodemo filename, followed by the map name" };
57 #endif
58
59 cvar_t r_draweffects = {0, "r_draweffects", "1","renders temporary sprite effects"};
60
61 cvar_t cl_explosions_alpha_start = {CVAR_SAVE, "cl_explosions_alpha_start", "1.5","starting alpha of an explosion shell"};
62 cvar_t cl_explosions_alpha_end = {CVAR_SAVE, "cl_explosions_alpha_end", "0","end alpha of an explosion shell (just before it disappears)"};
63 cvar_t cl_explosions_size_start = {CVAR_SAVE, "cl_explosions_size_start", "16","starting size of an explosion shell"};
64 cvar_t cl_explosions_size_end = {CVAR_SAVE, "cl_explosions_size_end", "128","ending alpha of an explosion shell (just before it disappears)"};
65 cvar_t cl_explosions_lifetime = {CVAR_SAVE, "cl_explosions_lifetime", "0.5","how long an explosion shell lasts"};
66
67 cvar_t cl_stainmaps = {CVAR_SAVE, "cl_stainmaps", "1","stains lightmaps, much faster than decals but blurred"};
68 cvar_t cl_stainmaps_clearonload = {CVAR_SAVE, "cl_stainmaps_clearonload", "1","clear stainmaps on map restart"};
69
70 cvar_t cl_beams_polygons = {CVAR_SAVE, "cl_beams_polygons", "1","use beam polygons instead of models"};
71 cvar_t cl_beams_quakepositionhack = {CVAR_SAVE, "cl_beams_quakepositionhack", "1", "makes your lightning gun appear to fire from your waist (as in Quake and QuakeWorld)"};
72 cvar_t cl_beams_instantaimhack = {CVAR_SAVE, "cl_beams_instantaimhack", "1", "makes your lightning gun aiming update instantly"};
73 cvar_t cl_beams_lightatend = {CVAR_SAVE, "cl_beams_lightatend", "0", "make a light at the end of the beam"};
74
75 cvar_t cl_noplayershadow = {CVAR_SAVE, "cl_noplayershadow", "0","hide player shadow"};
76
77 cvar_t qport = {0, "qport", "0", "identification key for playing on qw servers (allows you to maintain a connection to a quakeworld server even if your port changes)"};
78
79 cvar_t cl_prydoncursor = {0, "cl_prydoncursor", "0", "enables a mouse pointer which is able to click on entities in the world, useful for point and click mods, see PRYDON_CLIENTCURSOR extension in dpextensions.qc"};
80
81 cvar_t cl_deathnoviewmodel = {0, "cl_deathnoviewmodel", "1", "hides gun model when dead"};
82
83 client_static_t cls;
84 client_state_t  cl;
85
86 #define MAX_PARTICLES                   32768   // default max # of particles at one time
87 #define ABSOLUTE_MIN_PARTICLES  512             // no fewer than this no matter what's on the command line
88
89 /*
90 =====================
91 CL_ClearState
92
93 =====================
94 */
95 void CL_ClearState(void)
96 {
97         int i;
98         entity_t *ent;
99
100 // wipe the entire cl structure
101         Mem_EmptyPool(cls.levelmempool);
102         memset (&cl, 0, sizeof(cl));
103
104         S_StopAllSounds();
105
106         // reset the view zoom interpolation
107         cl.mviewzoom[0] = cl.mviewzoom[1] = 1;
108
109         cl.num_entities = 0;
110         cl.num_static_entities = 0;
111         cl.num_temp_entities = 0;
112         cl.num_brushmodel_entities = 0;
113
114         // tweak these if the game runs out
115         cl.max_entities = 256;
116         cl.max_static_entities = 256;
117         cl.max_temp_entities = 512;
118         cl.max_effects = 256;
119         cl.max_beams = 256;
120         cl.max_dlights = MAX_DLIGHTS;
121         cl.max_lightstyle = MAX_LIGHTSTYLES;
122         cl.max_brushmodel_entities = MAX_EDICTS;
123         cl.max_particles = MAX_PARTICLES;
124
125 // COMMANDLINEOPTION: Client: -particles <number> changes maximum number of particles at once, default 32768
126         i = COM_CheckParm ("-particles");
127         if (i && i < com_argc - 1)
128         {
129                 cl.max_particles = (int)(atoi(com_argv[i+1]));
130                 if (cl.max_particles < ABSOLUTE_MIN_PARTICLES)
131                         cl.max_particles = ABSOLUTE_MIN_PARTICLES;
132         }
133
134         cl.num_dlights = 0;
135         cl.num_effects = 0;
136         cl.num_beams = 0;
137
138         cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
139         cl.entities_active = (unsigned char *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(unsigned char));
140         cl.static_entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_static_entities * sizeof(entity_t));
141         cl.temp_entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_temp_entities * sizeof(entity_t));
142         cl.effects = (cl_effect_t *)Mem_Alloc(cls.levelmempool, cl.max_effects * sizeof(cl_effect_t));
143         cl.beams = (beam_t *)Mem_Alloc(cls.levelmempool, cl.max_beams * sizeof(beam_t));
144         cl.dlights = (dlight_t *)Mem_Alloc(cls.levelmempool, cl.max_dlights * sizeof(dlight_t));
145         cl.lightstyle = (lightstyle_t *)Mem_Alloc(cls.levelmempool, cl.max_lightstyle * sizeof(lightstyle_t));
146         cl.brushmodel_entities = (int *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(int));
147         cl.particles = (particle_t *) Mem_Alloc(cls.levelmempool, cl.max_particles * sizeof(particle_t));
148
149         // LordHavoc: have to set up the baseline info for alpha and other stuff
150         for (i = 0;i < cl.max_entities;i++)
151         {
152                 cl.entities[i].state_baseline = defaultstate;
153                 cl.entities[i].state_previous = defaultstate;
154                 cl.entities[i].state_current = defaultstate;
155         }
156
157         if (gamemode == GAME_NEXUIZ)
158         {
159                 VectorSet(cl.playerstandmins, -16, -16, -24);
160                 VectorSet(cl.playerstandmaxs, 16, 16, 45);
161                 VectorSet(cl.playercrouchmins, -16, -16, -24);
162                 VectorSet(cl.playercrouchmaxs, 16, 16, 25);
163         }
164         else
165         {
166                 VectorSet(cl.playerstandmins, -16, -16, -24);
167                 VectorSet(cl.playerstandmaxs, 16, 16, 24);
168                 VectorSet(cl.playercrouchmins, -16, -16, -24);
169                 VectorSet(cl.playercrouchmaxs, 16, 16, 24);
170         }
171
172         // disable until we get textures for it
173         R_ResetSkyBox();
174
175         ent = &cl.entities[0];
176         // entire entity array was cleared, so just fill in a few fields
177         ent->state_current.active = true;
178         ent->render.model = cl.worldmodel = NULL; // no world model yet
179         ent->render.alpha = 1;
180         ent->render.colormap = -1; // no special coloring
181         ent->render.flags = RENDER_SHADOW | RENDER_LIGHT;
182         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, 0, 0, 0, 0, 0, 0, 1);
183         CL_UpdateRenderEntity(&ent->render);
184
185         // noclip is turned off at start
186         noclip_anglehack = false;
187
188         // mark all frames invalid for delta
189         memset(cl.qw_deltasequence, -1, sizeof(cl.qw_deltasequence));
190
191         CL_Screen_NewMap();
192 }
193
194 void CL_SetInfo(const char *key, const char *value, qboolean send, qboolean allowstarkey, qboolean allowmodel, qboolean quiet)
195 {
196         int i;
197         qboolean fail = false;
198         if (!allowstarkey && key[0] == '*')
199                 fail = true;
200         if (!allowmodel && (!strcasecmp(key, "pmodel") || !strcasecmp(key, "emodel")))
201                 fail = true;
202         for (i = 0;key[i];i++)
203                 if (key[i] <= ' ' || key[i] == '\"')
204                         fail = true;
205         for (i = 0;value[i];i++)
206                 if (value[i] == '\r' || value[i] == '\n' || value[i] == '\"')
207                         fail = true;
208         if (fail)
209         {
210                 if (!quiet)
211                         Con_Printf("Can't setinfo \"%s\" \"%s\"\n", key, value);
212                 return;
213         }
214         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), key, value);
215         if (cls.state == ca_connected && cls.netcon)
216         {
217                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
218                 {
219                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
220                         MSG_WriteString(&cls.netcon->message, va("setinfo \"%s\" \"%s\"", key, value));
221                 }
222                 else if (!strcasecmp(key, "name"))
223                 {
224                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
225                         MSG_WriteString(&cls.netcon->message, va("name \"%s\"", value));
226                 }
227                 else if (!strcasecmp(key, "playermodel"))
228                 {
229                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
230                         MSG_WriteString(&cls.netcon->message, va("playermodel \"%s\"", value));
231                 }
232                 else if (!strcasecmp(key, "playerskin"))
233                 {
234                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
235                         MSG_WriteString(&cls.netcon->message, va("playerskin \"%s\"", value));
236                 }
237                 else if (!strcasecmp(key, "topcolor"))
238                 {
239                         // don't send anything, the combined color code will be updated manually
240                 }
241                 else if (!strcasecmp(key, "bottomcolor"))
242                 {
243                         // don't send anything, the combined color code will be updated manually
244                 }
245                 else if (!strcasecmp(key, "rate"))
246                 {
247                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
248                         MSG_WriteString(&cls.netcon->message, va("rate \"%s\"", value));
249                 }
250         }
251 }
252
253 void CL_ExpandEntities(int num)
254 {
255         int i, oldmaxentities;
256         entity_t *oldentities;
257         if (num >= cl.max_entities)
258         {
259                 if (!cl.entities)
260                         Sys_Error("CL_ExpandEntities: cl.entities not initialized");
261                 if (num >= MAX_EDICTS)
262                         Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS);
263                 oldmaxentities = cl.max_entities;
264                 oldentities = cl.entities;
265                 cl.max_entities = (num & ~255) + 256;
266                 cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
267                 memcpy(cl.entities, oldentities, oldmaxentities * sizeof(entity_t));
268                 Mem_Free(oldentities);
269                 for (i = oldmaxentities;i < cl.max_entities;i++)
270                 {
271                         cl.entities[i].state_baseline = defaultstate;
272                         cl.entities[i].state_previous = defaultstate;
273                         cl.entities[i].state_current = defaultstate;
274                 }
275         }
276 }
277
278 void CL_VM_ShutDown (void);
279 /*
280 =====================
281 CL_Disconnect
282
283 Sends a disconnect message to the server
284 This is also called on Host_Error, so it shouldn't cause any errors
285 =====================
286 */
287 void CL_Disconnect(void)
288 {
289         if (cls.state == ca_dedicated)
290                 return;
291
292         Con_DPrintf("CL_Disconnect\n");
293
294         CL_VM_ShutDown();
295 // stop sounds (especially looping!)
296         S_StopAllSounds ();
297
298         cl.parsingtextexpectingpingforscores = 0; // just in case no reply has come yet
299
300         // clear contents blends
301         cl.cshifts[0].percent = 0;
302         cl.cshifts[1].percent = 0;
303         cl.cshifts[2].percent = 0;
304         cl.cshifts[3].percent = 0;
305
306         cl.worldmodel = NULL;
307
308         CL_Parse_ErrorCleanUp();
309
310         if (cls.demoplayback)
311                 CL_StopPlayback();
312         else if (cls.netcon)
313         {
314                 sizebuf_t buf;
315                 unsigned char bufdata[8];
316                 if (cls.demorecording)
317                         CL_Stop_f();
318
319                 // send disconnect message 3 times to improve chances of server
320                 // receiving it (but it still fails sometimes)
321                 memset(&buf, 0, sizeof(buf));
322                 buf.data = bufdata;
323                 buf.maxsize = sizeof(bufdata);
324                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
325                 {
326                         Con_DPrint("Sending drop command\n");
327                         MSG_WriteByte(&buf, qw_clc_stringcmd);
328                         MSG_WriteString(&buf, "drop");
329                 }
330                 else
331                 {
332                         Con_DPrint("Sending clc_disconnect\n");
333                         MSG_WriteByte(&buf, clc_disconnect);
334                 }
335                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol);
336                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol);
337                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol);
338                 NetConn_Close(cls.netcon);
339                 cls.netcon = NULL;
340         }
341         cls.state = ca_disconnected;
342
343         cls.demoplayback = cls.timedemo = false;
344         cls.signon = 0;
345 }
346
347 void CL_Disconnect_f(void)
348 {
349         CL_Disconnect ();
350         if (sv.active)
351                 Host_ShutdownServer ();
352 }
353
354
355
356
357 /*
358 =====================
359 CL_EstablishConnection
360
361 Host should be either "local" or a net address
362 =====================
363 */
364 void CL_EstablishConnection(const char *host)
365 {
366         if (cls.state == ca_dedicated)
367                 return;
368
369         // clear menu's connect error message
370         M_Update_Return_Reason("");
371         cls.demonum = -1;
372
373         // stop demo loop in case this fails
374         CL_Disconnect();
375
376         // if downloads are running, cancel their finishing action
377         Curl_Clear_forthismap();
378
379         // make sure the client ports are open before attempting to connect
380         NetConn_UpdateSockets();
381
382         // run a network frame
383         //NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
384
385         if (LHNETADDRESS_FromString(&cls.connect_address, host, 26000) && (cls.connect_mysocket = NetConn_ChooseClientSocketForAddress(&cls.connect_address)))
386         {
387                 cls.connect_trying = true;
388                 cls.connect_remainingtries = 3;
389                 cls.connect_nextsendtime = 0;
390                 M_Update_Return_Reason("Trying to connect...");
391                 // run several network frames to jump into the game quickly
392                 //if (sv.active)
393                 //{
394                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
395                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
396                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
397                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
398                 //}
399         }
400         else
401         {
402                 Con_Print("Unable to find a suitable network socket to connect to server.\n");
403                 M_Update_Return_Reason("No network");
404         }
405 }
406
407 /*
408 ==============
409 CL_PrintEntities_f
410 ==============
411 */
412 static void CL_PrintEntities_f(void)
413 {
414         entity_t *ent;
415         int i;
416
417         for (i = 0, ent = cl.entities;i < cl.num_entities;i++, ent++)
418         {
419                 const char* modelname;
420
421                 if (!ent->state_current.active)
422                         continue;
423
424                 if (ent->render.model)
425                         modelname = ent->render.model->name;
426                 else
427                         modelname = "--no model--";
428                 Con_Printf("%3i: %-25s:%4i (%5i %5i %5i) [%3i %3i %3i] %4.2f %5.3f\n", i, modelname, ent->render.frame, (int) ent->state_current.origin[0], (int) ent->state_current.origin[1], (int) ent->state_current.origin[2], (int) ent->state_current.angles[0] % 360, (int) ent->state_current.angles[1] % 360, (int) ent->state_current.angles[2] % 360, ent->render.scale, ent->render.alpha);
429         }
430 }
431
432 //static const vec3_t nomodelmins = {-16, -16, -16};
433 //static const vec3_t nomodelmaxs = {16, 16, 16};
434 void CL_UpdateRenderEntity(entity_render_t *ent)
435 {
436         vec3_t org;
437         vec_t scale;
438         model_t *model = ent->model;
439         // update the inverse matrix for the renderer
440         Matrix4x4_Invert_Simple(&ent->inversematrix, &ent->matrix);
441         // update the animation blend state
442         R_LerpAnimation(ent);
443         // we need the matrix origin to center the box
444         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
445         // update entity->render.scale because the renderer needs it
446         ent->scale = scale = Matrix4x4_ScaleFromMatrix(&ent->matrix);
447         if (model)
448         {
449                 // NOTE: this directly extracts vector components from the matrix, which relies on the matrix orientation!
450 #ifdef MATRIX4x4_OPENGLORIENTATION
451                 if (ent->matrix.m[0][2] != 0 || ent->matrix.m[1][2] != 0)
452 #else
453                 if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0)
454 #endif
455                 {
456                         // pitch or roll
457                         VectorMA(org, scale, model->rotatedmins, ent->mins);
458                         VectorMA(org, scale, model->rotatedmaxs, ent->maxs);
459                 }
460 #ifdef MATRIX4x4_OPENGLORIENTATION
461                 else if (ent->matrix.m[1][0] != 0 || ent->matrix.m[0][1] != 0)
462 #else
463                 else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0)
464 #endif
465                 {
466                         // yaw
467                         VectorMA(org, scale, model->yawmins, ent->mins);
468                         VectorMA(org, scale, model->yawmaxs, ent->maxs);
469                 }
470                 else
471                 {
472                         VectorMA(org, scale, model->normalmins, ent->mins);
473                         VectorMA(org, scale, model->normalmaxs, ent->maxs);
474                 }
475         }
476         else
477         {
478                 ent->mins[0] = org[0] - 16;
479                 ent->mins[1] = org[1] - 16;
480                 ent->mins[2] = org[2] - 16;
481                 ent->maxs[0] = org[0] + 16;
482                 ent->maxs[1] = org[1] + 16;
483                 ent->maxs[2] = org[2] + 16;
484         }
485 }
486
487 /*
488 ===============
489 CL_LerpPoint
490
491 Determines the fraction between the last two messages that the objects
492 should be put at.
493 ===============
494 */
495 static float CL_LerpPoint(void)
496 {
497         float f;
498
499         if (cl_nettimesyncmode.integer == 3)
500                 cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
501
502         // LordHavoc: lerp in listen games as the server is being capped below the client (usually)
503         if (cl.mtime[0] <= cl.mtime[1])
504         {
505                 cl.time = cl.mtime[0];
506                 return 1;
507         }
508
509         f = (cl.time - cl.mtime[1]) / (cl.mtime[0] - cl.mtime[1]);
510         return bound(0, f, 1);
511 }
512
513 void CL_ClearTempEntities (void)
514 {
515         cl.num_temp_entities = 0;
516 }
517
518 entity_t *CL_NewTempEntity(void)
519 {
520         entity_t *ent;
521
522         if (r_refdef.numentities >= r_refdef.maxentities)
523                 return NULL;
524         if (cl.num_temp_entities >= cl.max_temp_entities)
525                 return NULL;
526         ent = &cl.temp_entities[cl.num_temp_entities++];
527         memset (ent, 0, sizeof(*ent));
528         r_refdef.entities[r_refdef.numentities++] = &ent->render;
529
530         ent->render.colormap = -1; // no special coloring
531         ent->render.alpha = 1;
532         VectorSet(ent->render.colormod, 1, 1, 1);
533         return ent;
534 }
535
536 void CL_Effect(vec3_t org, int modelindex, int startframe, int framecount, float framerate)
537 {
538         int i;
539         cl_effect_t *e;
540         if (!modelindex) // sanity check
541                 return;
542         if (framerate < 1)
543         {
544                 Con_Printf("CL_Effect: framerate %f is < 1\n", framerate);
545                 return;
546         }
547         if (framecount < 1)
548         {
549                 Con_Printf("CL_Effect: framecount %i is < 1\n", framecount);
550                 return;
551         }
552         for (i = 0, e = cl.effects;i < cl.max_effects;i++, e++)
553         {
554                 if (e->active)
555                         continue;
556                 e->active = true;
557                 VectorCopy(org, e->origin);
558                 e->modelindex = modelindex;
559                 e->starttime = cl.time;
560                 e->startframe = startframe;
561                 e->endframe = startframe + framecount;
562                 e->framerate = framerate;
563
564                 e->frame = 0;
565                 e->frame1time = cl.time;
566                 e->frame2time = cl.time;
567                 cl.num_effects = max(cl.num_effects, i + 1);
568                 break;
569         }
570 }
571
572 void CL_AllocLightFlash(entity_render_t *ent, matrix4x4_t *matrix, float radius, float red, float green, float blue, float decay, float lifetime, int cubemapnum, int style, int shadowenable, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
573 {
574         int i;
575         dlight_t *dl;
576
577         /*
578 // first look for an exact key match
579         if (ent)
580         {
581                 dl = cl.dlights;
582                 for (i = 0;i < cl.num_dlights;i++, dl++)
583                         if (dl->ent == ent)
584                                 goto dlightsetup;
585         }
586         */
587
588 // then look for anything else
589         dl = cl.dlights;
590         for (i = 0;i < cl.num_dlights;i++, dl++)
591                 if (!dl->radius)
592                         goto dlightsetup;
593         // if we hit the end of the active dlights and found no gaps, add a new one
594         if (i < MAX_DLIGHTS)
595         {
596                 cl.num_dlights = i + 1;
597                 goto dlightsetup;
598         }
599
600         // unable to find one
601         return;
602
603 dlightsetup:
604         //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius);
605         memset (dl, 0, sizeof(*dl));
606         Matrix4x4_Normalize(&dl->matrix, matrix);
607         dl->ent = ent;
608         Matrix4x4_OriginFromMatrix(&dl->matrix, dl->origin);
609         CL_FindNonSolidLocation(dl->origin, dl->origin, 6);
610         Matrix4x4_SetOrigin(&dl->matrix, dl->origin[0], dl->origin[1], dl->origin[2]);
611         Matrix4x4_Scale(&dl->matrix, radius, 1);
612         dl->radius = radius;
613         dl->color[0] = red;
614         dl->color[1] = green;
615         dl->color[2] = blue;
616         dl->initialradius = radius;
617         dl->initialcolor[0] = red;
618         dl->initialcolor[1] = green;
619         dl->initialcolor[2] = blue;
620         dl->decay = decay / radius; // changed decay to be a percentage decrease
621         dl->intensity = 1; // this is what gets decayed
622         if (lifetime)
623                 dl->die = cl.time + lifetime;
624         else
625                 dl->die = 0;
626         if (cubemapnum > 0)
627                 dpsnprintf(dl->cubemapname, sizeof(dl->cubemapname), "cubemaps/%i", cubemapnum);
628         else
629                 dl->cubemapname[0] = 0;
630         dl->style = style;
631         dl->shadow = shadowenable;
632         dl->corona = corona;
633         dl->flags = flags;
634         dl->coronasizescale = coronasizescale;
635         dl->ambientscale = ambientscale;
636         dl->diffusescale = diffusescale;
637         dl->specularscale = specularscale;
638 }
639
640 void CL_DecayLightFlashes(void)
641 {
642         int i, oldmax;
643         dlight_t *dl;
644         float time;
645
646         time = bound(0, cl.time - cl.oldtime, 0.1);
647         oldmax = cl.num_dlights;
648         cl.num_dlights = 0;
649         for (i = 0, dl = cl.dlights;i < oldmax;i++, dl++)
650         {
651                 if (dl->radius)
652                 {
653                         dl->intensity -= time * dl->decay;
654                         if (cl.time < dl->die && dl->intensity > 0)
655                         {
656                                 //dl->radius = dl->initialradius * dl->intensity;
657                                 VectorScale(dl->initialcolor, dl->intensity, dl->color);
658                                 cl.num_dlights = i + 1;
659                         }
660                         else
661                                 dl->radius = 0;
662                 }
663         }
664 }
665
666 // called before entity relinking
667 void CL_RelinkLightFlashes(void)
668 {
669         int i, j, k, l;
670         dlight_t *dl;
671         float frac, f;
672
673         if (r_dynamic.integer)
674                 for (i = 0, dl = cl.dlights;i < cl.num_dlights && r_refdef.numlights < MAX_DLIGHTS;i++, dl++)
675                         if (dl->radius)
676                                 R_RTLight_Update(&r_refdef.lights[r_refdef.numlights++], false, &dl->matrix, dl->color, dl->style, dl->cubemapname, dl->shadow, dl->corona, dl->coronasizescale, dl->ambientscale, dl->diffusescale, dl->specularscale, dl->flags);
677
678 // light animations
679 // 'm' is normal light, 'a' is no light, 'z' is double bright
680         f = cl.time * 10;
681         i = (int)floor(f);
682         frac = f - i;
683         for (j = 0;j < cl.max_lightstyle;j++)
684         {
685                 if (!cl.lightstyle || !cl.lightstyle[j].length)
686                 {
687                         r_refdef.lightstylevalue[j] = 256;
688                         continue;
689                 }
690                 k = i % cl.lightstyle[j].length;
691                 l = (i-1) % cl.lightstyle[j].length;
692                 k = cl.lightstyle[j].map[k] - 'a';
693                 l = cl.lightstyle[j].map[l] - 'a';
694                 r_refdef.lightstylevalue[j] = (unsigned short)(((k*frac)+(l*(1-frac)))*22);
695         }
696 }
697
698 void CL_AddQWCTFFlagModel(entity_t *player, int skin)
699 {
700         float f;
701         entity_t *flag;
702         matrix4x4_t flagmatrix;
703
704         // this code taken from QuakeWorld
705         f = 14;
706         if (player->render.frame2 >= 29 && player->render.frame2 <= 40)
707         {
708                 if (player->render.frame2 >= 29 && player->render.frame2 <= 34)
709                 { //axpain
710                         if      (player->render.frame2 == 29) f = f + 2;
711                         else if (player->render.frame2 == 30) f = f + 8;
712                         else if (player->render.frame2 == 31) f = f + 12;
713                         else if (player->render.frame2 == 32) f = f + 11;
714                         else if (player->render.frame2 == 33) f = f + 10;
715                         else if (player->render.frame2 == 34) f = f + 4;
716                 }
717                 else if (player->render.frame2 >= 35 && player->render.frame2 <= 40)
718                 { // pain
719                         if      (player->render.frame2 == 35) f = f + 2;
720                         else if (player->render.frame2 == 36) f = f + 10;
721                         else if (player->render.frame2 == 37) f = f + 10;
722                         else if (player->render.frame2 == 38) f = f + 8;
723                         else if (player->render.frame2 == 39) f = f + 4;
724                         else if (player->render.frame2 == 40) f = f + 2;
725                 }
726         }
727         else if (player->render.frame2 >= 103 && player->render.frame2 <= 118)
728         {
729                 if      (player->render.frame2 >= 103 && player->render.frame2 <= 104) f = f + 6;  //nailattack
730                 else if (player->render.frame2 >= 105 && player->render.frame2 <= 106) f = f + 6;  //light
731                 else if (player->render.frame2 >= 107 && player->render.frame2 <= 112) f = f + 7;  //rocketattack
732                 else if (player->render.frame2 >= 112 && player->render.frame2 <= 118) f = f + 7;  //shotattack
733         }
734         // end of code taken from QuakeWorld
735
736         flag = CL_NewTempEntity();
737         if (!flag)
738                 return;
739
740         flag->render.model = cl.model_precache[cl.qw_modelindex_flag];
741         flag->render.skinnum = skin;
742         flag->render.colormap = -1; // no special coloring
743         flag->render.alpha = 1;
744         VectorSet(flag->render.colormod, 1, 1, 1);
745         // attach the flag to the player matrix
746         Matrix4x4_CreateFromQuakeEntity(&flagmatrix, -f, -22, 0, 0, 0, -45, 1);
747         Matrix4x4_Concat(&flag->render.matrix, &player->render.matrix, &flagmatrix);
748         CL_UpdateRenderEntity(&flag->render);
749 }
750
751 matrix4x4_t viewmodelmatrix;
752
753 static const vec3_t muzzleflashorigin = {18, 0, 0};
754
755 extern void V_DriftPitch(void);
756 extern void V_FadeViewFlashs(void);
757 extern void V_CalcViewBlend(void);
758 extern void V_CalcRefdef(void);
759
760 // note this is a recursive function, recursionlimit should be 32 or so on the initial call
761 void CL_UpdateNetworkEntity(entity_t *e, int recursionlimit)
762 {
763         const matrix4x4_t *matrix;
764         matrix4x4_t blendmatrix, tempmatrix, matrix2;
765         int j, k, l;
766         float origin[3], angles[3], delta[3], lerp, d;
767         entity_t *t;
768         model_t *model;
769         //entity_persistent_t *p = &e->persistent;
770         //entity_render_t *r = &e->render;
771         // skip inactive entities and world
772         if (!e->state_current.active || e == cl.entities)
773                 return;
774         if (recursionlimit < 1)
775                 return;
776         e->render.alpha = e->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate?
777         e->render.scale = e->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate?
778         e->render.flags = e->state_current.flags;
779         e->render.effects = e->state_current.effects;
780         VectorScale(e->state_current.colormod, (1.0f / 32.0f), e->render.colormod);
781         if (e->state_current.flags & RENDER_COLORMAPPED)
782         {
783                 int cb;
784                 unsigned char *cbcolor;
785                 e->render.colormap = e->state_current.colormap;
786                 cb = (e->render.colormap & 0xF) << 4;cb += (cb >= 128 && cb < 224) ? 4 : 12;
787                 cbcolor = (unsigned char *) (&palette_complete[cb]);
788                 e->render.colormap_pantscolor[0] = cbcolor[0] * (1.0f / 255.0f);
789                 e->render.colormap_pantscolor[1] = cbcolor[1] * (1.0f / 255.0f);
790                 e->render.colormap_pantscolor[2] = cbcolor[2] * (1.0f / 255.0f);
791                 cb = (e->render.colormap & 0xF0);cb += (cb >= 128 && cb < 224) ? 4 : 12;
792                 cbcolor = (unsigned char *) (&palette_complete[cb]);
793                 e->render.colormap_shirtcolor[0] = cbcolor[0] * (1.0f / 255.0f);
794                 e->render.colormap_shirtcolor[1] = cbcolor[1] * (1.0f / 255.0f);
795                 e->render.colormap_shirtcolor[2] = cbcolor[2] * (1.0f / 255.0f);
796         }
797         else if (e->state_current.colormap && cl.scores != NULL)
798         {
799                 int cb;
800                 unsigned char *cbcolor;
801                 e->render.colormap = cl.scores[e->state_current.colormap - 1].colors; // color it
802                 cb = (e->render.colormap & 0xF) << 4;cb += (cb >= 128 && cb < 224) ? 4 : 12;
803                 cbcolor = (unsigned char *) (&palette_complete[cb]);
804                 e->render.colormap_pantscolor[0] = cbcolor[0] * (1.0f / 255.0f);
805                 e->render.colormap_pantscolor[1] = cbcolor[1] * (1.0f / 255.0f);
806                 e->render.colormap_pantscolor[2] = cbcolor[2] * (1.0f / 255.0f);
807                 cb = (e->render.colormap & 0xF0);cb += (cb >= 128 && cb < 224) ? 4 : 12;
808                 cbcolor = (unsigned char *) (&palette_complete[cb]);
809                 e->render.colormap_shirtcolor[0] = cbcolor[0] * (1.0f / 255.0f);
810                 e->render.colormap_shirtcolor[1] = cbcolor[1] * (1.0f / 255.0f);
811                 e->render.colormap_shirtcolor[2] = cbcolor[2] * (1.0f / 255.0f);
812         }
813         else
814         {
815                 e->render.colormap = -1; // no special coloring
816                 VectorClear(e->render.colormap_pantscolor);
817                 VectorClear(e->render.colormap_shirtcolor);
818         }
819         e->render.skinnum = e->state_current.skin;
820         if (e->state_current.tagentity)
821         {
822                 // attached entity (gun held in player model's hand, etc)
823                 // if the tag entity is currently impossible, skip it
824                 if (e->state_current.tagentity >= cl.num_entities)
825                         return;
826                 t = cl.entities + e->state_current.tagentity;
827                 // if the tag entity is inactive, skip it
828                 if (!t->state_current.active)
829                         return;
830                 // update the parent first
831                 CL_UpdateNetworkEntity(t, recursionlimit - 1);
832                 // make relative to the entity
833                 matrix = &t->render.matrix;
834                 // some properties of the tag entity carry over
835                 e->render.flags |= t->render.flags & (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL);
836                 // if a valid tagindex is used, make it relative to that tag instead
837                 // FIXME: use a model function to get tag info (need to handle skeletal)
838                 if (e->state_current.tagentity && e->state_current.tagindex >= 1 && (model = t->render.model))
839                 {
840                         // blend the matrices
841                         memset(&blendmatrix, 0, sizeof(blendmatrix));
842                         for (j = 0;j < 4 && t->render.frameblend[j].lerp > 0;j++)
843                         {
844                                 matrix4x4_t tagmatrix;
845                                 Mod_Alias_GetTagMatrix(model, t->render.frameblend[j].frame, e->state_current.tagindex - 1, &tagmatrix);
846                                 d = t->render.frameblend[j].lerp;
847                                 for (l = 0;l < 4;l++)
848                                         for (k = 0;k < 4;k++)
849                                                 blendmatrix.m[l][k] += d * tagmatrix.m[l][k];
850                         }
851                         // concat the tag matrices onto the entity matrix
852                         Matrix4x4_Concat(&tempmatrix, &t->render.matrix, &blendmatrix);
853                         // use the constructed tag matrix
854                         matrix = &tempmatrix;
855                 }
856         }
857         else if (e->render.flags & RENDER_VIEWMODEL)
858         {
859                 // view-relative entity (guns and such)
860                 matrix = &viewmodelmatrix;
861         }
862         else
863         {
864                 // world-relative entity (the normal kind)
865                 matrix = &identitymatrix;
866         }
867
868         // movement lerp
869         // if it's the predicted player entity, update according to client movement
870         if (e == cl.entities + cl.playerentity && cl.movement_predicted)
871         {
872                 lerp = (cl.time - cl.movement_time[2]) / (cl.movement_time[0] - cl.movement_time[1]);
873                 lerp = bound(0, lerp, 1);
874                 if (cl_nolerp.integer)
875                         lerp = 1;
876                 VectorLerp(cl.movement_oldorigin, lerp, cl.movement_origin, origin);
877                 VectorSet(angles, 0, cl.viewangles[1], 0);
878         }
879         else if (e->persistent.lerpdeltatime > 0 && (lerp = (cl.time - e->persistent.lerpstarttime) / e->persistent.lerpdeltatime) < 1)
880         {
881                 // interpolate the origin and angles
882                 lerp = max(0, lerp);
883                 VectorLerp(e->persistent.oldorigin, lerp, e->persistent.neworigin, origin);
884                 VectorSubtract(e->persistent.newangles, e->persistent.oldangles, delta);
885                 if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360;
886                 if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360;
887                 if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360;
888                 VectorMA(e->persistent.oldangles, lerp, delta, angles);
889         }
890         else
891         {
892                 // no interpolation
893                 VectorCopy(e->persistent.neworigin, origin);
894                 VectorCopy(e->persistent.newangles, angles);
895         }
896
897         // model setup and some modelflags
898         if(e->state_current.modelindex < MAX_MODELS)
899                 e->render.model = cl.model_precache[e->state_current.modelindex];
900         if (e->render.model)
901         {
902                 // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
903                 if (e->render.model->type == mod_alias)
904                         angles[0] = -angles[0];
905                 if ((e->render.model->flags & EF_ROTATE) && (!e->state_current.tagentity && !(e->render.flags & RENDER_VIEWMODEL)))
906                 {
907                         angles[1] = ANGLEMOD(100*cl.time);
908                         if (cl_itembobheight.value)
909                                 origin[2] += (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value;
910                 }
911                 // transfer certain model flags to effects
912                 e->render.effects |= e->render.model->flags2 & (EF_FULLBRIGHT | EF_ADDITIVE);
913                 if ((e->render.effects & EF_SELECTABLE) && cl.cmd.cursor_entitynumber == e->state_current.number)
914                         VectorScale(e->render.colormod, 2, e->render.colormod);
915         }
916         // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
917         else if (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC)
918                 angles[0] = -angles[0];
919
920         // animation lerp
921         if (e->render.frame2 == e->state_current.frame)
922         {
923                 // update frame lerp fraction
924                 e->render.framelerp = 1;
925                 if (e->render.frame2time > e->render.frame1time)
926                 {
927                         // make sure frame lerp won't last longer than 100ms
928                         // (this mainly helps with models that use framegroups and
929                         // switch between them infrequently)
930                         e->render.framelerp = (cl.time - e->render.frame2time) / min(e->render.frame2time - e->render.frame1time, 0.1);
931                         e->render.framelerp = bound(0, e->render.framelerp, 1);
932                 }
933         }
934         else
935         {
936                 // begin a new frame lerp
937                 e->render.frame1 = e->render.frame2;
938                 e->render.frame1time = e->render.frame2time;
939                 e->render.frame = e->render.frame2 = e->state_current.frame;
940                 e->render.frame2time = cl.time;
941                 e->render.framelerp = 0;
942         }
943
944         // set up the render matrix
945         if (matrix)
946         {
947                 // attached entity, this requires a matrix multiply (concat)
948                 // FIXME: e->render.scale should go away
949                 Matrix4x4_CreateFromQuakeEntity(&matrix2, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
950                 // concat the matrices to make the entity relative to its tag
951                 Matrix4x4_Concat(&e->render.matrix, matrix, &matrix2);
952                 // get the origin from the new matrix
953                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
954         }
955         else
956         {
957                 // unattached entities are faster to process
958                 Matrix4x4_CreateFromQuakeEntity(&e->render.matrix, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
959         }
960
961         // make the other useful stuff
962         CL_UpdateRenderEntity(&e->render);
963
964         // tenebrae's sprites are all additive mode (weird)
965         if (gamemode == GAME_TENEBRAE && e->render.model && e->render.model->type == mod_sprite)
966                 e->render.effects |= EF_ADDITIVE;
967         // player model is only shown with chase_active on
968         if (e->state_current.number == cl.viewentity)
969                 e->render.flags |= RENDER_EXTERIORMODEL;
970         // transparent stuff can't be lit during the opaque stage
971         if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
972                 e->render.flags |= RENDER_TRANSPARENT;
973         // double sided rendering mode causes backfaces to be visible
974         // (mostly useful on transparent stuff)
975         if (e->render.effects & EF_DOUBLESIDED)
976                 e->render.flags |= RENDER_NOCULLFACE;
977         // either fullbright or lit
978         if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
979                 e->render.flags |= RENDER_LIGHT;
980         // hide player shadow during intermission or nehahra movie
981         if (!(e->render.effects & EF_NOSHADOW)
982          && !(e->render.flags & (RENDER_VIEWMODEL | RENDER_TRANSPARENT))
983          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
984                 e->render.flags |= RENDER_SHADOW;
985 }
986
987 // creates light and trails from an entity
988 void CL_UpdateNetworkEntityTrail(entity_t *e)
989 {
990         effectnameindex_t trailtype;
991         vec3_t origin;
992
993         // bmodels are treated specially since their origin is usually '0 0 0' and
994         // their actual geometry is far from '0 0 0'
995         if (e->render.model && e->render.model->soundfromcenter)
996         {
997                 vec3_t o;
998                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
999                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1000         }
1001         else
1002                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1003
1004         // handle particle trails and such effects now that we know where this
1005         // entity is in the world...
1006         trailtype = EFFECT_NONE;
1007         // LordHavoc: if the entity has no effects, don't check each
1008         if (e->render.effects & (EF_BRIGHTFIELD | EF_FLAME | EF_STARDUST | EF_FLAG1QW | EF_FLAG2QW))
1009         {
1010                 if (e->render.effects & EF_BRIGHTFIELD)
1011                 {
1012                         if (gamemode == GAME_NEXUIZ)
1013                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1014                         else
1015                                 CL_EntityParticles(e);
1016                 }
1017                 if (e->render.effects & EF_FLAME)
1018                         CL_ParticleTrail(EFFECT_EF_FLAME, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true);
1019                 if (e->render.effects & EF_STARDUST)
1020                         CL_ParticleTrail(EFFECT_EF_STARDUST, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true);
1021                 if (e->render.effects & (EF_FLAG1QW | EF_FLAG2QW))
1022                 {
1023                         // these are only set on player entities
1024                         CL_AddQWCTFFlagModel(e, (e->render.effects & EF_FLAG2QW) != 0);
1025                 }
1026         }
1027         // muzzleflash fades over time
1028         if (e->persistent.muzzleflash > 0)
1029                 e->persistent.muzzleflash -= bound(0, cl.time - cl.oldtime, 0.1) * 20;
1030         // LordHavoc: if the model has no flags, don't check each
1031         if (e->render.model && e->render.model->flags && (!e->state_current.tagentity && !(e->render.flags & RENDER_VIEWMODEL)))
1032         {
1033                 if (e->render.model->flags & EF_GIB)
1034                         trailtype = EFFECT_TR_BLOOD;
1035                 else if (e->render.model->flags & EF_ZOMGIB)
1036                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1037                 else if (e->render.model->flags & EF_TRACER)
1038                         trailtype = EFFECT_TR_WIZSPIKE;
1039                 else if (e->render.model->flags & EF_TRACER2)
1040                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1041                 else if (e->render.model->flags & EF_ROCKET)
1042                         trailtype = EFFECT_TR_ROCKET;
1043                 else if (e->render.model->flags & EF_GRENADE)
1044                 {
1045                         // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1046                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1047                 }
1048                 else if (e->render.model->flags & EF_TRACER3)
1049                         trailtype = EFFECT_TR_VORESPIKE;
1050         }
1051         // do trails
1052         if (e->render.flags & RENDER_GLOWTRAIL)
1053                 trailtype = EFFECT_TR_GLOWTRAIL;
1054         if (trailtype)
1055         {
1056                 float len;
1057                 vec3_t vel;
1058                 VectorSubtract(e->state_current.origin, e->state_previous.origin, vel);
1059                 len = e->state_current.time - e->state_previous.time;
1060                 if (len > 0)
1061                         len = 1.0f / len;
1062                 VectorScale(vel, len, vel);
1063                 CL_ParticleTrail(trailtype, 1, e->persistent.trail_origin, origin, vel, vel, e, e->state_current.glowcolor, false, true);
1064         }
1065         VectorCopy(origin, e->persistent.trail_origin);
1066 }
1067
1068
1069 /*
1070 ===============
1071 CL_UpdateEntities
1072 ===============
1073 */
1074 void CL_UpdateEntities(void)
1075 {
1076         entity_t *ent;
1077         int i;
1078
1079         // process network entities
1080         // first link the player
1081         CL_UpdateNetworkEntity(cl.entities + cl.viewentity, 32);
1082
1083         // set up the view
1084         V_CalcRefdef();
1085
1086         // start on the entity after the world
1087         // skip the player entity because it was already processed
1088         for (i = 1;i < cl.num_entities;i++)
1089         {
1090                 if (cl.entities_active[i])
1091                 {
1092                         ent = cl.entities + i;
1093                         if (ent->state_current.active)
1094                         {
1095                                 CL_UpdateNetworkEntity(ent, 32);
1096                                 // view models should never create light/trails
1097                                 if (!(ent->render.flags & RENDER_VIEWMODEL))
1098                                         CL_UpdateNetworkEntityTrail(ent);
1099                                 if (ent->render.model && ent->render.model->name[0] == '*' && ent->render.model->TraceBox)
1100                                         cl.brushmodel_entities[cl.num_brushmodel_entities++] = ent->state_current.number;
1101                         }
1102                         else
1103                                 cl.entities_active[i] = false;
1104                 }
1105         }
1106
1107         ent = &cl.viewent;
1108         ent->state_previous = ent->state_current;
1109         ent->state_current = defaultstate;
1110         ent->state_current.time = cl.time;
1111         ent->state_current.number = -1;
1112         ent->state_current.active = true;
1113         ent->state_current.modelindex = cl.stats[STAT_WEAPON];
1114         ent->state_current.frame = cl.stats[STAT_WEAPONFRAME];
1115         ent->state_current.flags = RENDER_VIEWMODEL;
1116         if ((cl.stats[STAT_HEALTH] <= 0 && cl_deathnoviewmodel.integer) || cl.intermission)
1117                 ent->state_current.modelindex = 0;
1118         else if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1119         {
1120                 if (gamemode == GAME_TRANSFUSION)
1121                         ent->state_current.alpha = 128;
1122                 else
1123                         ent->state_current.modelindex = 0;
1124         }
1125         ent->state_current.alpha = cl.entities[cl.viewentity].state_current.alpha;
1126         ent->state_current.effects = EF_NOSHADOW | (cl.entities[cl.viewentity].state_current.effects & (EF_ADDITIVE | EF_REFLECTIVE | EF_FULLBRIGHT | EF_NODEPTHTEST));
1127
1128         // reset animation interpolation on weaponmodel if model changed
1129         if (ent->state_previous.modelindex != ent->state_current.modelindex)
1130         {
1131                 ent->render.frame = ent->render.frame1 = ent->render.frame2 = ent->state_current.frame;
1132                 ent->render.frame1time = ent->render.frame2time = cl.time;
1133                 ent->render.framelerp = 1;
1134         }
1135         CL_UpdateNetworkEntity(ent, 32);
1136 }
1137
1138 // note this is a recursive function, but it can never get in a runaway loop (because of the delayedlink flags)
1139 void CL_LinkNetworkEntity(entity_t *e)
1140 {
1141         effectnameindex_t trailtype;
1142         vec3_t origin;
1143         vec3_t dlightcolor;
1144         vec_t dlightradius;
1145
1146         // skip inactive entities and world
1147         if (!e->state_current.active || e == cl.entities)
1148                 return;
1149         if (e->render.flags & RENDER_VIEWMODEL && !e->state_current.tagentity)
1150         {
1151                 if (!r_drawviewmodel.integer || chase_active.integer || r_refdef.envmap)
1152                         return;
1153         }
1154         else
1155         {
1156                 // if the tag entity is currently impossible, skip it
1157                 if (e->state_current.tagentity >= cl.num_entities)
1158                         return;
1159                 // if the tag entity is inactive, skip it
1160                 if (!cl.entities[e->state_current.tagentity].state_current.active)
1161                         return;
1162         }
1163
1164         // create entity dlights associated with this entity
1165         if (e->render.model && e->render.model->soundfromcenter)
1166         {
1167                 // bmodels are treated specially since their origin is usually '0 0 0'
1168                 vec3_t o;
1169                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
1170                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1171         }
1172         else
1173                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1174         trailtype = EFFECT_NONE;
1175         dlightradius = 0;
1176         dlightcolor[0] = 0;
1177         dlightcolor[1] = 0;
1178         dlightcolor[2] = 0;
1179         // LordHavoc: if the entity has no effects, don't check each
1180         if (e->render.effects & (EF_BRIGHTFIELD | EF_DIMLIGHT | EF_BRIGHTLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
1181         {
1182                 if (e->render.effects & EF_BRIGHTFIELD)
1183                 {
1184                         if (gamemode == GAME_NEXUIZ)
1185                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1186                 }
1187                 if (e->render.effects & EF_DIMLIGHT)
1188                 {
1189                         dlightradius = max(dlightradius, 200);
1190                         dlightcolor[0] += 1.50f;
1191                         dlightcolor[1] += 1.50f;
1192                         dlightcolor[2] += 1.50f;
1193                 }
1194                 if (e->render.effects & EF_BRIGHTLIGHT)
1195                 {
1196                         dlightradius = max(dlightradius, 400);
1197                         dlightcolor[0] += 3.00f;
1198                         dlightcolor[1] += 3.00f;
1199                         dlightcolor[2] += 3.00f;
1200                 }
1201                 // LordHavoc: more effects
1202                 if (e->render.effects & EF_RED) // red
1203                 {
1204                         dlightradius = max(dlightradius, 200);
1205                         dlightcolor[0] += 1.50f;
1206                         dlightcolor[1] += 0.15f;
1207                         dlightcolor[2] += 0.15f;
1208                 }
1209                 if (e->render.effects & EF_BLUE) // blue
1210                 {
1211                         dlightradius = max(dlightradius, 200);
1212                         dlightcolor[0] += 0.15f;
1213                         dlightcolor[1] += 0.15f;
1214                         dlightcolor[2] += 1.50f;
1215                 }
1216                 if (e->render.effects & EF_FLAME)
1217                         CL_ParticleTrail(EFFECT_EF_FLAME, 0, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false);
1218                 if (e->render.effects & EF_STARDUST)
1219                         CL_ParticleTrail(EFFECT_EF_STARDUST, 0, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false);
1220         }
1221         // muzzleflash fades over time, and is offset a bit
1222         if (e->persistent.muzzleflash > 0 && r_refdef.numlights < MAX_DLIGHTS)
1223         {
1224                 vec3_t v2;
1225                 vec3_t color;
1226                 trace_t trace;
1227                 matrix4x4_t tempmatrix;
1228                 Matrix4x4_Transform(&e->render.matrix, muzzleflashorigin, v2);
1229                 trace = CL_Move(origin, vec3_origin, vec3_origin, v2, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID | SUPERCONTENTS_SKY, true, false, NULL, false);
1230                 Matrix4x4_Normalize(&tempmatrix, &e->render.matrix);
1231                 Matrix4x4_SetOrigin(&tempmatrix, trace.endpos[0], trace.endpos[1], trace.endpos[2]);
1232                 Matrix4x4_Scale(&tempmatrix, 150, 1);
1233                 VectorSet(color, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f);
1234                 R_RTLight_Update(&r_refdef.lights[r_refdef.numlights++], false, &tempmatrix, color, -1, NULL, true, 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1235         }
1236         // LordHavoc: if the model has no flags, don't check each
1237         if (e->render.model && e->render.model->flags && (!e->state_current.tagentity && !(e->render.flags & RENDER_VIEWMODEL)))
1238         {
1239                 if (e->render.model->flags & EF_GIB)
1240                         trailtype = EFFECT_TR_BLOOD;
1241                 else if (e->render.model->flags & EF_ZOMGIB)
1242                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1243                 else if (e->render.model->flags & EF_TRACER)
1244                         trailtype = EFFECT_TR_WIZSPIKE;
1245                 else if (e->render.model->flags & EF_TRACER2)
1246                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1247                 else if (e->render.model->flags & EF_ROCKET)
1248                         trailtype = EFFECT_TR_ROCKET;
1249                 else if (e->render.model->flags & EF_GRENADE)
1250                 {
1251                         // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1252                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1253                 }
1254                 else if (e->render.model->flags & EF_TRACER3)
1255                         trailtype = EFFECT_TR_VORESPIKE;
1256         }
1257         // LordHavoc: customizable glow
1258         if (e->state_current.glowsize)
1259         {
1260                 // * 4 for the expansion from 0-255 to 0-1023 range,
1261                 // / 255 to scale down byte colors
1262                 dlightradius = max(dlightradius, e->state_current.glowsize * 4);
1263                 VectorMA(dlightcolor, (1.0f / 255.0f), (unsigned char *)&palette_complete[e->state_current.glowcolor], dlightcolor);
1264         }
1265         // make the glow dlight
1266         if (dlightradius > 0 && (dlightcolor[0] || dlightcolor[1] || dlightcolor[2]) && !(e->render.flags & RENDER_VIEWMODEL) && r_refdef.numlights < MAX_DLIGHTS)
1267         {
1268                 matrix4x4_t dlightmatrix;
1269                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1270                 // hack to make glowing player light shine on their gun
1271                 //if (e->state_current.number == cl.viewentity/* && !chase_active.integer*/)
1272                 //      Matrix4x4_AdjustOrigin(&dlightmatrix, 0, 0, 30);
1273                 Matrix4x4_Scale(&dlightmatrix, dlightradius, 1);
1274                 R_RTLight_Update(&r_refdef.lights[r_refdef.numlights++], false, &dlightmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1275         }
1276         // custom rtlight
1277         if ((e->state_current.lightpflags & PFLAGS_FULLDYNAMIC) && r_refdef.numlights < MAX_DLIGHTS)
1278         {
1279                 matrix4x4_t dlightmatrix;
1280                 float light[4];
1281                 VectorScale(e->state_current.light, (1.0f / 256.0f), light);
1282                 light[3] = e->state_current.light[3];
1283                 if (light[0] == 0 && light[1] == 0 && light[2] == 0)
1284                         VectorSet(light, 1, 1, 1);
1285                 if (light[3] == 0)
1286                         light[3] = 350;
1287                 // FIXME: add ambient/diffuse/specular scales as an extension ontop of TENEBRAE_GFX_DLIGHTS?
1288                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1289                 Matrix4x4_Scale(&dlightmatrix, light[3], 1);
1290                 R_RTLight_Update(&r_refdef.lights[r_refdef.numlights++], false, &dlightmatrix, light, e->state_current.lightstyle, e->state_current.skin > 0 ? va("cubemaps/%i", e->state_current.skin) : NULL, !(e->state_current.lightpflags & PFLAGS_NOSHADOW), (e->state_current.lightpflags & PFLAGS_CORONA) != 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1291         }
1292         // do trail light
1293         if (e->render.flags & RENDER_GLOWTRAIL)
1294                 trailtype = EFFECT_TR_GLOWTRAIL;
1295         if (trailtype)
1296                 CL_ParticleTrail(trailtype, 0, origin, origin, vec3_origin, vec3_origin, NULL, e->state_current.glowcolor, true, false);
1297
1298         // don't show entities with no modelindex (note: this still shows
1299         // entities which have a modelindex that resolved to a NULL model)
1300         if (e->render.model && !(e->render.effects & EF_NODRAW) && r_refdef.numentities < r_refdef.maxentities)
1301                 r_refdef.entities[r_refdef.numentities++] = &e->render;
1302         //if (cl.viewentity && e->state_current.number == cl.viewentity)
1303         //      Matrix4x4_Print(&e->render.matrix);
1304 }
1305
1306 void CL_RelinkWorld(void)
1307 {
1308         entity_t *ent = &cl.entities[0];
1309         cl.brushmodel_entities[cl.num_brushmodel_entities++] = 0;
1310         // FIXME: this should be done at load
1311         ent->render.matrix = identitymatrix;
1312         CL_UpdateRenderEntity(&ent->render);
1313         ent->render.flags = RENDER_SHADOW;
1314         if (!r_fullbright.integer)
1315                 ent->render.flags |= RENDER_LIGHT;
1316         VectorSet(ent->render.colormod, 1, 1, 1);
1317         r_refdef.worldentity = &ent->render;
1318         r_refdef.worldmodel = cl.worldmodel;
1319 }
1320
1321 static void CL_RelinkStaticEntities(void)
1322 {
1323         int i;
1324         entity_t *e;
1325         for (i = 0, e = cl.static_entities;i < cl.num_static_entities && r_refdef.numentities < r_refdef.maxentities;i++, e++)
1326         {
1327                 e->render.flags = 0;
1328                 // if the model was not loaded when the static entity was created we
1329                 // need to re-fetch the model pointer
1330                 e->render.model = cl.model_precache[e->state_baseline.modelindex];
1331                 CL_UpdateRenderEntity(&e->render);
1332                 // transparent stuff can't be lit during the opaque stage
1333                 if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
1334                         e->render.flags |= RENDER_TRANSPARENT;
1335                 // either fullbright or lit
1336                 if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
1337                         e->render.flags |= RENDER_LIGHT;
1338                 // hide player shadow during intermission or nehahra movie
1339                 if (!(e->render.effects & EF_NOSHADOW) && !(e->render.flags & RENDER_TRANSPARENT))
1340                         e->render.flags |= RENDER_SHADOW;
1341                 VectorSet(e->render.colormod, 1, 1, 1);
1342                 R_LerpAnimation(&e->render);
1343                 r_refdef.entities[r_refdef.numentities++] = &e->render;
1344         }
1345 }
1346
1347 /*
1348 ===============
1349 CL_RelinkEntities
1350 ===============
1351 */
1352 static void CL_RelinkNetworkEntities(void)
1353 {
1354         entity_t *ent;
1355         int i;
1356
1357         // start on the entity after the world
1358         for (i = 1;i < cl.num_entities;i++)
1359         {
1360                 if (cl.entities_active[i])
1361                 {
1362                         ent = cl.entities + i;
1363                         if (ent->state_current.active)
1364                                 CL_LinkNetworkEntity(ent);
1365                         else
1366                                 cl.entities_active[i] = false;
1367                 }
1368         }
1369 }
1370
1371 static void CL_RelinkEffects(void)
1372 {
1373         int i, intframe;
1374         cl_effect_t *e;
1375         entity_t *ent;
1376         float frame;
1377
1378         for (i = 0, e = cl.effects;i < cl.num_effects;i++, e++)
1379         {
1380                 if (e->active)
1381                 {
1382                         frame = (cl.time - e->starttime) * e->framerate + e->startframe;
1383                         intframe = (int)frame;
1384                         if (intframe < 0 || intframe >= e->endframe)
1385                         {
1386                                 memset(e, 0, sizeof(*e));
1387                                 while (cl.num_effects > 0 && !cl.effects[cl.num_effects - 1].active)
1388                                         cl.num_effects--;
1389                                 continue;
1390                         }
1391
1392                         if (intframe != e->frame)
1393                         {
1394                                 e->frame = intframe;
1395                                 e->frame1time = e->frame2time;
1396                                 e->frame2time = cl.time;
1397                         }
1398
1399                         // if we're drawing effects, get a new temp entity
1400                         // (NewTempEntity adds it to the render entities list for us)
1401                         if (r_draweffects.integer && (ent = CL_NewTempEntity()))
1402                         {
1403                                 // interpolation stuff
1404                                 ent->render.frame1 = intframe;
1405                                 ent->render.frame2 = intframe + 1;
1406                                 if (ent->render.frame2 >= e->endframe)
1407                                         ent->render.frame2 = -1; // disappear
1408                                 ent->render.framelerp = frame - intframe;
1409                                 ent->render.frame1time = e->frame1time;
1410                                 ent->render.frame2time = e->frame2time;
1411
1412                                 // normal stuff
1413                                 if(e->modelindex < MAX_MODELS)
1414                                         ent->render.model = cl.model_precache[e->modelindex];
1415                                 else
1416                                         ent->render.model = cl.csqc_model_precache[-(e->modelindex+1)];
1417                                 ent->render.frame = ent->render.frame2;
1418                                 ent->render.colormap = -1; // no special coloring
1419                                 ent->render.alpha = 1;
1420                                 VectorSet(ent->render.colormod, 1, 1, 1);
1421
1422                                 Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1);
1423                                 CL_UpdateRenderEntity(&ent->render);
1424                         }
1425                 }
1426         }
1427 }
1428
1429 void CL_Beam_CalculatePositions(const beam_t *b, vec3_t start, vec3_t end)
1430 {
1431         VectorCopy(b->start, start);
1432         VectorCopy(b->end, end);
1433
1434         // if coming from the player, update the start position
1435         if (b->entity == cl.viewentity)
1436         {
1437                 if (cl_beams_quakepositionhack.integer && !chase_active.integer)
1438                 {
1439                         // LordHavoc: this is a stupid hack from Quake that makes your
1440                         // lightning appear to come from your waist and cover less of your
1441                         // view
1442                         // in Quake this hack was applied to all players (causing the
1443                         // infamous crotch-lightning), but in darkplaces and QuakeWorld it
1444                         // only applies to your own lightning, and only in first person
1445                         Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, start);
1446                 }
1447                 if (cl_beams_instantaimhack.integer)
1448                 {
1449                         vec3_t dir, localend;
1450                         vec_t len;
1451                         // LordHavoc: this updates the beam direction to match your
1452                         // viewangles
1453                         VectorSubtract(end, start, dir);
1454                         len = VectorLength(dir);
1455                         VectorNormalize(dir);
1456                         VectorSet(localend, len, 0, 0);
1457                         Matrix4x4_Transform(&r_view.matrix, localend, end);
1458                 }
1459         }
1460 }
1461
1462 void CL_RelinkBeams(void)
1463 {
1464         int i;
1465         beam_t *b;
1466         vec3_t dist, org, start, end;
1467         float d;
1468         entity_t *ent;
1469         float yaw, pitch;
1470         float forward;
1471         matrix4x4_t tempmatrix;
1472
1473         for (i = 0, b = cl.beams;i < cl.num_beams;i++, b++)
1474         {
1475                 if (!b->model)
1476                         continue;
1477                 if (b->endtime < cl.time)
1478                 {
1479                         b->model = NULL;
1480                         continue;
1481                 }
1482
1483                 CL_Beam_CalculatePositions(b, start, end);
1484
1485                 if (b->lightning)
1486                 {
1487                         if (cl_beams_lightatend.integer && r_refdef.numlights < MAX_DLIGHTS)
1488                         {
1489                                 // FIXME: create a matrix from the beam start/end orientation
1490                                 vec3_t dlightcolor;
1491                                 VectorSet(dlightcolor, 0.3, 0.7, 1);
1492                                 Matrix4x4_CreateFromQuakeEntity(&tempmatrix, end[0], end[1], end[2], 0, 0, 0, 200);
1493                                 R_RTLight_Update(&r_refdef.lights[r_refdef.numlights++], false, &tempmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 1, 0, 0, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1494                         }
1495                         if (cl_beams_polygons.integer)
1496                                 continue;
1497                 }
1498
1499                 // calculate pitch and yaw
1500                 // (this is similar to the QuakeC builtin function vectoangles)
1501                 VectorSubtract(end, start, dist);
1502                 if (dist[1] == 0 && dist[0] == 0)
1503                 {
1504                         yaw = 0;
1505                         if (dist[2] > 0)
1506                                 pitch = 90;
1507                         else
1508                                 pitch = 270;
1509                 }
1510                 else
1511                 {
1512                         yaw = (int) (atan2(dist[1], dist[0]) * 180 / M_PI);
1513                         if (yaw < 0)
1514                                 yaw += 360;
1515
1516                         forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]);
1517                         pitch = (int) (atan2(dist[2], forward) * 180 / M_PI);
1518                         if (pitch < 0)
1519                                 pitch += 360;
1520                 }
1521
1522                 // add new entities for the lightning
1523                 VectorCopy (start, org);
1524                 d = VectorNormalizeLength(dist);
1525                 while (d > 0)
1526                 {
1527                         ent = CL_NewTempEntity ();
1528                         if (!ent)
1529                                 return;
1530                         //VectorCopy (org, ent->render.origin);
1531                         ent->render.model = b->model;
1532                         //ent->render.effects = EF_FULLBRIGHT;
1533                         //ent->render.angles[0] = pitch;
1534                         //ent->render.angles[1] = yaw;
1535                         //ent->render.angles[2] = rand()%360;
1536                         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1);
1537                         CL_UpdateRenderEntity(&ent->render);
1538                         VectorMA(org, 30, dist, org);
1539                         d -= 30;
1540                 }
1541         }
1542
1543         while (cl.num_beams > 0 && !cl.beams[cl.num_beams - 1].model)
1544                 cl.num_beams--;
1545 }
1546
1547 static void CL_RelinkQWNails(void)
1548 {
1549         int i;
1550         vec_t *v;
1551         entity_t *ent;
1552
1553         for (i = 0;i < cl.qw_num_nails;i++)
1554         {
1555                 v = cl.qw_nails[i];
1556
1557                 // if we're drawing effects, get a new temp entity
1558                 // (NewTempEntity adds it to the render entities list for us)
1559                 if (!(ent = CL_NewTempEntity()))
1560                         continue;
1561
1562                 // normal stuff
1563                 ent->render.model = cl.model_precache[cl.qw_modelindex_spike];
1564                 ent->render.colormap = -1; // no special coloring
1565                 ent->render.alpha = 1;
1566                 VectorSet(ent->render.colormod, 1, 1, 1);
1567
1568                 Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, v[0], v[1], v[2], v[3], v[4], v[5], 1);
1569                 CL_UpdateRenderEntity(&ent->render);
1570         }
1571 }
1572
1573 void CL_LerpPlayer(float frac)
1574 {
1575         int i;
1576
1577         cl.viewzoom = cl.mviewzoom[1] + frac * (cl.mviewzoom[0] - cl.mviewzoom[1]);
1578         for (i = 0;i < 3;i++)
1579         {
1580                 cl.punchangle[i] = cl.mpunchangle[1][i] + frac * (cl.mpunchangle[0][i] - cl.mpunchangle[1][i]);
1581                 cl.punchvector[i] = cl.mpunchvector[1][i] + frac * (cl.mpunchvector[0][i] - cl.mpunchvector[1][i]);
1582                 cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
1583         }
1584
1585         // interpolate the angles if playing a demo or spectating someone
1586         if (cls.demoplayback || cl.fixangle[0])
1587         {
1588                 for (i = 0;i < 3;i++)
1589                 {
1590                         float d = cl.mviewangles[0][i] - cl.mviewangles[1][i];
1591                         if (d > 180)
1592                                 d -= 360;
1593                         else if (d < -180)
1594                                 d += 360;
1595                         cl.viewangles[i] = cl.mviewangles[1][i] + frac * d;
1596                 }
1597         }
1598 }
1599
1600 void CSQC_RelinkAllEntities (int drawmask)
1601 {
1602         // link stuff
1603         CL_RelinkWorld();
1604         CL_RelinkStaticEntities();
1605         CL_RelinkBeams();
1606         CL_RelinkEffects();
1607
1608         // link stuff
1609         if (drawmask & ENTMASK_ENGINE)
1610         {
1611                 CL_RelinkNetworkEntities();
1612                 if (drawmask & ENTMASK_ENGINEVIEWMODELS)
1613                         CL_LinkNetworkEntity(&cl.viewent); // link gun model
1614                 CL_RelinkQWNails();
1615         }
1616
1617         // update view blend
1618         V_CalcViewBlend();
1619 }
1620
1621 /*
1622 ===============
1623 CL_ReadFromServer
1624
1625 Read all incoming data from the server
1626 ===============
1627 */
1628 int CL_ReadFromServer(void)
1629 {
1630         CL_ReadDemoMessage();
1631         CL_SendMove();
1632
1633         r_refdef.time = cl.time;
1634         r_refdef.extraupdate = !r_speeds.integer;
1635         r_refdef.numentities = 0;
1636         r_refdef.numlights = 0;
1637         r_view.matrix = identitymatrix;
1638
1639         cl.num_brushmodel_entities = 0;
1640
1641         if (cls.state == ca_connected && cls.signon == SIGNONS)
1642         {
1643                 // prepare for a new frame
1644                 CL_LerpPlayer(CL_LerpPoint());
1645                 CL_DecayLightFlashes();
1646                 CL_ClearTempEntities();
1647                 V_DriftPitch();
1648                 V_FadeViewFlashs();
1649
1650                 // now update all the network entities and the view matrix
1651                 CL_UpdateEntities();
1652
1653                 CL_RelinkLightFlashes();
1654                 CSQC_RelinkAllEntities(ENTMASK_ENGINE | ENTMASK_ENGINEVIEWMODELS);
1655
1656                 // move particles
1657                 CL_MoveParticles();
1658                 R_MoveExplosions();
1659
1660                 // update the r_refdef time again because cl.time may have changed in
1661                 // CL_LerpPoint()
1662                 r_refdef.time = cl.time;
1663         }
1664
1665         return 0;
1666 }
1667
1668 // LordHavoc: pausedemo command
1669 static void CL_PauseDemo_f (void)
1670 {
1671         cls.demopaused = !cls.demopaused;
1672         if (cls.demopaused)
1673                 Con_Print("Demo paused\n");
1674         else
1675                 Con_Print("Demo unpaused\n");
1676 }
1677
1678 /*
1679 ======================
1680 CL_Fog_f
1681 ======================
1682 */
1683 static void CL_Fog_f (void)
1684 {
1685         if (Cmd_Argc () == 1)
1686         {
1687                 Con_Printf("\"fog\" is \"%f %f %f %f\"\n", r_refdef.fog_density, r_refdef.fog_red, r_refdef.fog_green, r_refdef.fog_blue);
1688                 return;
1689         }
1690         r_refdef.fog_density = atof(Cmd_Argv(1));
1691         r_refdef.fog_red = atof(Cmd_Argv(2));
1692         r_refdef.fog_green = atof(Cmd_Argv(3));
1693         r_refdef.fog_blue = atof(Cmd_Argv(4));
1694 }
1695
1696 /*
1697 ====================
1698 CL_TimeRefresh_f
1699
1700 For program optimization
1701 ====================
1702 */
1703 static void CL_TimeRefresh_f (void)
1704 {
1705         int i;
1706         float timestart, timedelta, oldangles[3];
1707
1708         r_refdef.extraupdate = false;
1709         VectorCopy(cl.viewangles, oldangles);
1710         VectorClear(cl.viewangles);
1711
1712         timestart = Sys_DoubleTime();
1713         for (i = 0;i < 128;i++)
1714         {
1715                 Matrix4x4_CreateFromQuakeEntity(&r_view.matrix, r_view.origin[0], r_view.origin[1], r_view.origin[2], 0, i / 128.0 * 360.0, 0, 1);
1716                 CL_UpdateScreen();
1717         }
1718         timedelta = Sys_DoubleTime() - timestart;
1719
1720         VectorCopy(oldangles, cl.viewangles);
1721         Con_Printf("%f seconds (%f fps)\n", timedelta, 128/timedelta);
1722 }
1723
1724 void CL_AreaStats_f(void)
1725 {
1726         World_PrintAreaStats(&cl.world, "client");
1727 }
1728
1729 /*
1730 ===========
1731 CL_Shutdown
1732 ===========
1733 */
1734 void CL_Shutdown (void)
1735 {
1736         CL_Particles_Shutdown();
1737         CL_Parse_Shutdown();
1738
1739         Mem_FreePool (&cls.permanentmempool);
1740         Mem_FreePool (&cls.levelmempool);
1741 }
1742
1743 /*
1744 =================
1745 CL_Init
1746 =================
1747 */
1748 void CL_Init (void)
1749 {
1750         cls.levelmempool = Mem_AllocPool("client (per-level memory)", 0, NULL);
1751         cls.permanentmempool = Mem_AllocPool("client (long term memory)", 0, NULL);
1752
1753         memset(&r_refdef, 0, sizeof(r_refdef));
1754         // max entities sent to renderer per frame
1755         r_refdef.maxentities = MAX_EDICTS + 256 + 512;
1756         r_refdef.entities = (entity_render_t **)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t *) * r_refdef.maxentities);
1757
1758         CL_InitInput ();
1759
1760 //
1761 // register our commands
1762 //
1763         Cvar_RegisterVariable (&cl_upspeed);
1764         Cvar_RegisterVariable (&cl_forwardspeed);
1765         Cvar_RegisterVariable (&cl_backspeed);
1766         Cvar_RegisterVariable (&cl_sidespeed);
1767         Cvar_RegisterVariable (&cl_movespeedkey);
1768         Cvar_RegisterVariable (&cl_yawspeed);
1769         Cvar_RegisterVariable (&cl_pitchspeed);
1770         Cvar_RegisterVariable (&cl_anglespeedkey);
1771         Cvar_RegisterVariable (&cl_shownet);
1772         Cvar_RegisterVariable (&cl_nolerp);
1773         Cvar_RegisterVariable (&lookspring);
1774         Cvar_RegisterVariable (&lookstrafe);
1775         Cvar_RegisterVariable (&sensitivity);
1776         Cvar_RegisterVariable (&freelook);
1777
1778         Cvar_RegisterVariable (&m_pitch);
1779         Cvar_RegisterVariable (&m_yaw);
1780         Cvar_RegisterVariable (&m_forward);
1781         Cvar_RegisterVariable (&m_side);
1782
1783         Cvar_RegisterVariable (&cl_itembobspeed);
1784         Cvar_RegisterVariable (&cl_itembobheight);
1785
1786         Cmd_AddCommand ("entities", CL_PrintEntities_f, "print information on network entities known to client");
1787         Cmd_AddCommand ("disconnect", CL_Disconnect_f, "disconnect from server (or disconnect all clients if running a server)");
1788         Cmd_AddCommand ("record", CL_Record_f, "record a demo");
1789         Cmd_AddCommand ("stop", CL_Stop_f, "stop recording or playing a demo");
1790         Cmd_AddCommand ("playdemo", CL_PlayDemo_f, "watch a demo file");
1791         Cmd_AddCommand ("timedemo", CL_TimeDemo_f, "play back a demo as fast as possible and save statistics to benchmark.log");
1792
1793 #ifdef AUTODEMO_BROKEN
1794         Cvar_RegisterVariable (&cl_autodemo);
1795         Cvar_RegisterVariable (&cl_autodemo_nameformat);
1796 #endif
1797
1798         Cmd_AddCommand ("fog", CL_Fog_f, "set global fog parameters (density red green blue)");
1799
1800         // LordHavoc: added pausedemo
1801         Cmd_AddCommand ("pausedemo", CL_PauseDemo_f, "pause demo playback (can also safely pause demo recording if using QUAKE, QUAKEDP or NEHAHRAMOVIE protocol, useful for making movies)");
1802
1803         Cmd_AddCommand ("cl_areastats", CL_AreaStats_f, "prints statistics on entity culling during collision traces");
1804
1805         Cvar_RegisterVariable(&r_draweffects);
1806         Cvar_RegisterVariable(&cl_explosions_alpha_start);
1807         Cvar_RegisterVariable(&cl_explosions_alpha_end);
1808         Cvar_RegisterVariable(&cl_explosions_size_start);
1809         Cvar_RegisterVariable(&cl_explosions_size_end);
1810         Cvar_RegisterVariable(&cl_explosions_lifetime);
1811         Cvar_RegisterVariable(&cl_stainmaps);
1812         Cvar_RegisterVariable(&cl_stainmaps_clearonload);
1813         Cvar_RegisterVariable(&cl_beams_polygons);
1814         Cvar_RegisterVariable(&cl_beams_quakepositionhack);
1815         Cvar_RegisterVariable(&cl_beams_instantaimhack);
1816         Cvar_RegisterVariable(&cl_beams_lightatend);
1817         Cvar_RegisterVariable(&cl_noplayershadow);
1818
1819         Cvar_RegisterVariable(&cl_prydoncursor);
1820
1821         Cvar_RegisterVariable(&cl_deathnoviewmodel);
1822
1823         // for QW connections
1824         Cvar_RegisterVariable(&qport);
1825         Cvar_SetValueQuick(&qport, (rand() * RAND_MAX + rand()) & 0xffff);
1826
1827         Cmd_AddCommand("timerefresh", CL_TimeRefresh_f, "turn quickly and print rendering statistcs");
1828
1829         CL_Parse_Init();
1830         CL_Particles_Init();
1831         CL_Screen_Init();
1832
1833         CL_Video_Init();
1834 }
1835
1836
1837