changed cl_brushmodel_entities array from entity_render_t * to int, to fix a crash...
[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
27 // we need to declare some mouse variables here, because the menu system
28 // references them even when on a unix system.
29
30 cvar_t cl_shownet = {0, "cl_shownet","0"};
31 cvar_t cl_nolerp = {0, "cl_nolerp", "0"};
32
33 cvar_t cl_itembobheight = {0, "cl_itembobheight", "0"}; // try 8
34 cvar_t cl_itembobspeed = {0, "cl_itembobspeed", "0.5"};
35
36 cvar_t lookspring = {CVAR_SAVE, "lookspring","0"};
37 cvar_t lookstrafe = {CVAR_SAVE, "lookstrafe","0"};
38 cvar_t sensitivity = {CVAR_SAVE, "sensitivity","3", 1, 30};
39
40 cvar_t m_pitch = {CVAR_SAVE, "m_pitch","0.022"};
41 cvar_t m_yaw = {CVAR_SAVE, "m_yaw","0.022"};
42 cvar_t m_forward = {CVAR_SAVE, "m_forward","1"};
43 cvar_t m_side = {CVAR_SAVE, "m_side","0.8"};
44
45 cvar_t freelook = {CVAR_SAVE, "freelook", "1"};
46
47 cvar_t r_draweffects = {0, "r_draweffects", "1"};
48
49 cvar_t cl_explosions_alpha_start = {CVAR_SAVE, "cl_explosions_alpha_start", "1.5"};
50 cvar_t cl_explosions_alpha_end = {CVAR_SAVE, "cl_explosions_alpha_end", "0"};
51 cvar_t cl_explosions_size_start = {CVAR_SAVE, "cl_explosions_size_start", "16"};
52 cvar_t cl_explosions_size_end = {CVAR_SAVE, "cl_explosions_size_end", "128"};
53 cvar_t cl_explosions_lifetime = {CVAR_SAVE, "cl_explosions_lifetime", "0.5"};
54
55 cvar_t cl_stainmaps = {CVAR_SAVE, "cl_stainmaps", "1"};
56 cvar_t cl_stainmaps_clearonload = {CVAR_SAVE, "cl_stainmaps_clearonload", "1"};
57
58 cvar_t cl_beams_polygons = {CVAR_SAVE, "cl_beams_polygons", "1"};
59 cvar_t cl_beams_relative = {CVAR_SAVE, "cl_beams_relative", "1"};
60 cvar_t cl_beams_lightatend = {CVAR_SAVE, "cl_beams_lightatend", "0"};
61
62 cvar_t cl_noplayershadow = {CVAR_SAVE, "cl_noplayershadow", "0"};
63
64 cvar_t cl_prydoncursor = {0, "cl_prydoncursor", "0"};
65
66 mempool_t *cl_mempool;
67
68 client_static_t cls;
69 client_state_t  cl;
70
71 int cl_max_entities;
72 int cl_max_static_entities;
73 int cl_max_temp_entities;
74 int cl_max_effects;
75 int cl_max_beams;
76 int cl_max_dlights;
77 int cl_max_lightstyle;
78 int cl_max_brushmodel_entities;
79
80 entity_t *cl_entities;
81 qbyte *cl_entities_active;
82 entity_t *cl_static_entities;
83 entity_t *cl_temp_entities;
84 cl_effect_t *cl_effects;
85 beam_t *cl_beams;
86 dlight_t *cl_dlights;
87 lightstyle_t *cl_lightstyle;
88 int *cl_brushmodel_entities;
89
90 int cl_num_entities;
91 int cl_num_static_entities;
92 int cl_num_temp_entities;
93 int cl_num_brushmodel_entities;
94
95 /*
96 =====================
97 CL_ClearState
98
99 =====================
100 */
101 void CL_ClearState(void)
102 {
103         int i;
104
105         if (cl_entities) Mem_Free(cl_entities);cl_entities = NULL;
106         if (cl_entities_active) Mem_Free(cl_entities_active);cl_entities_active = NULL;
107         if (cl_static_entities) Mem_Free(cl_static_entities);cl_static_entities = NULL;
108         if (cl_temp_entities) Mem_Free(cl_temp_entities);cl_temp_entities = NULL;
109         if (cl_effects) Mem_Free(cl_effects);cl_effects = NULL;
110         if (cl_beams) Mem_Free(cl_beams);cl_beams = NULL;
111         if (cl_dlights) Mem_Free(cl_dlights);cl_dlights = NULL;
112         if (cl_lightstyle) Mem_Free(cl_lightstyle);cl_lightstyle = NULL;
113         if (cl_brushmodel_entities) Mem_Free(cl_brushmodel_entities);cl_brushmodel_entities = NULL;
114         if (cl.entitydatabase) EntityFrame_FreeDatabase(cl.entitydatabase);cl.entitydatabase = NULL;
115         if (cl.entitydatabase4) EntityFrame4_FreeDatabase(cl.entitydatabase4);cl.entitydatabase4 = NULL;
116         if (cl.scores) Mem_Free(cl.scores);cl.scores = NULL;
117
118         if (!sv.active)
119                 Host_ClearMemory ();
120
121 // wipe the entire cl structure
122         memset (&cl, 0, sizeof(cl));
123         // reset the view zoom interpolation
124         cl.mviewzoom[0] = cl.mviewzoom[1] = 1;
125
126         SZ_Clear (&cls.message);
127
128         cl_num_entities = 0;
129         cl_num_static_entities = 0;
130         cl_num_temp_entities = 0;
131         cl_num_brushmodel_entities = 0;
132
133         // tweak these if the game runs out
134         cl_max_entities = 256;
135         cl_max_static_entities = 256;
136         cl_max_temp_entities = 512;
137         cl_max_effects = 256;
138         cl_max_beams = 256;
139         cl_max_dlights = MAX_DLIGHTS;
140         cl_max_lightstyle = MAX_LIGHTSTYLES;
141         cl_max_brushmodel_entities = MAX_EDICTS;
142
143         cl_entities = Mem_Alloc(cl_mempool, cl_max_entities * sizeof(entity_t));
144         cl_entities_active = Mem_Alloc(cl_mempool, cl_max_brushmodel_entities * sizeof(qbyte));
145         cl_static_entities = Mem_Alloc(cl_mempool, cl_max_static_entities * sizeof(entity_t));
146         cl_temp_entities = Mem_Alloc(cl_mempool, cl_max_temp_entities * sizeof(entity_t));
147         cl_effects = Mem_Alloc(cl_mempool, cl_max_effects * sizeof(cl_effect_t));
148         cl_beams = Mem_Alloc(cl_mempool, cl_max_beams * sizeof(beam_t));
149         cl_dlights = Mem_Alloc(cl_mempool, cl_max_dlights * sizeof(dlight_t));
150         cl_lightstyle = Mem_Alloc(cl_mempool, cl_max_lightstyle * sizeof(lightstyle_t));
151         cl_brushmodel_entities = Mem_Alloc(cl_mempool, cl_max_brushmodel_entities * sizeof(int));
152
153         // LordHavoc: have to set up the baseline info for alpha and other stuff
154         for (i = 0;i < cl_max_entities;i++)
155         {
156                 cl_entities[i].state_baseline = defaultstate;
157                 cl_entities[i].state_previous = defaultstate;
158                 cl_entities[i].state_current = defaultstate;
159         }
160
161         CL_Screen_NewMap();
162         CL_Particles_Clear();
163         CL_CGVM_Clear();
164 }
165
166 void CL_ExpandEntities(int num)
167 {
168         int i, oldmaxentities;
169         entity_t *oldentities;
170         if (num >= cl_max_entities)
171         {
172                 if (!cl_entities)
173                         Host_Error("CL_ExpandEntities: cl_entities not initialized\n");
174                 if (num >= MAX_EDICTS)
175                         Host_Error("CL_ExpandEntities: num %i >= %i\n", num, MAX_EDICTS);
176                 oldmaxentities = cl_max_entities;
177                 oldentities = cl_entities;
178                 cl_max_entities = (num & ~255) + 256;
179                 cl_entities = Mem_Alloc(cl_mempool, cl_max_entities * sizeof(entity_t));
180                 memcpy(cl_entities, oldentities, oldmaxentities * sizeof(entity_t));
181                 Mem_Free(oldentities);
182                 for (i = oldmaxentities;i < cl_max_entities;i++)
183                 {
184                         cl_entities[i].state_baseline = defaultstate;
185                         cl_entities[i].state_previous = defaultstate;
186                         cl_entities[i].state_current = defaultstate;
187                 }
188         }
189 }
190
191 /*
192 =====================
193 CL_Disconnect
194
195 Sends a disconnect message to the server
196 This is also called on Host_Error, so it shouldn't cause any errors
197 =====================
198 */
199 void CL_Disconnect(void)
200 {
201         if (cls.state == ca_dedicated)
202                 return;
203
204         Con_DPrintf("CL_Disconnect\n");
205
206 // stop sounds (especially looping!)
207         S_StopAllSounds ();
208
209         // clear contents blends
210         cl.cshifts[0].percent = 0;
211         cl.cshifts[1].percent = 0;
212         cl.cshifts[2].percent = 0;
213         cl.cshifts[3].percent = 0;
214
215         cl.worldmodel = NULL;
216
217         if (cls.demoplayback)
218                 CL_StopPlayback();
219         else if (cls.netcon)
220         {
221                 if (cls.demorecording)
222                         CL_Stop_f();
223
224                 Con_DPrint("Sending clc_disconnect\n");
225                 SZ_Clear(&cls.message);
226                 MSG_WriteByte(&cls.message, clc_disconnect);
227                 NetConn_SendUnreliableMessage(cls.netcon, &cls.message);
228                 SZ_Clear(&cls.message);
229                 NetConn_Close(cls.netcon);
230                 cls.netcon = NULL;
231         }
232         cls.state = ca_disconnected;
233
234         cls.demoplayback = cls.timedemo = false;
235         cls.signon = 0;
236 }
237
238 void CL_Disconnect_f(void)
239 {
240         CL_Disconnect ();
241         if (sv.active)
242                 Host_ShutdownServer (false);
243 }
244
245
246
247
248 /*
249 =====================
250 CL_EstablishConnection
251
252 Host should be either "local" or a net address
253 =====================
254 */
255 void CL_EstablishConnection(const char *host)
256 {
257         if (cls.state == ca_dedicated)
258                 return;
259
260         // clear menu's connect error message
261         M_Update_Return_Reason("");
262         cls.demonum = -1;
263
264         // stop demo loop in case this fails
265         CL_Disconnect();
266         NetConn_ClientFrame();
267         NetConn_ServerFrame();
268
269         if (LHNETADDRESS_FromString(&cls.connect_address, host, 26000) && (cls.connect_mysocket = NetConn_ChooseClientSocketForAddress(&cls.connect_address)))
270         {
271                 cls.connect_trying = true;
272                 cls.connect_remainingtries = 3;
273                 cls.connect_nextsendtime = 0;
274                 M_Update_Return_Reason("Trying to connect...");
275                 if (sv.active)
276                 {
277                         NetConn_ClientFrame();
278                         NetConn_ServerFrame();
279                         NetConn_ClientFrame();
280                         NetConn_ServerFrame();
281                         NetConn_ClientFrame();
282                         NetConn_ServerFrame();
283                         NetConn_ClientFrame();
284                         NetConn_ServerFrame();
285                 }
286         }
287         else
288         {
289                 Con_Print("Unable to find a suitable network socket to connect to server.\n");
290                 M_Update_Return_Reason("No network");
291         }
292 }
293
294 /*
295 ==============
296 CL_PrintEntities_f
297 ==============
298 */
299 static void CL_PrintEntities_f(void)
300 {
301         entity_t *ent;
302         int i, j;
303         char name[32];
304
305         for (i = 0, ent = cl_entities;i < cl_num_entities;i++, ent++)
306         {
307                 if (!ent->state_current.active)
308                         continue;
309
310                 if (ent->render.model)
311                         strlcpy (name, ent->render.model->name, 25);
312                 else
313                         strcpy(name, "--no model--");
314                 for (j = strlen(name);j < 25;j++)
315                         name[j] = ' ';
316                 Con_Printf("%3i: %s:%04i (%5i %5i %5i) [%3i %3i %3i] %4.2f %5.3f\n", i, name, ent->render.frame, (int) ent->render.origin[0], (int) ent->render.origin[1], (int) ent->render.origin[2], (int) ent->render.angles[0] % 360, (int) ent->render.angles[1] % 360, (int) ent->render.angles[2] % 360, ent->render.scale, ent->render.alpha);
317         }
318 }
319
320 //static const vec3_t nomodelmins = {-16, -16, -16};
321 //static const vec3_t nomodelmaxs = {16, 16, 16};
322 void CL_BoundingBoxForEntity(entity_render_t *ent)
323 {
324         if (ent->model)
325         {
326                 //if (ent->angles[0] || ent->angles[2])
327                 if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0)
328                 {
329                         // pitch or roll
330                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->rotatedmins[0];
331                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->rotatedmins[1];
332                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->rotatedmins[2];
333                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->rotatedmaxs[0];
334                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->rotatedmaxs[1];
335                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->rotatedmaxs[2];
336                         //VectorAdd(ent->origin, ent->model->rotatedmins, ent->mins);
337                         //VectorAdd(ent->origin, ent->model->rotatedmaxs, ent->maxs);
338                 }
339                 //else if (ent->angles[1])
340                 else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0)
341                 {
342                         // yaw
343                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->yawmins[0];
344                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->yawmins[1];
345                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->yawmins[2];
346                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->yawmaxs[0];
347                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->yawmaxs[1];
348                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->yawmaxs[2];
349                         //VectorAdd(ent->origin, ent->model->yawmins, ent->mins);
350                         //VectorAdd(ent->origin, ent->model->yawmaxs, ent->maxs);
351                 }
352                 else
353                 {
354                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->normalmins[0];
355                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->normalmins[1];
356                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->normalmins[2];
357                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->normalmaxs[0];
358                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->normalmaxs[1];
359                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->normalmaxs[2];
360                         //VectorAdd(ent->origin, ent->model->normalmins, ent->mins);
361                         //VectorAdd(ent->origin, ent->model->normalmaxs, ent->maxs);
362                 }
363         }
364         else
365         {
366                 ent->mins[0] = ent->matrix.m[0][3] - 16;
367                 ent->mins[1] = ent->matrix.m[1][3] - 16;
368                 ent->mins[2] = ent->matrix.m[2][3] - 16;
369                 ent->maxs[0] = ent->matrix.m[0][3] + 16;
370                 ent->maxs[1] = ent->matrix.m[1][3] + 16;
371                 ent->maxs[2] = ent->matrix.m[2][3] + 16;
372                 //VectorAdd(ent->origin, nomodelmins, ent->mins);
373                 //VectorAdd(ent->origin, nomodelmaxs, ent->maxs);
374         }
375 }
376
377 /*
378 ===============
379 CL_LerpPoint
380
381 Determines the fraction between the last two messages that the objects
382 should be put at.
383 ===============
384 */
385 static float CL_LerpPoint(void)
386 {
387         float f;
388
389         // dropped packet, or start of demo
390         if (cl.mtime[1] < cl.mtime[0] - 0.1)
391                 cl.mtime[1] = cl.mtime[0] - 0.1;
392
393         cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
394
395         // LordHavoc: lerp in listen games as the server is being capped below the client (usually)
396         f = cl.mtime[0] - cl.mtime[1];
397         if (!f || cl_nolerp.integer || cls.timedemo || cl.islocalgame)
398         {
399                 cl.time = cl.mtime[0];
400                 return 1;
401         }
402
403         f = (cl.time - cl.mtime[1]) / f;
404         return bound(0, f, 1);
405 }
406
407 void CL_ClearTempEntities (void)
408 {
409         cl_num_temp_entities = 0;
410 }
411
412 entity_t *CL_NewTempEntity(void)
413 {
414         entity_t *ent;
415
416         if (r_refdef.numentities >= r_refdef.maxentities)
417                 return NULL;
418         if (cl_num_temp_entities >= cl_max_temp_entities)
419                 return NULL;
420         ent = &cl_temp_entities[cl_num_temp_entities++];
421         memset (ent, 0, sizeof(*ent));
422         r_refdef.entities[r_refdef.numentities++] = &ent->render;
423
424         ent->render.colormap = -1; // no special coloring
425         ent->render.scale = 1;
426         ent->render.alpha = 1;
427         VectorSet(ent->render.colormod, 1, 1, 1);
428         return ent;
429 }
430
431 void CL_Effect(vec3_t org, int modelindex, int startframe, int framecount, float framerate)
432 {
433         int i;
434         cl_effect_t *e;
435         if (!modelindex) // sanity check
436                 return;
437         for (i = 0, e = cl_effects;i < cl_max_effects;i++, e++)
438         {
439                 if (e->active)
440                         continue;
441                 e->active = true;
442                 VectorCopy(org, e->origin);
443                 e->modelindex = modelindex;
444                 e->starttime = cl.time;
445                 e->startframe = startframe;
446                 e->endframe = startframe + framecount;
447                 e->framerate = framerate;
448
449                 e->frame = 0;
450                 e->frame1time = cl.time;
451                 e->frame2time = cl.time;
452                 break;
453         }
454 }
455
456 void CL_AllocDlight(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)
457 {
458         int i;
459         dlight_t *dl;
460
461         /*
462 // first look for an exact key match
463         if (ent)
464         {
465                 dl = cl_dlights;
466                 for (i = 0;i < MAX_DLIGHTS;i++, dl++)
467                         if (dl->ent == ent)
468                                 goto dlightsetup;
469         }
470         */
471
472 // then look for anything else
473         dl = cl_dlights;
474         for (i = 0;i < MAX_DLIGHTS;i++, dl++)
475                 if (!dl->radius)
476                         goto dlightsetup;
477
478         // unable to find one
479         return;
480
481 dlightsetup:
482         //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius);
483         memset (dl, 0, sizeof(*dl));
484         dl->matrix = *matrix;
485         dl->ent = ent;
486         dl->origin[0] = dl->matrix.m[0][3];
487         dl->origin[1] = dl->matrix.m[1][3];
488         dl->origin[2] = dl->matrix.m[2][3];
489         CL_FindNonSolidLocation(dl->origin, dl->origin, 6);
490         dl->matrix.m[0][3] = dl->origin[0];
491         dl->matrix.m[1][3] = dl->origin[1];
492         dl->matrix.m[2][3] = dl->origin[2];
493         dl->radius = radius;
494         dl->color[0] = red;
495         dl->color[1] = green;
496         dl->color[2] = blue;
497         dl->decay = decay;
498         if (lifetime)
499                 dl->die = cl.time + lifetime;
500         else
501                 dl->die = 0;
502         dl->cubemapnum = cubemapnum;
503         dl->style = style;
504         dl->shadow = shadowenable;
505         dl->corona = corona;
506         dl->flags = flags;
507         dl->coronasizescale = coronasizescale;
508         dl->ambientscale = ambientscale;
509         dl->diffusescale = diffusescale;
510         dl->specularscale = specularscale;
511 }
512
513 void CL_DecayLights(void)
514 {
515         int i;
516         dlight_t *dl;
517         float time;
518
519         time = cl.time - cl.oldtime;
520         for (i = 0, dl = cl_dlights;i < MAX_DLIGHTS;i++, dl++)
521                 if (dl->radius)
522                         dl->radius = (cl.time < dl->die) ? max(0, dl->radius - time * dl->decay) : 0;
523 }
524
525 #define MAXVIEWMODELS 32
526 entity_t *viewmodels[MAXVIEWMODELS];
527 int numviewmodels;
528
529 matrix4x4_t viewmodelmatrix;
530
531 static int entitylinkframenumber;
532
533 static const vec3_t muzzleflashorigin = {18, 0, 0};
534
535 extern void V_DriftPitch(void);
536 extern void V_FadeViewFlashs(void);
537 extern void V_CalcViewBlend(void);
538
539 extern void V_CalcRefdef(void);
540 // note this is a recursive function, but it can never get in a runaway loop (because of the delayedlink flags)
541 void CL_LinkNetworkEntity(entity_t *e)
542 {
543         matrix4x4_t *matrix, blendmatrix, tempmatrix, matrix2;
544         //matrix4x4_t dlightmatrix;
545         int j, k, l, trailtype, temp;
546         float origin[3], angles[3], delta[3], lerp, dlightcolor[3], dlightradius, mins[3], maxs[3], v[3], v2[3], d;
547         entity_t *t;
548         model_t *model;
549         //entity_persistent_t *p = &e->persistent;
550         //entity_render_t *r = &e->render;
551         if (e->persistent.linkframe != entitylinkframenumber)
552         {
553                 e->persistent.linkframe = entitylinkframenumber;
554                 // skip inactive entities and world
555                 if (!e->state_current.active || e == cl_entities)
556                         return;
557                 e->render.alpha = e->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate?
558                 e->render.scale = e->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate?
559                 e->render.flags = e->state_current.flags;
560                 e->render.effects = e->state_current.effects;
561                 if (e->state_current.flags & RENDER_COLORMAPPED)
562                         e->render.colormap = e->state_current.colormap;
563                 else if (cl.scores != NULL && e->state_current.colormap)
564                         e->render.colormap = cl.scores[e->state_current.colormap - 1].colors; // color it
565                 else
566                         e->render.colormap = -1; // no special coloring
567                 e->render.skinnum = e->state_current.skin;
568                 VectorScale(e->state_current.colormod, (1.0f / 32.0f), e->render.colormod);
569                 if (e->render.flags & RENDER_VIEWMODEL)
570                 {
571                         if (!r_drawviewmodel.integer || chase_active.integer || envmap)
572                                 return;
573                         if (cl.viewentity)
574                                 CL_LinkNetworkEntity(cl_entities + cl.viewentity);
575                         matrix = &viewmodelmatrix;
576                         if (e == &cl.viewent && cl_entities[cl.viewentity].state_current.active)
577                         {
578                                 e->state_current.alpha = cl_entities[cl.viewentity].state_current.alpha;
579                                 e->state_current.effects = EF_NOSHADOW | (cl_entities[cl.viewentity].state_current.effects & (EF_ADDITIVE | EF_REFLECTIVE | EF_FULLBRIGHT | EF_NODEPTHTEST));
580                         }
581                 }
582                 else
583                 {
584                         // if the tag entity is currently impossible, skip it
585                         if (e->state_current.tagentity >= cl_num_entities)
586                                 return;
587                         t = cl_entities + e->state_current.tagentity;
588                         // if the tag entity is inactive, skip it
589                         if (!t->state_current.active)
590                                 return;
591                         // note: this can link to world
592                         CL_LinkNetworkEntity(t);
593                         // make relative to the entity
594                         matrix = &t->render.matrix;
595                         // some properties of the tag entity carry over
596                         e->render.flags |= t->render.flags & RENDER_EXTERIORMODEL;
597                         // if a valid tagindex is used, make it relative to that tag instead
598                         // FIXME: use a model function to get tag info (need to handle skeletal)
599                         if (e->state_current.tagentity && e->state_current.tagindex >= 1 && (model = t->render.model))
600                         {
601                                 // blend the matrices
602                                 memset(&blendmatrix, 0, sizeof(blendmatrix));
603                                 for (j = 0;j < 4 && t->render.frameblend[j].lerp > 0;j++)
604                                 {
605                                         matrix4x4_t tagmatrix;
606                                         Mod_Alias_GetTagMatrix(model, t->render.frameblend[j].frame, e->state_current.tagindex - 1, &tagmatrix);
607                                         d = t->render.frameblend[j].lerp;
608                                         for (l = 0;l < 4;l++)
609                                                 for (k = 0;k < 4;k++)
610                                                         blendmatrix.m[l][k] += d * tagmatrix.m[l][k];
611                                 }
612                                 // concat the tag matrices onto the entity matrix
613                                 Matrix4x4_Concat(&tempmatrix, &t->render.matrix, &blendmatrix);
614                                 // use the constructed tag matrix
615                                 matrix = &tempmatrix;
616                         }
617                 }
618
619                 // movement lerp
620                 if (e->persistent.lerpdeltatime > 0 && (lerp = (cl.time - e->persistent.lerpstarttime) / e->persistent.lerpdeltatime) < 1)
621                 {
622                         // interpolate the origin and angles
623                         VectorLerp(e->persistent.oldorigin, lerp, e->persistent.neworigin, origin);
624                         VectorSubtract(e->persistent.newangles, e->persistent.oldangles, delta);
625                         if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360;
626                         if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360;
627                         if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360;
628                         VectorMA(e->persistent.oldangles, lerp, delta, angles);
629                 }
630                 else
631                 {
632                         // no interpolation
633                         VectorCopy(e->persistent.neworigin, origin);
634                         VectorCopy(e->persistent.newangles, angles);
635                 }
636
637                 // model setup and some modelflags
638                 e->render.model = cl.model_precache[e->state_current.modelindex];
639                 if (e->render.model)
640                 {
641                         Mod_CheckLoaded(e->render.model);
642                         // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
643                         if (e->render.model->type == mod_alias || (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC))
644                                 angles[0] = -angles[0];
645                         if ((e->render.model->flags & EF_ROTATE) && (!e->state_current.tagentity && !(e->render.flags & RENDER_VIEWMODEL)))
646                         {
647                                 angles[1] = ANGLEMOD(100*cl.time);
648                                 if (cl_itembobheight.value)
649                                         origin[2] += (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value;
650                         }
651                         // transfer certain model flags to effects
652                         e->render.effects |= e->render.model->flags2 & (EF_FULLBRIGHT | EF_ADDITIVE);
653                         if (cl_prydoncursor.integer && (e->render.effects & EF_SELECTABLE) && cl.cmd.cursor_entitynumber == e->state_current.number)
654                                 VectorScale(e->render.colormod, 2, e->render.colormod);
655                 }
656
657                 // animation lerp
658                 if (e->render.frame2 == e->state_current.frame)
659                 {
660                         // update frame lerp fraction
661                         e->render.framelerp = 1;
662                         if (e->render.frame2time > e->render.frame1time)
663                         {
664                                 // make sure frame lerp won't last longer than 100ms
665                                 // (this mainly helps with models that use framegroups and
666                                 // switch between them infrequently)
667                                 e->render.framelerp = (cl.time - e->render.frame2time) / min(e->render.frame2time - e->render.frame1time, 0.1);
668                                 e->render.framelerp = bound(0, e->render.framelerp, 1);
669                         }
670                 }
671                 else
672                 {
673                         // begin a new frame lerp
674                         e->render.frame1 = e->render.frame2;
675                         e->render.frame1time = e->render.frame2time;
676                         e->render.frame = e->render.frame2 = e->state_current.frame;
677                         e->render.frame2time = cl.time;
678                         e->render.framelerp = 0;
679                 }
680                 R_LerpAnimation(&e->render);
681
682                 // set up the render matrix
683                 // FIXME: e->render.scale should go away
684                 Matrix4x4_CreateFromQuakeEntity(&matrix2, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
685                 // concat the matrices to make the entity relative to its tag
686                 Matrix4x4_Concat(&e->render.matrix, matrix, &matrix2);
687                 // make the other useful stuff
688                 Matrix4x4_Invert_Simple(&e->render.inversematrix, &e->render.matrix);
689                 CL_BoundingBoxForEntity(&e->render);
690
691                 // handle effects now that we know where this entity is in the world...
692                 origin[0] = e->render.matrix.m[0][3];
693                 origin[1] = e->render.matrix.m[1][3];
694                 origin[2] = e->render.matrix.m[2][3];
695                 trailtype = -1;
696                 dlightradius = 0;
697                 dlightcolor[0] = 0;
698                 dlightcolor[1] = 0;
699                 dlightcolor[2] = 0;
700                 // LordHavoc: if the entity has no effects, don't check each
701                 if (e->render.effects)
702                 {
703                         if (e->render.effects & EF_BRIGHTFIELD)
704                         {
705                                 if (gamemode == GAME_NEXUIZ)
706                                 {
707                                         dlightradius = max(dlightradius, 200);
708                                         dlightcolor[0] += 0.75f;
709                                         dlightcolor[1] += 1.50f;
710                                         dlightcolor[2] += 3.00f;
711                                         trailtype = 8;
712                                 }
713                                 else
714                                         CL_EntityParticles(e);
715                         }
716                         if (e->render.effects & EF_MUZZLEFLASH)
717                                 e->persistent.muzzleflash = 1.0f;
718                         if (e->render.effects & EF_DIMLIGHT)
719                         {
720                                 dlightradius = max(dlightradius, 200);
721                                 dlightcolor[0] += 1.50f;
722                                 dlightcolor[1] += 1.50f;
723                                 dlightcolor[2] += 1.50f;
724                         }
725                         if (e->render.effects & EF_BRIGHTLIGHT)
726                         {
727                                 dlightradius = max(dlightradius, 400);
728                                 dlightcolor[0] += 3.00f;
729                                 dlightcolor[1] += 3.00f;
730                                 dlightcolor[2] += 3.00f;
731                         }
732                         // LordHavoc: more effects
733                         if (e->render.effects & EF_RED) // red
734                         {
735                                 dlightradius = max(dlightradius, 200);
736                                 dlightcolor[0] += 1.50f;
737                                 dlightcolor[1] += 0.15f;
738                                 dlightcolor[2] += 0.15f;
739                         }
740                         if (e->render.effects & EF_BLUE) // blue
741                         {
742                                 dlightradius = max(dlightradius, 200);
743                                 dlightcolor[0] += 0.15f;
744                                 dlightcolor[1] += 0.15f;
745                                 dlightcolor[2] += 1.50f;
746                         }
747                         if (e->render.effects & EF_FLAME)
748                         {
749                                 mins[0] = origin[0] - 16.0f;
750                                 mins[1] = origin[1] - 16.0f;
751                                 mins[2] = origin[2] - 16.0f;
752                                 maxs[0] = origin[0] + 16.0f;
753                                 maxs[1] = origin[1] + 16.0f;
754                                 maxs[2] = origin[2] + 16.0f;
755                                 // how many flames to make
756                                 temp = (int) (cl.time * 300) - (int) (cl.oldtime * 300);
757                                 CL_FlameCube(mins, maxs, temp);
758                                 d = lhrandom(0.75f, 1);
759                                 dlightradius = max(dlightradius, 200);
760                                 dlightcolor[0] += d * 2.0f;
761                                 dlightcolor[1] += d * 1.5f;
762                                 dlightcolor[2] += d * 0.5f;
763                         }
764                         if (e->render.effects & EF_STARDUST)
765                         {
766                                 mins[0] = origin[0] - 16.0f;
767                                 mins[1] = origin[1] - 16.0f;
768                                 mins[2] = origin[2] - 16.0f;
769                                 maxs[0] = origin[0] + 16.0f;
770                                 maxs[1] = origin[1] + 16.0f;
771                                 maxs[2] = origin[2] + 16.0f;
772                                 // how many particles to make
773                                 temp = (int) (cl.time * 200) - (int) (cl.oldtime * 200);
774                                 CL_Stardust(mins, maxs, temp);
775                                 dlightradius = max(dlightradius, 200);
776                                 dlightcolor[0] += 1.0f;
777                                 dlightcolor[1] += 0.7f;
778                                 dlightcolor[2] += 0.3f;
779                         }
780                 }
781                 // muzzleflash fades over time, and is offset a bit
782                 if (e->persistent.muzzleflash > 0)
783                 {
784                         Matrix4x4_Transform(&e->render.matrix, muzzleflashorigin, v2);
785                         CL_TraceLine(origin, v2, v, NULL, true, NULL, SUPERCONTENTS_SOLID | SUPERCONTENTS_SKY);
786                         tempmatrix = e->render.matrix;
787                         tempmatrix.m[0][3] = v[0];
788                         tempmatrix.m[1][3] = v[1];
789                         tempmatrix.m[2][3] = v[2];
790                         CL_AllocDlight(NULL, &tempmatrix, 100, e->persistent.muzzleflash, e->persistent.muzzleflash, e->persistent.muzzleflash, 0, 0, 0, -1, true, 0, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
791                         e->persistent.muzzleflash -= cl.frametime * 10;
792                 }
793                 // LordHavoc: if the model has no flags, don't check each
794                 if (e->render.model && e->render.model->flags && (!e->state_current.tagentity && !(e->render.flags & RENDER_VIEWMODEL)))
795                 {
796                         if (e->render.model->flags & EF_GIB)
797                                 trailtype = 2;
798                         else if (e->render.model->flags & EF_ZOMGIB)
799                                 trailtype = 4;
800                         else if (e->render.model->flags & EF_TRACER)
801                         {
802                                 trailtype = 3;
803                                 dlightradius = max(dlightradius, 100);
804                                 dlightcolor[0] += 0.25f;
805                                 dlightcolor[1] += 1.00f;
806                                 dlightcolor[2] += 0.25f;
807                         }
808                         else if (e->render.model->flags & EF_TRACER2)
809                         {
810                                 trailtype = 5;
811                                 dlightradius = max(dlightradius, 100);
812                                 dlightcolor[0] += 1.00f;
813                                 dlightcolor[1] += 0.60f;
814                                 dlightcolor[2] += 0.20f;
815                         }
816                         else if (e->render.model->flags & EF_ROCKET)
817                         {
818                                 trailtype = 0;
819                                 dlightradius = max(dlightradius, 200);
820                                 dlightcolor[0] += 3.00f;
821                                 dlightcolor[1] += 1.50f;
822                                 dlightcolor[2] += 0.50f;
823                         }
824                         else if (e->render.model->flags & EF_GRENADE)
825                         {
826                                 // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
827                                 trailtype = e->render.alpha == -1 ? 7 : 1;
828                         }
829                         else if (e->render.model->flags & EF_TRACER3)
830                         {
831                                 trailtype = 6;
832                                 if (gamemode == GAME_PRYDON)
833                                 {
834                                         dlightradius = max(dlightradius, 100);
835                                         dlightcolor[0] += 0.30f;
836                                         dlightcolor[1] += 0.60f;
837                                         dlightcolor[2] += 1.20f;
838                                 }
839                                 else
840                                 {
841                                         dlightradius = max(dlightradius, 200);
842                                         dlightcolor[0] += 1.20f;
843                                         dlightcolor[1] += 0.50f;
844                                         dlightcolor[2] += 1.00f;
845                                 }
846                         }
847                 }
848                 // LordHavoc: customizable glow
849                 if (e->state_current.glowsize)
850                 {
851                         // * 4 for the expansion from 0-255 to 0-1023 range,
852                         // / 255 to scale down byte colors
853                         dlightradius = max(dlightradius, e->state_current.glowsize * 4);
854                         VectorMA(dlightcolor, (1.0f / 255.0f), (qbyte *)&palette_complete[e->state_current.glowcolor], dlightcolor);
855                 }
856                 // make the glow dlight
857                 if (dlightradius > 0 && (dlightcolor[0] || dlightcolor[1] || dlightcolor[2]) && !(e->render.flags & RENDER_VIEWMODEL))
858                 {
859                         //dlightmatrix = e->render.matrix;
860                         // hack to make glowing player light shine on their gun
861                         //if (e->state_current.number == cl.viewentity/* && !chase_active.integer*/)
862                         //      dlightmatrix.m[2][3] += 30;
863                         CL_AllocDlight(&e->render, &e->render.matrix, dlightradius, dlightcolor[0], dlightcolor[1], dlightcolor[2], 0, 0, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
864                 }
865                 // custom rtlight
866                 if (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC)
867                 {
868                         float light[4];
869                         VectorScale(e->state_current.light, (1.0f / 256.0f), light);
870                         light[3] = e->state_current.light[3];
871                         if (light[0] == 0 && light[1] == 0 && light[2] == 0)
872                                 VectorSet(light, 1, 1, 1);
873                         if (light[3] == 0)
874                                 light[3] = 350;
875                         // FIXME: add ambient/diffuse/specular scales as an extension ontop of TENEBRAE_GFX_DLIGHTS?
876                         CL_AllocDlight(&e->render, &e->render.matrix, light[3], light[0], light[1], light[2], 0, 0, e->state_current.skin, e->state_current.lightstyle, !(e->state_current.lightpflags & PFLAGS_NOSHADOW), (e->state_current.lightpflags & PFLAGS_CORONA) != 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
877                 }
878                 // do trails
879                 if (e->render.flags & RENDER_GLOWTRAIL)
880                         trailtype = 9;
881                 if (trailtype >= 0)
882                         CL_RocketTrail(e->persistent.trail_origin, origin, trailtype, e->state_current.glowcolor, e);
883                 VectorCopy(origin, e->persistent.trail_origin);
884                 // tenebrae's sprites are all additive mode (weird)
885                 if (gamemode == GAME_TENEBRAE && e->render.model && e->render.model->type == mod_sprite)
886                         e->render.effects |= EF_ADDITIVE;
887                 // player model is only shown with chase_active on
888                 if (e->state_current.number == cl.viewentity)
889                         e->render.flags |= RENDER_EXTERIORMODEL;
890                 // transparent stuff can't be lit during the opaque stage
891                 if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
892                         e->render.flags |= RENDER_TRANSPARENT;
893                 // either fullbright or lit
894                 if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
895                         e->render.flags |= RENDER_LIGHT;
896                 // hide player shadow during intermission or nehahra movie
897                 if (!(e->render.effects & EF_NOSHADOW)
898                  && !(e->render.flags & (RENDER_VIEWMODEL | RENDER_TRANSPARENT))
899                  && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cl.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
900                         e->render.flags |= RENDER_SHADOW;
901                 // as soon as player is known we can call V_CalcRefDef
902                 if (e->state_current.number == cl.viewentity)
903                         V_CalcRefdef();
904                 if (e->render.model && e->render.model->name[0] == '*' && e->render.model->TraceBox)
905                         cl_brushmodel_entities[cl_num_brushmodel_entities++] = e->state_current.number;
906                 // don't show entities with no modelindex (note: this still shows
907                 // entities which have a modelindex that resolved to a NULL model)
908                 if (e->render.model && !(e->render.effects & EF_NODRAW) && r_refdef.numentities < r_refdef.maxentities)
909                         r_refdef.entities[r_refdef.numentities++] = &e->render;
910                 //if (cl.viewentity && e->state_current.number == cl.viewentity)
911                 //      Matrix4x4_Print(&e->render.matrix);
912         }
913 }
914
915 void CL_RelinkWorld(void)
916 {
917         entity_t *ent = &cl_entities[0];
918         cl_brushmodel_entities[cl_num_brushmodel_entities++] = 0;
919         // FIXME: this should be done at load
920         Matrix4x4_CreateIdentity(&ent->render.matrix);
921         Matrix4x4_CreateIdentity(&ent->render.inversematrix);
922         R_LerpAnimation(&ent->render);
923         CL_BoundingBoxForEntity(&ent->render);
924         ent->render.flags = RENDER_SHADOW;
925         if (!r_fullbright.integer)
926                 ent->render.flags |= RENDER_LIGHT;
927         VectorSet(ent->render.colormod, 1, 1, 1);
928         r_refdef.worldentity = &ent->render;
929         r_refdef.worldmodel = cl.worldmodel;
930 }
931
932 static void CL_RelinkStaticEntities(void)
933 {
934         int i;
935         entity_t *e;
936         for (i = 0, e = cl_static_entities;i < cl_num_static_entities && r_refdef.numentities < r_refdef.maxentities;i++, e++)
937         {
938                 Mod_CheckLoaded(e->render.model);
939                 e->render.flags = 0;
940                 // transparent stuff can't be lit during the opaque stage
941                 if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
942                         e->render.flags |= RENDER_TRANSPARENT;
943                 // either fullbright or lit
944                 if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
945                         e->render.flags |= RENDER_LIGHT;
946                 // hide player shadow during intermission or nehahra movie
947                 if (!(e->render.effects & EF_NOSHADOW) && !(e->render.flags & RENDER_TRANSPARENT))
948                         e->render.flags |= RENDER_SHADOW;
949                 VectorSet(e->render.colormod, 1, 1, 1);
950                 R_LerpAnimation(&e->render);
951                 r_refdef.entities[r_refdef.numentities++] = &e->render;
952         }
953 }
954
955 /*
956 ===============
957 CL_RelinkEntities
958 ===============
959 */
960 static void CL_RelinkNetworkEntities(void)
961 {
962         entity_t *ent;
963         int i;
964
965         ent = &cl.viewent;
966         ent->state_previous = ent->state_current;
967         ent->state_current = defaultstate;
968         ent->state_current.time = cl.time;
969         ent->state_current.number = -1;
970         ent->state_current.active = true;
971         ent->state_current.modelindex = cl.stats[STAT_WEAPON];
972         ent->state_current.frame = cl.stats[STAT_WEAPONFRAME];
973         ent->state_current.flags = RENDER_VIEWMODEL;
974         if (cl.stats[STAT_HEALTH] <= 0 || cl.intermission)
975                 ent->state_current.modelindex = 0;
976         else if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
977         {
978                 if (gamemode == GAME_TRANSFUSION)
979                         ent->state_current.alpha = 128;
980                 else
981                         ent->state_current.modelindex = 0;
982         }
983
984         // reset animation interpolation on weaponmodel if model changed
985         if (ent->state_previous.modelindex != ent->state_current.modelindex)
986         {
987                 ent->render.frame = ent->render.frame1 = ent->render.frame2 = ent->state_current.frame;
988                 ent->render.frame1time = ent->render.frame2time = cl.time;
989                 ent->render.framelerp = 1;
990         }
991
992         // start on the entity after the world
993         entitylinkframenumber++;
994         for (i = 1;i < cl_num_entities;i++)
995         {
996                 if (cl_entities_active[i])
997                 {
998                         ent = cl_entities + i;
999                         if (ent->state_current.active)
1000                                 CL_LinkNetworkEntity(ent);
1001                         else
1002                                 cl_entities_active[i] = false;
1003                 }
1004         }
1005         CL_LinkNetworkEntity(&cl.viewent);
1006 }
1007
1008 static void CL_RelinkEffects(void)
1009 {
1010         int i, intframe;
1011         cl_effect_t *e;
1012         entity_t *ent;
1013         float frame;
1014
1015         for (i = 0, e = cl_effects;i < cl_max_effects;i++, e++)
1016         {
1017                 if (e->active)
1018                 {
1019                         frame = (cl.time - e->starttime) * e->framerate + e->startframe;
1020                         intframe = frame;
1021                         if (intframe < 0 || intframe >= e->endframe)
1022                         {
1023                                 memset(e, 0, sizeof(*e));
1024                                 continue;
1025                         }
1026
1027                         if (intframe != e->frame)
1028                         {
1029                                 e->frame = intframe;
1030                                 e->frame1time = e->frame2time;
1031                                 e->frame2time = cl.time;
1032                         }
1033
1034                         // if we're drawing effects, get a new temp entity
1035                         // (NewTempEntity adds it to the render entities list for us)
1036                         if (r_draweffects.integer && (ent = CL_NewTempEntity()))
1037                         {
1038                                 // interpolation stuff
1039                                 ent->render.frame1 = intframe;
1040                                 ent->render.frame2 = intframe + 1;
1041                                 if (ent->render.frame2 >= e->endframe)
1042                                         ent->render.frame2 = -1; // disappear
1043                                 ent->render.framelerp = frame - intframe;
1044                                 ent->render.frame1time = e->frame1time;
1045                                 ent->render.frame2time = e->frame2time;
1046
1047                                 // normal stuff
1048                                 ent->render.model = cl.model_precache[e->modelindex];
1049                                 ent->render.frame = ent->render.frame2;
1050                                 ent->render.colormap = -1; // no special coloring
1051                                 ent->render.alpha = 1;
1052                                 VectorSet(ent->render.colormod, 1, 1, 1);
1053
1054                                 Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1);
1055                                 Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
1056                                 R_LerpAnimation(&ent->render);
1057                                 CL_BoundingBoxForEntity(&ent->render);
1058                         }
1059                 }
1060         }
1061 }
1062
1063 void CL_RelinkBeams(void)
1064 {
1065         int i;
1066         beam_t *b;
1067         vec3_t dist, org;
1068         float d;
1069         entity_t *ent;
1070         float yaw, pitch;
1071         float forward;
1072         matrix4x4_t tempmatrix;
1073
1074         for (i = 0, b = cl_beams;i < cl_max_beams;i++, b++)
1075         {
1076                 if (!b->model || b->endtime < cl.time)
1077                         continue;
1078
1079                 // if coming from the player, update the start position
1080                 //if (b->entity == cl.viewentity)
1081                 //      VectorCopy (cl_entities[cl.viewentity].render.origin, b->start);
1082                 if (cl_beams_relative.integer && b->entity == cl.viewentity && b->entity && cl_entities[b->entity].state_current.active && b->relativestartvalid)
1083                 {
1084                         entity_state_t *p = &cl_entities[b->entity].state_previous;
1085                         //entity_state_t *c = &cl_entities[b->entity].state_current;
1086                         entity_render_t *r = &cl_entities[b->entity].render;
1087                         matrix4x4_t matrix, imatrix;
1088                         if (b->relativestartvalid == 2)
1089                         {
1090                                 // not really valid yet, we need to get the orientation now
1091                                 // (ParseBeam flagged this because it is received before
1092                                 //  entities are received, by now they have been received)
1093                                 // note: because players create lightning in their think
1094                                 // function (which occurs before movement), they actually
1095                                 // have some lag in it's location, so compare to the
1096                                 // previous player state, not the latest
1097                                 if (b->entity == cl.viewentity)
1098                                         Matrix4x4_CreateFromQuakeEntity(&matrix, p->origin[0], p->origin[1], p->origin[2] + 16, cl.viewangles[0], cl.viewangles[1], cl.viewangles[2], 1);
1099                                 else
1100                                         Matrix4x4_CreateFromQuakeEntity(&matrix, p->origin[0], p->origin[1], p->origin[2] + 16, p->angles[0], p->angles[1], p->angles[2], 1);
1101                                 Matrix4x4_Invert_Simple(&imatrix, &matrix);
1102                                 Matrix4x4_Transform(&imatrix, b->start, b->relativestart);
1103                                 Matrix4x4_Transform(&imatrix, b->end, b->relativeend);
1104                                 b->relativestartvalid = 1;
1105                         }
1106                         else
1107                         {
1108                                 if (b->entity == cl.viewentity)
1109                                         Matrix4x4_CreateFromQuakeEntity(&matrix, r->origin[0], r->origin[1], r->origin[2] + 16, cl.viewangles[0], cl.viewangles[1], cl.viewangles[2], 1);
1110                                 else
1111                                         Matrix4x4_CreateFromQuakeEntity(&matrix, r->origin[0], r->origin[1], r->origin[2] + 16, r->angles[0], r->angles[1], r->angles[2], 1);
1112                                 Matrix4x4_Transform(&matrix, b->relativestart, b->start);
1113                                 Matrix4x4_Transform(&matrix, b->relativeend, b->end);
1114                         }
1115                 }
1116
1117                 if (b->lightning)
1118                 {
1119                         if (cl_beams_lightatend.integer)
1120                         {
1121                                 // FIXME: create a matrix from the beam start/end orientation
1122                                 Matrix4x4_CreateTranslate(&tempmatrix, b->end[0], b->end[1], b->end[2]);
1123                                 CL_AllocDlight (NULL, &tempmatrix, 200, 0.3, 0.7, 1, 0, 0, 0, -1, true, 1, 0.25, 1, 0, 0, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1124                         }
1125                         if (cl_beams_polygons.integer)
1126                                 continue;
1127                 }
1128
1129                 // calculate pitch and yaw
1130                 VectorSubtract (b->end, b->start, dist);
1131
1132                 if (dist[1] == 0 && dist[0] == 0)
1133                 {
1134                         yaw = 0;
1135                         if (dist[2] > 0)
1136                                 pitch = 90;
1137                         else
1138                                 pitch = 270;
1139                 }
1140                 else
1141                 {
1142                         yaw = (int) (atan2(dist[1], dist[0]) * 180 / M_PI);
1143                         if (yaw < 0)
1144                                 yaw += 360;
1145
1146                         forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]);
1147                         pitch = (int) (atan2(dist[2], forward) * 180 / M_PI);
1148                         if (pitch < 0)
1149                                 pitch += 360;
1150                 }
1151
1152                 // add new entities for the lightning
1153                 VectorCopy (b->start, org);
1154                 d = VectorNormalizeLength(dist);
1155                 while (d > 0)
1156                 {
1157                         ent = CL_NewTempEntity ();
1158                         if (!ent)
1159                                 return;
1160                         //VectorCopy (org, ent->render.origin);
1161                         ent->render.model = b->model;
1162                         //ent->render.effects = EF_FULLBRIGHT;
1163                         //ent->render.angles[0] = pitch;
1164                         //ent->render.angles[1] = yaw;
1165                         //ent->render.angles[2] = rand()%360;
1166                         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1);
1167                         Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
1168                         R_LerpAnimation(&ent->render);
1169                         CL_BoundingBoxForEntity(&ent->render);
1170                         VectorMA(org, 30, dist, org);
1171                         d -= 30;
1172                 }
1173         }
1174 }
1175
1176 void CL_LerpPlayer(float frac)
1177 {
1178         int i;
1179         float d;
1180
1181         cl.viewzoom = cl.mviewzoom[1] + frac * (cl.mviewzoom[0] - cl.mviewzoom[1]);
1182         for (i = 0;i < 3;i++)
1183         {
1184                 cl.punchangle[i] = cl.mpunchangle[1][i] + frac * (cl.mpunchangle[0][i] - cl.mpunchangle[1][i]);
1185                 cl.punchvector[i] = cl.mpunchvector[1][i] + frac * (cl.mpunchvector[0][i] - cl.mpunchvector[1][i]);
1186                 cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
1187         }
1188
1189         if (cls.demoplayback)
1190         {
1191                 // interpolate the angles
1192                 for (i = 0;i < 3;i++)
1193                 {
1194                         d = cl.mviewangles[0][i] - cl.mviewangles[1][i];
1195                         if (d > 180)
1196                                 d -= 360;
1197                         else if (d < -180)
1198                                 d += 360;
1199                         cl.viewangles[i] = cl.mviewangles[1][i] + frac * d;
1200                 }
1201         }
1202 }
1203
1204 /*
1205 ===============
1206 CL_ReadFromServer
1207
1208 Read all incoming data from the server
1209 ===============
1210 */
1211 int CL_ReadFromServer(void)
1212 {
1213         CL_ReadDemoMessage();
1214
1215         r_refdef.time = cl.time;
1216         r_refdef.extraupdate = !r_speeds.integer;
1217         r_refdef.numentities = 0;
1218         cl_num_brushmodel_entities = 0;
1219
1220         if (cls.state == ca_connected && cls.signon == SIGNONS)
1221         {
1222                 // prepare for a new frame
1223                 CL_LerpPlayer(CL_LerpPoint());
1224                 CL_DecayLights();
1225                 CL_ClearTempEntities();
1226                 V_DriftPitch();
1227                 V_FadeViewFlashs();
1228
1229                 // relink network entities (note: this sets up the view!)
1230                 CL_RelinkNetworkEntities();
1231
1232                 // move particles
1233                 CL_MoveParticles();
1234                 R_MoveExplosions();
1235
1236                 // link stuff
1237                 CL_RelinkWorld();
1238                 CL_RelinkStaticEntities();
1239                 CL_RelinkBeams();
1240                 CL_RelinkEffects();
1241
1242                 // run cgame code (which can add more entities)
1243                 CL_CGVM_Frame();
1244
1245                 // update view blend
1246                 V_CalcViewBlend();
1247         }
1248
1249         return 0;
1250 }
1251
1252 /*
1253 =================
1254 CL_SendCmd
1255 =================
1256 */
1257 void CL_SendCmd(void)
1258 {
1259         if (cls.signon == SIGNONS)
1260                 CL_SendMove();
1261
1262         if (cls.demoplayback)
1263         {
1264                 SZ_Clear(&cls.message);
1265                 return;
1266         }
1267
1268         // send the reliable message (forwarded commands) if there is one
1269         if (cls.message.cursize && NetConn_CanSendMessage(cls.netcon))
1270         {
1271                 if (developer.integer)
1272                 {
1273                         Con_Print("CL_SendCmd: sending reliable message:\n");
1274                         SZ_HexDumpToConsole(&cls.message);
1275                 }
1276                 if (NetConn_SendReliableMessage(cls.netcon, &cls.message) == -1)
1277                         Host_Error("CL_WriteToServer: lost server connection");
1278                 SZ_Clear(&cls.message);
1279         }
1280 }
1281
1282 // LordHavoc: pausedemo command
1283 static void CL_PauseDemo_f (void)
1284 {
1285         cls.demopaused = !cls.demopaused;
1286         if (cls.demopaused)
1287                 Con_Print("Demo paused\n");
1288         else
1289                 Con_Print("Demo unpaused\n");
1290 }
1291
1292 /*
1293 ======================
1294 CL_Fog_f
1295 ======================
1296 */
1297 static void CL_Fog_f (void)
1298 {
1299         if (Cmd_Argc () == 1)
1300         {
1301                 Con_Printf("\"fog\" is \"%f %f %f %f\"\n", fog_density, fog_red, fog_green, fog_blue);
1302                 return;
1303         }
1304         fog_density = atof(Cmd_Argv(1));
1305         fog_red = atof(Cmd_Argv(2));
1306         fog_green = atof(Cmd_Argv(3));
1307         fog_blue = atof(Cmd_Argv(4));
1308 }
1309
1310 /*
1311 ====================
1312 CL_TimeRefresh_f
1313
1314 For program optimization
1315 ====================
1316 */
1317 static void CL_TimeRefresh_f (void)
1318 {
1319         int i;
1320         float timestart, timedelta, oldangles[3];
1321
1322         r_refdef.extraupdate = false;
1323         VectorCopy(cl.viewangles, oldangles);
1324         VectorClear(cl.viewangles);
1325
1326         timestart = Sys_DoubleTime();
1327         for (i = 0;i < 128;i++)
1328         {
1329                 Matrix4x4_CreateFromQuakeEntity(&r_refdef.viewentitymatrix, r_vieworigin[0], r_vieworigin[1], r_vieworigin[2], 0, i / 128.0 * 360.0, 0, 1);
1330                 CL_UpdateScreen();
1331         }
1332         timedelta = Sys_DoubleTime() - timestart;
1333
1334         VectorCopy(oldangles, cl.viewangles);
1335         Con_Printf("%f seconds (%f fps)\n", timedelta, 128/timedelta);
1336 }
1337
1338 /*
1339 ===========
1340 CL_Shutdown
1341 ===========
1342 */
1343 void CL_Shutdown (void)
1344 {
1345         CL_CGVM_Shutdown();
1346         CL_Particles_Shutdown();
1347         CL_Parse_Shutdown();
1348
1349         Mem_FreePool (&cl_mempool);
1350 }
1351
1352 /*
1353 =================
1354 CL_Init
1355 =================
1356 */
1357 void CL_Init (void)
1358 {
1359         cl_mempool = Mem_AllocPool("client", 0, NULL);
1360
1361         memset(&r_refdef, 0, sizeof(r_refdef));
1362         // max entities sent to renderer per frame
1363         r_refdef.maxentities = MAX_EDICTS + 256 + 512;
1364         r_refdef.entities = Mem_Alloc(cl_mempool, sizeof(entity_render_t *) * r_refdef.maxentities);
1365         // 256k drawqueue buffer
1366         r_refdef.maxdrawqueuesize = 256 * 1024;
1367         r_refdef.drawqueue = Mem_Alloc(cl_mempool, r_refdef.maxdrawqueuesize);
1368
1369         cls.message.data = cls.message_buf;
1370         cls.message.maxsize = sizeof(cls.message_buf);
1371         cls.message.cursize = 0;
1372
1373         CL_InitInput ();
1374
1375 //
1376 // register our commands
1377 //
1378         Cvar_RegisterVariable (&cl_upspeed);
1379         Cvar_RegisterVariable (&cl_forwardspeed);
1380         Cvar_RegisterVariable (&cl_backspeed);
1381         Cvar_RegisterVariable (&cl_sidespeed);
1382         Cvar_RegisterVariable (&cl_movespeedkey);
1383         Cvar_RegisterVariable (&cl_yawspeed);
1384         Cvar_RegisterVariable (&cl_pitchspeed);
1385         Cvar_RegisterVariable (&cl_anglespeedkey);
1386         Cvar_RegisterVariable (&cl_shownet);
1387         Cvar_RegisterVariable (&cl_nolerp);
1388         Cvar_RegisterVariable (&lookspring);
1389         Cvar_RegisterVariable (&lookstrafe);
1390         Cvar_RegisterVariable (&sensitivity);
1391         Cvar_RegisterVariable (&freelook);
1392
1393         Cvar_RegisterVariable (&m_pitch);
1394         Cvar_RegisterVariable (&m_yaw);
1395         Cvar_RegisterVariable (&m_forward);
1396         Cvar_RegisterVariable (&m_side);
1397
1398         Cvar_RegisterVariable (&cl_itembobspeed);
1399         Cvar_RegisterVariable (&cl_itembobheight);
1400
1401         Cmd_AddCommand ("entities", CL_PrintEntities_f);
1402         Cmd_AddCommand ("disconnect", CL_Disconnect_f);
1403         Cmd_AddCommand ("record", CL_Record_f);
1404         Cmd_AddCommand ("stop", CL_Stop_f);
1405         Cmd_AddCommand ("playdemo", CL_PlayDemo_f);
1406         Cmd_AddCommand ("timedemo", CL_TimeDemo_f);
1407
1408         Cmd_AddCommand ("fog", CL_Fog_f);
1409
1410         // LordHavoc: added pausedemo
1411         Cmd_AddCommand ("pausedemo", CL_PauseDemo_f);
1412
1413         Cvar_RegisterVariable(&r_draweffects);
1414         Cvar_RegisterVariable(&cl_explosions_alpha_start);
1415         Cvar_RegisterVariable(&cl_explosions_alpha_end);
1416         Cvar_RegisterVariable(&cl_explosions_size_start);
1417         Cvar_RegisterVariable(&cl_explosions_size_end);
1418         Cvar_RegisterVariable(&cl_explosions_lifetime);
1419         Cvar_RegisterVariable(&cl_stainmaps);
1420         Cvar_RegisterVariable(&cl_stainmaps_clearonload);
1421         Cvar_RegisterVariable(&cl_beams_polygons);
1422         Cvar_RegisterVariable(&cl_beams_relative);
1423         Cvar_RegisterVariable(&cl_beams_lightatend);
1424         Cvar_RegisterVariable(&cl_noplayershadow);
1425
1426         Cvar_RegisterVariable(&cl_prydoncursor);
1427
1428         Cmd_AddCommand("timerefresh", CL_TimeRefresh_f);
1429
1430         CL_Parse_Init();
1431         CL_Particles_Init();
1432         CL_Screen_Init();
1433         CL_CGVM_Init();
1434
1435         CL_Video_Init();
1436 }
1437
1438
1439