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