make csqc render entities persistent (except the temp ones created by a
[xonotic/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_gecko.h"
25 #include "cl_video.h"
26 #include "image.h"
27 #include "csprogs.h"
28 #include "r_shadow.h"
29 #include "libcurl.h"
30 #include "snd_main.h"
31
32 // we need to declare some mouse variables here, because the menu system
33 // references them even when on a unix system.
34
35 cvar_t csqc_progname = {0, "csqc_progname","csprogs.dat","name of csprogs.dat file to load"};
36 cvar_t csqc_progcrc = {CVAR_READONLY, "csqc_progcrc","-1","CRC of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"};
37 cvar_t csqc_progsize = {CVAR_READONLY, "csqc_progsize","-1","file size of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"};
38
39 cvar_t cl_shownet = {0, "cl_shownet","0","1 = print packet size, 2 = print packet message list"};
40 cvar_t cl_nolerp = {0, "cl_nolerp", "0","network update smoothing"};
41
42 cvar_t cl_itembobheight = {0, "cl_itembobheight", "0","how much items bob up and down (try 8)"};
43 cvar_t cl_itembobspeed = {0, "cl_itembobspeed", "0.5","how frequently items bob up and down"};
44
45 cvar_t lookspring = {CVAR_SAVE, "lookspring","0","returns pitch to level with the floor when no longer holding a pitch key"};
46 cvar_t lookstrafe = {CVAR_SAVE, "lookstrafe","0","move instead of turning"};
47 cvar_t sensitivity = {CVAR_SAVE, "sensitivity","3","mouse speed multiplier"};
48
49 cvar_t m_pitch = {CVAR_SAVE, "m_pitch","0.022","mouse pitch speed multiplier"};
50 cvar_t m_yaw = {CVAR_SAVE, "m_yaw","0.022","mouse yaw speed multiplier"};
51 cvar_t m_forward = {CVAR_SAVE, "m_forward","1","mouse forward speed multiplier"};
52 cvar_t m_side = {CVAR_SAVE, "m_side","0.8","mouse side speed multiplier"};
53
54 cvar_t freelook = {CVAR_SAVE, "freelook", "1","mouse controls pitch instead of forward/back"};
55
56 cvar_t cl_autodemo = {CVAR_SAVE, "cl_autodemo", "0", "records every game played, using the date/time and map name to name the demo file" };
57 cvar_t cl_autodemo_nameformat = {CVAR_SAVE, "cl_autodemo_nameformat", "autodemos/%Y-%m-%d_%H-%M", "The format of the cl_autodemo filename, followed by the map name (the date is encoded using strftime escapes)" };
58
59 cvar_t r_draweffects = {0, "r_draweffects", "1","renders temporary sprite effects"};
60
61 cvar_t cl_explosions_alpha_start = {CVAR_SAVE, "cl_explosions_alpha_start", "1.5","starting alpha of an explosion shell"};
62 cvar_t cl_explosions_alpha_end = {CVAR_SAVE, "cl_explosions_alpha_end", "0","end alpha of an explosion shell (just before it disappears)"};
63 cvar_t cl_explosions_size_start = {CVAR_SAVE, "cl_explosions_size_start", "16","starting size of an explosion shell"};
64 cvar_t cl_explosions_size_end = {CVAR_SAVE, "cl_explosions_size_end", "128","ending alpha of an explosion shell (just before it disappears)"};
65 cvar_t cl_explosions_lifetime = {CVAR_SAVE, "cl_explosions_lifetime", "0.5","how long an explosion shell lasts"};
66
67 cvar_t cl_stainmaps = {CVAR_SAVE, "cl_stainmaps", "0","stains lightmaps, much faster than decals but blurred"};
68 cvar_t cl_stainmaps_clearonload = {CVAR_SAVE, "cl_stainmaps_clearonload", "1","clear stainmaps on map restart"};
69
70 cvar_t cl_beams_polygons = {CVAR_SAVE, "cl_beams_polygons", "1","use beam polygons instead of models"};
71 cvar_t cl_beams_quakepositionhack = {CVAR_SAVE, "cl_beams_quakepositionhack", "1", "makes your lightning gun appear to fire from your waist (as in Quake and QuakeWorld)"};
72 cvar_t cl_beams_instantaimhack = {CVAR_SAVE, "cl_beams_instantaimhack", "0", "makes your lightning gun aiming update instantly"};
73 cvar_t cl_beams_lightatend = {CVAR_SAVE, "cl_beams_lightatend", "0", "make a light at the end of the beam"};
74
75 cvar_t cl_deathfade = {CVAR_SAVE, "cl_deathfade", "0", "fade screen to dark red when dead, value = how fast the fade is"};
76
77 cvar_t cl_noplayershadow = {CVAR_SAVE, "cl_noplayershadow", "0","hide player shadow"};
78
79 cvar_t cl_dlights_decayradius = {CVAR_SAVE, "cl_dlights_decayradius", "1", "reduces size of light flashes over time"};
80 cvar_t cl_dlights_decaybrightness = {CVAR_SAVE, "cl_dlights_decaybrightness", "1", "reduces brightness of light flashes over time"};
81
82 cvar_t qport = {0, "qport", "0", "identification key for playing on qw servers (allows you to maintain a connection to a quakeworld server even if your port changes)"};
83
84 cvar_t cl_prydoncursor = {0, "cl_prydoncursor", "0", "enables a mouse pointer which is able to click on entities in the world, useful for point and click mods, see PRYDON_CLIENTCURSOR extension in dpextensions.qc"};
85
86 cvar_t cl_deathnoviewmodel = {0, "cl_deathnoviewmodel", "1", "hides gun model when dead"};
87
88 cvar_t cl_locs_enable = {CVAR_SAVE, "locs_enable", "1", "enables replacement of certain % codes in chat messages: %l (location), %d (last death location), %h (health), %a (armor), %x (rockets), %c (cells), %r (rocket launcher status), %p (powerup status), %w (weapon status), %t (current time in level)"};
89 cvar_t cl_locs_show = {0, "locs_show", "0", "shows defined locations for editing purposes"};
90
91 extern cvar_t r_equalize_entities_fullbright;
92
93 client_static_t cls;
94 client_state_t  cl;
95
96 /*
97 =====================
98 CL_ClearState
99
100 =====================
101 */
102 void CL_VM_ShutDown (void);
103 void CL_ClearState(void)
104 {
105         int i;
106         entity_t *ent;
107
108         CL_VM_ShutDown();
109
110 // wipe the entire cl structure
111         Mem_EmptyPool(cls.levelmempool);
112         memset (&cl, 0, sizeof(cl));
113
114         S_StopAllSounds();
115
116         // reset the view zoom interpolation
117         cl.mviewzoom[0] = cl.mviewzoom[1] = 1;
118         cl.sensitivityscale = 1.0f;
119
120         // enable rendering of the world and such
121         cl.csqc_vidvars.drawworld = true;
122         cl.csqc_vidvars.drawenginesbar = true;
123         cl.csqc_vidvars.drawcrosshair = true;
124
125         // set up the float version of the stats array for easier access to float stats
126         cl.statsf = (float *)cl.stats;
127
128         cl.num_entities = 0;
129         cl.num_static_entities = 0;
130         cl.num_brushmodel_entities = 0;
131
132         // tweak these if the game runs out
133         cl.max_csqcrenderentities = 0;
134         cl.max_entities = 256;
135         cl.max_static_entities = 256;
136         cl.max_effects = 256;
137         cl.max_beams = 256;
138         cl.max_dlights = MAX_DLIGHTS;
139         cl.max_lightstyle = MAX_LIGHTSTYLES;
140         cl.max_brushmodel_entities = MAX_EDICTS;
141         cl.max_particles = 8192; // grows dynamically
142         cl.max_decals = 2048; // grows dynamically
143         cl.max_showlmps = 0;
144
145         cl.num_dlights = 0;
146         cl.num_effects = 0;
147         cl.num_beams = 0;
148
149         cl.csqcrenderentities = NULL;
150         cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
151         cl.entities_active = (unsigned char *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(unsigned char));
152         cl.static_entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_static_entities * sizeof(entity_t));
153         cl.effects = (cl_effect_t *)Mem_Alloc(cls.levelmempool, cl.max_effects * sizeof(cl_effect_t));
154         cl.beams = (beam_t *)Mem_Alloc(cls.levelmempool, cl.max_beams * sizeof(beam_t));
155         cl.dlights = (dlight_t *)Mem_Alloc(cls.levelmempool, cl.max_dlights * sizeof(dlight_t));
156         cl.lightstyle = (lightstyle_t *)Mem_Alloc(cls.levelmempool, cl.max_lightstyle * sizeof(lightstyle_t));
157         cl.brushmodel_entities = (int *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(int));
158         cl.particles = (particle_t *) Mem_Alloc(cls.levelmempool, cl.max_particles * sizeof(particle_t));
159         cl.decals = (decal_t *) Mem_Alloc(cls.levelmempool, cl.max_decals * sizeof(decal_t));
160         cl.showlmps = NULL;
161
162         // LordHavoc: have to set up the baseline info for alpha and other stuff
163         for (i = 0;i < cl.max_entities;i++)
164         {
165                 cl.entities[i].state_baseline = defaultstate;
166                 cl.entities[i].state_previous = defaultstate;
167                 cl.entities[i].state_current = defaultstate;
168         }
169
170         if (gamemode == GAME_NEXUIZ)
171         {
172                 VectorSet(cl.playerstandmins, -16, -16, -24);
173                 VectorSet(cl.playerstandmaxs, 16, 16, 45);
174                 VectorSet(cl.playercrouchmins, -16, -16, -24);
175                 VectorSet(cl.playercrouchmaxs, 16, 16, 25);
176         }
177         else
178         {
179                 VectorSet(cl.playerstandmins, -16, -16, -24);
180                 VectorSet(cl.playerstandmaxs, 16, 16, 24);
181                 VectorSet(cl.playercrouchmins, -16, -16, -24);
182                 VectorSet(cl.playercrouchmaxs, 16, 16, 24);
183         }
184
185         // disable until we get textures for it
186         R_ResetSkyBox();
187
188         ent = &cl.entities[0];
189         // entire entity array was cleared, so just fill in a few fields
190         ent->state_current.active = true;
191         ent->render.model = cl.worldmodel = NULL; // no world model yet
192         ent->render.alpha = 1;
193         ent->render.flags = RENDER_SHADOW | RENDER_LIGHT;
194         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, 0, 0, 0, 0, 0, 0, 1);
195         ent->render.allowdecals = true;
196         CL_UpdateRenderEntity(&ent->render);
197
198         // noclip is turned off at start
199         noclip_anglehack = false;
200
201         // mark all frames invalid for delta
202         memset(cl.qw_deltasequence, -1, sizeof(cl.qw_deltasequence));
203
204         // set bestweapon data back to Quake data
205         IN_BestWeapon_ResetData();
206
207         CL_Screen_NewMap();
208 }
209
210 void CL_SetInfo(const char *key, const char *value, qboolean send, qboolean allowstarkey, qboolean allowmodel, qboolean quiet)
211 {
212         int i;
213         qboolean fail = false;
214         if (!allowstarkey && key[0] == '*')
215                 fail = true;
216         if (!allowmodel && (!strcasecmp(key, "pmodel") || !strcasecmp(key, "emodel")))
217                 fail = true;
218         for (i = 0;key[i];i++)
219                 if (ISWHITESPACE(key[i]) || key[i] == '\"')
220                         fail = true;
221         for (i = 0;value[i];i++)
222                 if (value[i] == '\r' || value[i] == '\n' || value[i] == '\"')
223                         fail = true;
224         if (fail)
225         {
226                 if (!quiet)
227                         Con_Printf("Can't setinfo \"%s\" \"%s\"\n", key, value);
228                 return;
229         }
230         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), key, value);
231         if (cls.state == ca_connected && cls.netcon)
232         {
233                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
234                 {
235                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
236                         MSG_WriteString(&cls.netcon->message, va("setinfo \"%s\" \"%s\"", key, value));
237                 }
238                 else if (!strcasecmp(key, "name"))
239                 {
240                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
241                         MSG_WriteString(&cls.netcon->message, va("name \"%s\"", value));
242                 }
243                 else if (!strcasecmp(key, "playermodel"))
244                 {
245                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
246                         MSG_WriteString(&cls.netcon->message, va("playermodel \"%s\"", value));
247                 }
248                 else if (!strcasecmp(key, "playerskin"))
249                 {
250                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
251                         MSG_WriteString(&cls.netcon->message, va("playerskin \"%s\"", value));
252                 }
253                 else if (!strcasecmp(key, "topcolor"))
254                 {
255                         // don't send anything, the combined color code will be updated manually
256                 }
257                 else if (!strcasecmp(key, "bottomcolor"))
258                 {
259                         // don't send anything, the combined color code will be updated manually
260                 }
261                 else if (!strcasecmp(key, "rate"))
262                 {
263                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
264                         MSG_WriteString(&cls.netcon->message, va("rate \"%s\"", value));
265                 }
266         }
267 }
268
269 void CL_ExpandEntities(int num)
270 {
271         int i, oldmaxentities;
272         entity_t *oldentities;
273         if (num >= cl.max_entities)
274         {
275                 if (!cl.entities)
276                         Sys_Error("CL_ExpandEntities: cl.entities not initialized");
277                 if (num >= MAX_EDICTS)
278                         Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS);
279                 oldmaxentities = cl.max_entities;
280                 oldentities = cl.entities;
281                 cl.max_entities = (num & ~255) + 256;
282                 cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
283                 memcpy(cl.entities, oldentities, oldmaxentities * sizeof(entity_t));
284                 Mem_Free(oldentities);
285                 for (i = oldmaxentities;i < cl.max_entities;i++)
286                 {
287                         cl.entities[i].state_baseline = defaultstate;
288                         cl.entities[i].state_previous = defaultstate;
289                         cl.entities[i].state_current = defaultstate;
290                 }
291         }
292 }
293
294 void CL_ExpandCSQCRenderEntities(int num)
295 {
296         int oldmaxcsqcrenderentities;
297         entity_render_t *oldcsqcrenderentities;
298         if (num >= cl.max_csqcrenderentities)
299         {
300                 if (num >= MAX_EDICTS)
301                         Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS);
302                 oldmaxcsqcrenderentities = cl.max_csqcrenderentities;
303                 oldcsqcrenderentities = cl.csqcrenderentities;
304                 cl.max_csqcrenderentities = (num & ~255) + 256;
305                 cl.csqcrenderentities = (entity_render_t *)Mem_Alloc(cls.levelmempool, cl.max_csqcrenderentities * sizeof(entity_render_t));
306                 if (oldcsqcrenderentities)
307                 {
308                         memcpy(cl.csqcrenderentities, oldcsqcrenderentities, oldmaxcsqcrenderentities * sizeof(entity_render_t));
309                         Mem_Free(oldcsqcrenderentities);
310                 }
311         }
312 }
313
314 /*
315 =====================
316 CL_Disconnect
317
318 Sends a disconnect message to the server
319 This is also called on Host_Error, so it shouldn't cause any errors
320 =====================
321 */
322 void CL_Disconnect(void)
323 {
324         if (cls.state == ca_dedicated)
325                 return;
326
327         if (COM_CheckParm("-profilegameonly"))
328                 Sys_AllowProfiling(false);
329
330         Curl_Clear_forthismap();
331
332         Con_DPrintf("CL_Disconnect\n");
333
334     Cvar_SetValueQuick(&csqc_progcrc, -1);
335         Cvar_SetValueQuick(&csqc_progsize, -1);
336         CL_VM_ShutDown();
337 // stop sounds (especially looping!)
338         S_StopAllSounds ();
339
340         cl.parsingtextexpectingpingforscores = 0; // just in case no reply has come yet
341
342         // clear contents blends
343         cl.cshifts[0].percent = 0;
344         cl.cshifts[1].percent = 0;
345         cl.cshifts[2].percent = 0;
346         cl.cshifts[3].percent = 0;
347
348         cl.worldmodel = NULL;
349
350         CL_Parse_ErrorCleanUp();
351
352         if (cls.demoplayback)
353                 CL_StopPlayback();
354         else if (cls.netcon)
355         {
356                 sizebuf_t buf;
357                 unsigned char bufdata[8];
358                 if (cls.demorecording)
359                         CL_Stop_f();
360
361                 // send disconnect message 3 times to improve chances of server
362                 // receiving it (but it still fails sometimes)
363                 memset(&buf, 0, sizeof(buf));
364                 buf.data = bufdata;
365                 buf.maxsize = sizeof(bufdata);
366                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
367                 {
368                         Con_DPrint("Sending drop command\n");
369                         MSG_WriteByte(&buf, qw_clc_stringcmd);
370                         MSG_WriteString(&buf, "drop");
371                 }
372                 else
373                 {
374                         Con_DPrint("Sending clc_disconnect\n");
375                         MSG_WriteByte(&buf, clc_disconnect);
376                 }
377                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, false);
378                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, false);
379                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, false);
380                 NetConn_Close(cls.netcon);
381                 cls.netcon = NULL;
382         }
383         cls.state = ca_disconnected;
384
385         cls.demoplayback = cls.timedemo = false;
386         cls.signon = 0;
387 }
388
389 void CL_Disconnect_f(void)
390 {
391         CL_Disconnect ();
392         if (sv.active)
393                 Host_ShutdownServer ();
394 }
395
396
397
398
399 /*
400 =====================
401 CL_EstablishConnection
402
403 Host should be either "local" or a net address
404 =====================
405 */
406 void CL_EstablishConnection(const char *host)
407 {
408         if (cls.state == ca_dedicated)
409                 return;
410
411         // clear menu's connect error message
412         M_Update_Return_Reason("");
413         cls.demonum = -1;
414
415         // stop demo loop in case this fails
416         if (cls.demoplayback)
417                 CL_StopPlayback();
418
419         // if downloads are running, cancel their finishing action
420         Curl_Clear_forthismap();
421
422         // make sure the client ports are open before attempting to connect
423         NetConn_UpdateSockets();
424
425         // run a network frame
426         //NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
427
428         if (LHNETADDRESS_FromString(&cls.connect_address, host, 26000) && (cls.connect_mysocket = NetConn_ChooseClientSocketForAddress(&cls.connect_address)))
429         {
430                 cls.connect_trying = true;
431                 cls.connect_remainingtries = 3;
432                 cls.connect_nextsendtime = 0;
433                 M_Update_Return_Reason("Trying to connect...");
434                 // run several network frames to jump into the game quickly
435                 //if (sv.active)
436                 //{
437                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
438                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
439                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
440                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
441                 //}
442         }
443         else
444         {
445                 Con_Print("Unable to find a suitable network socket to connect to server.\n");
446                 M_Update_Return_Reason("No network");
447         }
448 }
449
450 /*
451 ==============
452 CL_PrintEntities_f
453 ==============
454 */
455 static void CL_PrintEntities_f(void)
456 {
457         entity_t *ent;
458         int i;
459
460         for (i = 0, ent = cl.entities;i < cl.num_entities;i++, ent++)
461         {
462                 const char* modelname;
463
464                 if (!ent->state_current.active)
465                         continue;
466
467                 if (ent->render.model)
468                         modelname = ent->render.model->name;
469                 else
470                         modelname = "--no model--";
471                 Con_Printf("%3i: %-25s:%4i (%5i %5i %5i) [%3i %3i %3i] %4.2f %5.3f\n", i, modelname, ent->render.framegroupblend[0].frame, (int) ent->state_current.origin[0], (int) ent->state_current.origin[1], (int) ent->state_current.origin[2], (int) ent->state_current.angles[0] % 360, (int) ent->state_current.angles[1] % 360, (int) ent->state_current.angles[2] % 360, ent->render.scale, ent->render.alpha);
472         }
473 }
474
475 /*
476 ===============
477 CL_ModelIndexList_f
478
479 List information on all models in the client modelindex
480 ===============
481 */
482 static void CL_ModelIndexList_f(void)
483 {
484         int i = 1;
485
486         // Print Header
487         Con_Printf("%3s: %-30s %-8s %-8s\n", "ID", "Name", "Type", "Triangles");
488
489         while(cl.model_precache[i] && i != MAX_MODELS)
490         { // Valid Model
491                 if(cl.model_precache[i]->loaded || i == 1)
492                         Con_Printf("%3i: %-30s %-8s %-10i\n", i, cl.model_precache[i]->name, cl.model_precache[i]->modeldatatypestring, cl.model_precache[i]->surfmesh.num_triangles);
493                 else
494                         Con_Printf("%3i: %-30s %-30s\n", i, cl.model_precache[i]->name, "--no local model found--");
495                 i++;
496         }
497 }
498
499 /*
500 ===============
501 CL_SoundIndexList_f
502
503 List all sounds in the client soundindex
504 ===============
505 */
506 static void CL_SoundIndexList_f(void)
507 {
508         int i = 1;
509
510         while(cl.sound_precache[i] && i != MAX_SOUNDS)
511         { // Valid Sound
512                 Con_Printf("%i : %s\n", i, cl.sound_precache[i]->name);
513                 i++;
514         }
515 }
516
517 /*
518 ===============
519 CL_UpdateRenderEntity
520
521 Updates inversematrix, animation interpolation factors, scale, and mins/maxs
522 ===============
523 */
524 void CL_UpdateRenderEntity(entity_render_t *ent)
525 {
526         vec3_t org;
527         vec_t scale;
528         dp_model_t *model = ent->model;
529         // update the inverse matrix for the renderer
530         Matrix4x4_Invert_Simple(&ent->inversematrix, &ent->matrix);
531         // update the animation blend state
532         R_LerpAnimation(ent);
533         // we need the matrix origin to center the box
534         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
535         // update entity->render.scale because the renderer needs it
536         ent->scale = scale = Matrix4x4_ScaleFromMatrix(&ent->matrix);
537         if (model)
538         {
539                 // NOTE: this directly extracts vector components from the matrix, which relies on the matrix orientation!
540 #ifdef MATRIX4x4_OPENGLORIENTATION
541                 if (ent->matrix.m[0][2] != 0 || ent->matrix.m[1][2] != 0)
542 #else
543                 if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0)
544 #endif
545                 {
546                         // pitch or roll
547                         VectorMA(org, scale, model->rotatedmins, ent->mins);
548                         VectorMA(org, scale, model->rotatedmaxs, ent->maxs);
549                 }
550 #ifdef MATRIX4x4_OPENGLORIENTATION
551                 else if (ent->matrix.m[1][0] != 0 || ent->matrix.m[0][1] != 0)
552 #else
553                 else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0)
554 #endif
555                 {
556                         // yaw
557                         VectorMA(org, scale, model->yawmins, ent->mins);
558                         VectorMA(org, scale, model->yawmaxs, ent->maxs);
559                 }
560                 else
561                 {
562                         VectorMA(org, scale, model->normalmins, ent->mins);
563                         VectorMA(org, scale, model->normalmaxs, ent->maxs);
564                 }
565         }
566         else
567         {
568                 ent->mins[0] = org[0] - 16;
569                 ent->mins[1] = org[1] - 16;
570                 ent->mins[2] = org[2] - 16;
571                 ent->maxs[0] = org[0] + 16;
572                 ent->maxs[1] = org[1] + 16;
573                 ent->maxs[2] = org[2] + 16;
574         }
575 }
576
577 /*
578 ===============
579 CL_LerpPoint
580
581 Determines the fraction between the last two messages that the objects
582 should be put at.
583 ===============
584 */
585 static float CL_LerpPoint(void)
586 {
587         float f;
588
589         if (cl_nettimesyncboundmode.integer == 1)
590                 cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
591
592         // LordHavoc: lerp in listen games as the server is being capped below the client (usually)
593         if (cl.mtime[0] <= cl.mtime[1])
594         {
595                 cl.time = cl.mtime[0];
596                 return 1;
597         }
598
599         f = (cl.time - cl.mtime[1]) / (cl.mtime[0] - cl.mtime[1]);
600         return bound(0, f, 1);
601 }
602
603 void CL_ClearTempEntities (void)
604 {
605         r_refdef.scene.numtempentities = 0;
606 }
607
608 entity_render_t *CL_NewTempEntity(double shadertime)
609 {
610         entity_render_t *render;
611
612         if (r_refdef.scene.numentities >= r_refdef.scene.maxentities)
613                 return NULL;
614         if (r_refdef.scene.numtempentities >= r_refdef.scene.maxtempentities)
615                 return NULL;
616         render = &r_refdef.scene.tempentities[r_refdef.scene.numtempentities++];
617         memset (render, 0, sizeof(*render));
618         r_refdef.scene.entities[r_refdef.scene.numentities++] = render;
619
620         render->shadertime = shadertime;
621         render->alpha = 1;
622         VectorSet(render->colormod, 1, 1, 1);
623         VectorSet(render->glowmod, 1, 1, 1);
624         return render;
625 }
626
627 void CL_Effect(vec3_t org, int modelindex, int startframe, int framecount, float framerate)
628 {
629         int i;
630         cl_effect_t *e;
631         if (!modelindex) // sanity check
632                 return;
633         if (framerate < 1)
634         {
635                 Con_Printf("CL_Effect: framerate %f is < 1\n", framerate);
636                 return;
637         }
638         if (framecount < 1)
639         {
640                 Con_Printf("CL_Effect: framecount %i is < 1\n", framecount);
641                 return;
642         }
643         for (i = 0, e = cl.effects;i < cl.max_effects;i++, e++)
644         {
645                 if (e->active)
646                         continue;
647                 e->active = true;
648                 VectorCopy(org, e->origin);
649                 e->modelindex = modelindex;
650                 e->starttime = cl.time;
651                 e->startframe = startframe;
652                 e->endframe = startframe + framecount;
653                 e->framerate = framerate;
654
655                 e->frame = 0;
656                 e->frame1time = cl.time;
657                 e->frame2time = cl.time;
658                 cl.num_effects = max(cl.num_effects, i + 1);
659                 break;
660         }
661 }
662
663 void CL_AllocLightFlash(entity_render_t *ent, matrix4x4_t *matrix, float radius, float red, float green, float blue, float decay, float lifetime, int cubemapnum, int style, int shadowenable, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
664 {
665         int i;
666         dlight_t *dl;
667
668 // then look for anything else
669         dl = cl.dlights;
670         for (i = 0;i < cl.max_dlights;i++, dl++)
671                 if (!dl->radius)
672                         break;
673
674         // unable to find one
675         if (i == cl.max_dlights)
676                 return;
677
678         //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius);
679         memset (dl, 0, sizeof(*dl));
680         cl.num_dlights = max(cl.num_dlights, i + 1);
681         Matrix4x4_Normalize(&dl->matrix, matrix);
682         dl->ent = ent;
683         Matrix4x4_OriginFromMatrix(&dl->matrix, dl->origin);
684         CL_FindNonSolidLocation(dl->origin, dl->origin, 6);
685         Matrix4x4_SetOrigin(&dl->matrix, dl->origin[0], dl->origin[1], dl->origin[2]);
686         dl->radius = radius;
687         dl->color[0] = red;
688         dl->color[1] = green;
689         dl->color[2] = blue;
690         dl->initialradius = radius;
691         dl->initialcolor[0] = red;
692         dl->initialcolor[1] = green;
693         dl->initialcolor[2] = blue;
694         dl->decay = decay / radius; // changed decay to be a percentage decrease
695         dl->intensity = 1; // this is what gets decayed
696         if (lifetime)
697                 dl->die = cl.time + lifetime;
698         else
699                 dl->die = 0;
700         if (cubemapnum > 0)
701                 dpsnprintf(dl->cubemapname, sizeof(dl->cubemapname), "cubemaps/%i", cubemapnum);
702         else
703                 dl->cubemapname[0] = 0;
704         dl->style = style;
705         dl->shadow = shadowenable;
706         dl->corona = corona;
707         dl->flags = flags;
708         dl->coronasizescale = coronasizescale;
709         dl->ambientscale = ambientscale;
710         dl->diffusescale = diffusescale;
711         dl->specularscale = specularscale;
712 }
713
714 void CL_DecayLightFlashes(void)
715 {
716         int i, oldmax;
717         dlight_t *dl;
718         float time;
719
720         time = bound(0, cl.time - cl.oldtime, 0.1);
721         oldmax = cl.num_dlights;
722         cl.num_dlights = 0;
723         for (i = 0, dl = cl.dlights;i < oldmax;i++, dl++)
724         {
725                 if (dl->radius)
726                 {
727                         dl->intensity -= time * dl->decay;
728                         if (cl.time < dl->die && dl->intensity > 0)
729                         {
730                                 if (cl_dlights_decayradius.integer)
731                                         dl->radius = dl->initialradius * dl->intensity;
732                                 else
733                                         dl->radius = dl->initialradius;
734                                 if (cl_dlights_decaybrightness.integer)
735                                         VectorScale(dl->initialcolor, dl->intensity, dl->color);
736                                 else
737                                         VectorCopy(dl->initialcolor, dl->color);
738                                 cl.num_dlights = i + 1;
739                         }
740                         else
741                                 dl->radius = 0;
742                 }
743         }
744 }
745
746 // called before entity relinking
747 void CL_RelinkLightFlashes(void)
748 {
749         int i, j, k, l;
750         dlight_t *dl;
751         float frac, f;
752         matrix4x4_t tempmatrix;
753
754         if (r_dynamic.integer)
755         {
756                 for (i = 0, dl = cl.dlights;i < cl.num_dlights && r_refdef.scene.numlights < MAX_DLIGHTS;i++, dl++)
757                 {
758                         if (dl->radius)
759                         {
760                                 tempmatrix = dl->matrix;
761                                 Matrix4x4_Scale(&tempmatrix, dl->radius, 1);
762                                 // we need the corona fading to be persistent
763                                 R_RTLight_Update(&dl->rtlight, false, &tempmatrix, dl->color, dl->style, dl->cubemapname, dl->shadow, dl->corona, dl->coronasizescale, dl->ambientscale, dl->diffusescale, dl->specularscale, dl->flags);
764                                 r_refdef.scene.lights[r_refdef.scene.numlights++] = &dl->rtlight;
765                         }
766                 }
767         }
768
769         if (!cl.lightstyle)
770         {
771                 for (j = 0;j < cl.max_lightstyle;j++)
772                 {
773                         r_refdef.scene.rtlightstylevalue[j] = 1;
774                         r_refdef.scene.lightstylevalue[j] = 256;
775                 }
776                 return;
777         }
778
779 // light animations
780 // 'm' is normal light, 'a' is no light, 'z' is double bright
781         f = cl.time * 10;
782         i = (int)floor(f);
783         frac = f - i;
784         for (j = 0;j < cl.max_lightstyle;j++)
785         {
786                 if (!cl.lightstyle[j].length)
787                 {
788                         r_refdef.scene.rtlightstylevalue[j] = 1;
789                         r_refdef.scene.lightstylevalue[j] = 256;
790                         continue;
791                 }
792                 // static lightstyle "=value"
793                 if (cl.lightstyle[j].map[0] == '=')
794                 {
795                         r_refdef.scene.rtlightstylevalue[j] = atof(cl.lightstyle[j].map + 1);
796                         if ( r_lerplightstyles.integer || ((int)f - f) < 0.01)
797                                 r_refdef.scene.lightstylevalue[j] = r_refdef.scene.rtlightstylevalue[j];
798                         continue;
799                 }
800                 k = i % cl.lightstyle[j].length;
801                 l = (i-1) % cl.lightstyle[j].length;
802                 k = cl.lightstyle[j].map[k] - 'a';
803                 l = cl.lightstyle[j].map[l] - 'a';
804                 // rtlightstylevalue is always interpolated because it has no bad
805                 // consequences for performance
806                 // lightstylevalue is subject to a cvar for performance reasons;
807                 // skipping lightmap updates on most rendered frames substantially
808                 // improves framerates (but makes light fades look bad)
809                 r_refdef.scene.rtlightstylevalue[j] = ((k*frac)+(l*(1-frac)))*(22/256.0f);
810                 r_refdef.scene.lightstylevalue[j] = r_lerplightstyles.integer ? (unsigned short)(((k*frac)+(l*(1-frac)))*22) : k*22;
811         }
812 }
813
814 void CL_AddQWCTFFlagModel(entity_t *player, int skin)
815 {
816         int frame = player->render.framegroupblend[0].frame;
817         float f;
818         entity_render_t *flagrender;
819         matrix4x4_t flagmatrix;
820
821         // this code taken from QuakeWorld
822         f = 14;
823         if (frame >= 29 && frame <= 40)
824         {
825                 if (frame >= 29 && frame <= 34)
826                 { //axpain
827                         if      (frame == 29) f = f + 2;
828                         else if (frame == 30) f = f + 8;
829                         else if (frame == 31) f = f + 12;
830                         else if (frame == 32) f = f + 11;
831                         else if (frame == 33) f = f + 10;
832                         else if (frame == 34) f = f + 4;
833                 }
834                 else if (frame >= 35 && frame <= 40)
835                 { // pain
836                         if      (frame == 35) f = f + 2;
837                         else if (frame == 36) f = f + 10;
838                         else if (frame == 37) f = f + 10;
839                         else if (frame == 38) f = f + 8;
840                         else if (frame == 39) f = f + 4;
841                         else if (frame == 40) f = f + 2;
842                 }
843         }
844         else if (frame >= 103 && frame <= 118)
845         {
846                 if      (frame >= 103 && frame <= 104) f = f + 6;  //nailattack
847                 else if (frame >= 105 && frame <= 106) f = f + 6;  //light
848                 else if (frame >= 107 && frame <= 112) f = f + 7;  //rocketattack
849                 else if (frame >= 112 && frame <= 118) f = f + 7;  //shotattack
850         }
851         // end of code taken from QuakeWorld
852
853         flagrender = CL_NewTempEntity(player->render.shadertime);
854         if (!flagrender)
855                 return;
856
857         flagrender->model = cl.model_precache[cl.qw_modelindex_flag];
858         flagrender->skinnum = skin;
859         flagrender->alpha = 1;
860         VectorSet(flagrender->colormod, 1, 1, 1);
861         VectorSet(flagrender->glowmod, 1, 1, 1);
862         // attach the flag to the player matrix
863         Matrix4x4_CreateFromQuakeEntity(&flagmatrix, -f, -22, 0, 0, 0, -45, 1);
864         Matrix4x4_Concat(&flagrender->matrix, &player->render.matrix, &flagmatrix);
865         CL_UpdateRenderEntity(flagrender);
866 }
867
868 matrix4x4_t viewmodelmatrix;
869
870 static const vec3_t muzzleflashorigin = {18, 0, 0};
871
872 extern void V_DriftPitch(void);
873 extern void V_FadeViewFlashs(void);
874 extern void V_CalcViewBlend(void);
875 extern void V_CalcRefdef(void);
876
877 void CL_SetEntityColormapColors(entity_render_t *ent, int colormap)
878 {
879         const unsigned char *cbcolor;
880         if (colormap >= 0)
881         {
882                 cbcolor = palette_rgb_pantscolormap[colormap & 0xF];
883                 VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_pantscolor);
884                 cbcolor = palette_rgb_shirtcolormap[(colormap & 0xF0) >> 4];
885                 VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_shirtcolor);
886         }
887         else
888         {
889                 VectorClear(ent->colormap_pantscolor);
890                 VectorClear(ent->colormap_shirtcolor);
891         }
892 }
893
894 // note this is a recursive function, recursionlimit should be 32 or so on the initial call
895 void CL_UpdateNetworkEntity(entity_t *e, int recursionlimit, qboolean interpolate)
896 {
897         const matrix4x4_t *matrix;
898         matrix4x4_t blendmatrix, tempmatrix, matrix2;
899         int frame;
900         float origin[3], angles[3], lerp;
901         entity_t *t;
902         //entity_persistent_t *p = &e->persistent;
903         //entity_render_t *r = &e->render;
904         // skip inactive entities and world
905         if (!e->state_current.active || e == cl.entities)
906                 return;
907         if (recursionlimit < 1)
908                 return;
909         e->render.alpha = e->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate?
910         e->render.scale = e->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate?
911         e->render.flags = e->state_current.flags;
912         e->render.effects = e->state_current.effects;
913         VectorScale(e->state_current.colormod, (1.0f / 32.0f), e->render.colormod);
914         VectorScale(e->state_current.glowmod, (1.0f / 32.0f), e->render.glowmod);
915         if(e >= cl.entities && e < cl.entities + cl.num_entities)
916                 e->render.entitynumber = e - cl.entities;
917         else
918                 e->render.entitynumber = 0;
919         if (e->state_current.flags & RENDER_COLORMAPPED)
920                 CL_SetEntityColormapColors(&e->render, e->state_current.colormap);
921         else if (e->state_current.colormap > 0 && e->state_current.colormap <= cl.maxclients && cl.scores != NULL)
922                 CL_SetEntityColormapColors(&e->render, cl.scores[e->state_current.colormap-1].colors);
923         else
924                 CL_SetEntityColormapColors(&e->render, -1);
925         e->render.skinnum = e->state_current.skin;
926         if (e->state_current.tagentity)
927         {
928                 // attached entity (gun held in player model's hand, etc)
929                 // if the tag entity is currently impossible, skip it
930                 if (e->state_current.tagentity >= cl.num_entities)
931                         return;
932                 t = cl.entities + e->state_current.tagentity;
933                 // if the tag entity is inactive, skip it
934                 if (!t->state_current.active)
935                         return;
936                 // update the parent first
937                 CL_UpdateNetworkEntity(t, recursionlimit - 1, interpolate);
938                 // make relative to the entity
939                 matrix = &t->render.matrix;
940                 // some properties of the tag entity carry over
941                 e->render.flags |= t->render.flags & (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL);
942                 // if a valid tagindex is used, make it relative to that tag instead
943                 // FIXME: use a model function to get tag info (need to handle skeletal)
944                 if (e->state_current.tagentity && e->state_current.tagindex >= 1 && t->render.model)
945                 {
946                         if(!CL_BlendTagMatrix(&t->render, e->state_current.tagindex - 1, &blendmatrix)) // i.e. no error
947                         {
948                                 // concat the tag matrices onto the entity matrix
949                                 Matrix4x4_Concat(&tempmatrix, &t->render.matrix, &blendmatrix);
950                                 // use the constructed tag matrix
951                                 matrix = &tempmatrix;
952                         }
953                 }
954         }
955         else if (e->render.flags & RENDER_VIEWMODEL)
956         {
957                 // view-relative entity (guns and such)
958                 if (e->render.effects & EF_NOGUNBOB)
959                         matrix = &r_refdef.view.matrix; // really attached to view
960                 else
961                         matrix = &viewmodelmatrix; // attached to gun bob matrix
962         }
963         else
964         {
965                 // world-relative entity (the normal kind)
966                 matrix = &identitymatrix;
967         }
968
969         // movement lerp
970         // if it's the predicted player entity, update according to client movement
971         // but don't lerp if going through a teleporter as it causes a bad lerp
972         // also don't use the predicted location if fixangle was set on both of
973         // the most recent server messages, as that cause means you are spectating
974         // someone or watching a cutscene of some sort
975         if (cl_nolerp.integer || cls.timedemo)
976                 interpolate = false;
977         if (e == cl.entities + cl.playerentity && cl.movement_predicted && (!cl.fixangle[1] || !cl.fixangle[0]))
978         {
979                 VectorCopy(cl.movement_origin, origin);
980                 VectorSet(angles, 0, cl.viewangles[1], 0);
981         }
982         else if (interpolate && e->persistent.lerpdeltatime > 0 && (lerp = (cl.time - e->persistent.lerpstarttime) / e->persistent.lerpdeltatime) < 1)
983         {
984                 // interpolate the origin and angles
985                 lerp = max(0, lerp);
986                 VectorLerp(e->persistent.oldorigin, lerp, e->persistent.neworigin, origin);
987 #if 0
988                 // this fails at the singularity of euler angles
989                 VectorSubtract(e->persistent.newangles, e->persistent.oldangles, delta);
990                 if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360;
991                 if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360;
992                 if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360;
993                 VectorMA(e->persistent.oldangles, lerp, delta, angles);
994 #else
995                 {
996                         vec3_t f0, u0, f1, u1;
997                         AngleVectors(e->persistent.oldangles, f0, NULL, u0);
998                         AngleVectors(e->persistent.newangles, f1, NULL, u1);
999                         VectorMAM(1-lerp, f0, lerp, f1, f0);
1000                         VectorMAM(1-lerp, u0, lerp, u1, u0);
1001                         AnglesFromVectors(angles, f0, u0, false);
1002                 }
1003 #endif
1004         }
1005         else
1006         {
1007                 // no interpolation
1008                 VectorCopy(e->persistent.neworigin, origin);
1009                 VectorCopy(e->persistent.newangles, angles);
1010         }
1011
1012         // model setup and some modelflags
1013         frame = e->state_current.frame;
1014         if (e->state_current.modelindex < MAX_MODELS)
1015                 e->render.model = cl.model_precache[e->state_current.modelindex];
1016         else
1017                 e->render.model = NULL;
1018         if (e->render.model)
1019         {
1020                 if (e->render.skinnum >= e->render.model->numskins)
1021                         e->render.skinnum = 0;
1022                 if (frame >= e->render.model->numframes)
1023                         frame = 0;
1024                 // models can set flags such as EF_ROCKET
1025                 // this 0xFF800000 mask is EF_NOMODELFLAGS plus all the higher EF_ flags such as EF_ROCKET
1026                 if (!(e->render.effects & 0xFF800000))
1027                         e->render.effects |= e->render.model->effects;
1028                 // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
1029                 if (e->render.model->type == mod_alias)
1030                         angles[0] = -angles[0];
1031                 if ((e->render.effects & EF_SELECTABLE) && cl.cmd.cursor_entitynumber == e->state_current.number)
1032                 {
1033                         VectorScale(e->render.colormod, 2, e->render.colormod);
1034                         VectorScale(e->render.glowmod, 2, e->render.glowmod);
1035                 }
1036         }
1037         // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
1038         else if (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC)
1039                 angles[0] = -angles[0];
1040                 // NOTE: this must be synced to SV_GetPitchSign!
1041
1042         if ((e->render.effects & EF_ROTATE) && !(e->render.flags & RENDER_VIEWMODEL))
1043         {
1044                 angles[1] = ANGLEMOD(100*cl.time);
1045                 if (cl_itembobheight.value)
1046                         origin[2] += (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value;
1047         }
1048
1049         // animation lerp
1050         if (e->render.framegroupblend[0].frame == frame)
1051         {
1052                 // update frame lerp fraction
1053                 e->render.framegroupblend[0].lerp = 1;
1054                 e->render.framegroupblend[1].lerp = 0;
1055                 if (e->render.framegroupblend[0].start > e->render.framegroupblend[1].start)
1056                 {
1057                         // make sure frame lerp won't last longer than 100ms
1058                         // (this mainly helps with models that use framegroups and
1059                         // switch between them infrequently)
1060                         e->render.framegroupblend[0].lerp = (cl.time - e->render.framegroupblend[0].start) / min(e->render.framegroupblend[0].start - e->render.framegroupblend[1].start, 0.1);
1061                         e->render.framegroupblend[0].lerp = bound(0, e->render.framegroupblend[0].lerp, 1);
1062                         e->render.framegroupblend[1].lerp = 1 - e->render.framegroupblend[0].lerp;
1063                 }
1064         }
1065         else
1066         {
1067                 // begin a new frame lerp
1068                 e->render.framegroupblend[1] = e->render.framegroupblend[0];
1069                 e->render.framegroupblend[1].lerp = 1;
1070                 e->render.framegroupblend[0].frame = frame;
1071                 e->render.framegroupblend[0].start = cl.time;
1072                 e->render.framegroupblend[0].lerp = 0;
1073         }
1074
1075         // set up the render matrix
1076         if (matrix)
1077         {
1078                 // attached entity, this requires a matrix multiply (concat)
1079                 // FIXME: e->render.scale should go away
1080                 Matrix4x4_CreateFromQuakeEntity(&matrix2, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
1081                 // concat the matrices to make the entity relative to its tag
1082                 Matrix4x4_Concat(&e->render.matrix, matrix, &matrix2);
1083                 // get the origin from the new matrix
1084                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1085         }
1086         else
1087         {
1088                 // unattached entities are faster to process
1089                 Matrix4x4_CreateFromQuakeEntity(&e->render.matrix, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
1090         }
1091
1092         // tenebrae's sprites are all additive mode (weird)
1093         if (gamemode == GAME_TENEBRAE && e->render.model && e->render.model->type == mod_sprite)
1094                 e->render.flags |= RENDER_ADDITIVE;
1095         // player model is only shown with chase_active on
1096         if (e->state_current.number == cl.viewentity)
1097                 e->render.flags |= RENDER_EXTERIORMODEL;
1098         // either fullbright or lit
1099         if(!r_fullbright.integer)
1100         {
1101                 if (!(e->render.effects & EF_FULLBRIGHT))
1102                         e->render.flags |= RENDER_LIGHT;
1103                 else if(r_equalize_entities_fullbright.integer)
1104                         e->render.flags |= RENDER_LIGHT | RENDER_EQUALIZE;
1105         }
1106         // hide player shadow during intermission or nehahra movie
1107         if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
1108          && (e->render.alpha >= 1)
1109          && !(e->render.flags & RENDER_VIEWMODEL)
1110          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
1111                 e->render.flags |= RENDER_SHADOW;
1112         if (e->render.flags & RENDER_VIEWMODEL)
1113                 e->render.flags |= RENDER_NOSELFSHADOW;
1114         if (e->render.effects & EF_NOSELFSHADOW)
1115                 e->render.flags |= RENDER_NOSELFSHADOW;
1116         if (e->render.effects & EF_NODEPTHTEST)
1117                 e->render.flags |= RENDER_NODEPTHTEST;
1118         if (e->render.effects & EF_ADDITIVE)
1119                 e->render.flags |= RENDER_ADDITIVE;
1120         if (e->render.effects & EF_DOUBLESIDED)
1121                 e->render.flags |= RENDER_DOUBLESIDED;
1122
1123         // make the other useful stuff
1124         e->render.allowdecals = true;
1125         CL_UpdateRenderEntity(&e->render);
1126 }
1127
1128 // creates light and trails from an entity
1129 void CL_UpdateNetworkEntityTrail(entity_t *e)
1130 {
1131         effectnameindex_t trailtype;
1132         vec3_t origin;
1133
1134         // bmodels are treated specially since their origin is usually '0 0 0' and
1135         // their actual geometry is far from '0 0 0'
1136         if (e->render.model && e->render.model->soundfromcenter)
1137         {
1138                 vec3_t o;
1139                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
1140                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1141         }
1142         else
1143                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1144
1145         // handle particle trails and such effects now that we know where this
1146         // entity is in the world...
1147         trailtype = EFFECT_NONE;
1148         // LordHavoc: if the entity has no effects, don't check each
1149         if (e->render.effects & (EF_BRIGHTFIELD | EF_FLAME | EF_STARDUST))
1150         {
1151                 if (e->render.effects & EF_BRIGHTFIELD)
1152                 {
1153                         if (gamemode == GAME_NEXUIZ)
1154                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1155                         else
1156                                 CL_EntityParticles(e);
1157                 }
1158                 if (e->render.effects & EF_FLAME)
1159                         CL_ParticleTrail(EFFECT_EF_FLAME, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true);
1160                 if (e->render.effects & EF_STARDUST)
1161                         CL_ParticleTrail(EFFECT_EF_STARDUST, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true);
1162         }
1163         if (e->render.internaleffects & (INTEF_FLAG1QW | INTEF_FLAG2QW))
1164         {
1165                 // these are only set on player entities
1166                 CL_AddQWCTFFlagModel(e, (e->render.internaleffects & INTEF_FLAG2QW) != 0);
1167         }
1168         // muzzleflash fades over time
1169         if (e->persistent.muzzleflash > 0)
1170                 e->persistent.muzzleflash -= bound(0, cl.time - cl.oldtime, 0.1) * 20;
1171         // LordHavoc: if the entity has no effects, don't check each
1172         if (e->render.effects && !(e->render.flags & RENDER_VIEWMODEL))
1173         {
1174                 if (e->render.effects & EF_GIB)
1175                         trailtype = EFFECT_TR_BLOOD;
1176                 else if (e->render.effects & EF_ZOMGIB)
1177                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1178                 else if (e->render.effects & EF_TRACER)
1179                         trailtype = EFFECT_TR_WIZSPIKE;
1180                 else if (e->render.effects & EF_TRACER2)
1181                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1182                 else if (e->render.effects & EF_ROCKET)
1183                         trailtype = EFFECT_TR_ROCKET;
1184                 else if (e->render.effects & EF_GRENADE)
1185                 {
1186                         // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1187                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1188                 }
1189                 else if (e->render.effects & EF_TRACER3)
1190                         trailtype = EFFECT_TR_VORESPIKE;
1191         }
1192         // do trails
1193         if (e->render.flags & RENDER_GLOWTRAIL)
1194                 trailtype = EFFECT_TR_GLOWTRAIL;
1195         // check if a trail is allowed (it is not after a teleport for example)
1196         if (trailtype && e->persistent.trail_allowed)
1197         {
1198                 float len;
1199                 vec3_t vel;
1200                 VectorSubtract(e->state_current.origin, e->state_previous.origin, vel);
1201                 len = e->state_current.time - e->state_previous.time;
1202                 if (len > 0)
1203                         len = 1.0f / len;
1204                 VectorScale(vel, len, vel);
1205                 CL_ParticleTrail(trailtype, 1, e->persistent.trail_origin, origin, vel, vel, e, e->state_current.glowcolor, false, true);
1206         }
1207         // now that the entity has survived one trail update it is allowed to
1208         // leave a real trail on later frames
1209         e->persistent.trail_allowed = true;
1210         VectorCopy(origin, e->persistent.trail_origin);
1211 }
1212
1213
1214 /*
1215 ===============
1216 CL_UpdateViewEntities
1217 ===============
1218 */
1219 void CL_UpdateViewEntities(void)
1220 {
1221         int i;
1222         // update any RENDER_VIEWMODEL entities to use the new view matrix
1223         for (i = 1;i < cl.num_entities;i++)
1224         {
1225                 if (cl.entities_active[i])
1226                 {
1227                         entity_t *ent = cl.entities + i;
1228                         if ((ent->render.flags & RENDER_VIEWMODEL) || ent->state_current.tagentity)
1229                                 CL_UpdateNetworkEntity(ent, 32, true);
1230                 }
1231         }
1232         // and of course the engine viewmodel needs updating as well
1233         CL_UpdateNetworkEntity(&cl.viewent, 32, true);
1234 }
1235
1236 /*
1237 ===============
1238 CL_UpdateNetworkCollisionEntities
1239 ===============
1240 */
1241 void CL_UpdateNetworkCollisionEntities(void)
1242 {
1243         entity_t *ent;
1244         int i;
1245
1246         // start on the entity after the world
1247         cl.num_brushmodel_entities = 0;
1248         for (i = cl.maxclients + 1;i < cl.num_entities;i++)
1249         {
1250                 if (cl.entities_active[i])
1251                 {
1252                         ent = cl.entities + i;
1253                         if (ent->state_current.active && ent->render.model && ent->render.model->name[0] == '*' && ent->render.model->TraceBox)
1254                         {
1255                                 // do not interpolate the bmodels for this
1256                                 CL_UpdateNetworkEntity(ent, 32, false);
1257                                 cl.brushmodel_entities[cl.num_brushmodel_entities++] = i;
1258                         }
1259                 }
1260         }
1261 }
1262
1263 extern void R_DecalSystem_Reset(decalsystem_t *decalsystem);
1264
1265 /*
1266 ===============
1267 CL_UpdateNetworkEntities
1268 ===============
1269 */
1270 void CL_UpdateNetworkEntities(void)
1271 {
1272         entity_t *ent;
1273         int i;
1274
1275         // start on the entity after the world
1276         for (i = 1;i < cl.num_entities;i++)
1277         {
1278                 if (cl.entities_active[i])
1279                 {
1280                         ent = cl.entities + i;
1281                         if (ent->state_current.active)
1282                         {
1283                                 CL_UpdateNetworkEntity(ent, 32, true);
1284                                 // view models should never create light/trails
1285                                 if (!(ent->render.flags & RENDER_VIEWMODEL))
1286                                         CL_UpdateNetworkEntityTrail(ent);
1287                         }
1288                         else
1289                         {
1290                                 R_DecalSystem_Reset(&ent->render.decalsystem);
1291                                 cl.entities_active[i] = false;
1292                         }
1293                 }
1294         }
1295 }
1296
1297 void CL_UpdateViewModel(void)
1298 {
1299         entity_t *ent;
1300         ent = &cl.viewent;
1301         ent->state_previous = ent->state_current;
1302         ent->state_current = defaultstate;
1303         ent->state_current.time = cl.time;
1304         ent->state_current.number = (unsigned short)-1;
1305         ent->state_current.active = true;
1306         ent->state_current.modelindex = cl.stats[STAT_WEAPON];
1307         ent->state_current.frame = cl.stats[STAT_WEAPONFRAME];
1308         ent->state_current.flags = RENDER_VIEWMODEL;
1309         if ((cl.stats[STAT_HEALTH] <= 0 && cl_deathnoviewmodel.integer) || cl.intermission)
1310                 ent->state_current.modelindex = 0;
1311         else if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1312         {
1313                 if (gamemode == GAME_TRANSFUSION)
1314                         ent->state_current.alpha = 128;
1315                 else
1316                         ent->state_current.modelindex = 0;
1317         }
1318         ent->state_current.alpha = cl.entities[cl.viewentity].state_current.alpha;
1319         ent->state_current.effects = EF_NOSHADOW | (cl.entities[cl.viewentity].state_current.effects & (EF_ADDITIVE | EF_FULLBRIGHT | EF_NODEPTHTEST | EF_NOGUNBOB));
1320
1321         // reset animation interpolation on weaponmodel if model changed
1322         if (ent->state_previous.modelindex != ent->state_current.modelindex)
1323         {
1324                 ent->render.framegroupblend[0].frame = ent->render.framegroupblend[1].frame = ent->state_current.frame;
1325                 ent->render.framegroupblend[0].start = ent->render.framegroupblend[1].start = cl.time;
1326                 ent->render.framegroupblend[0].lerp = 1;ent->render.framegroupblend[1].lerp = 0;
1327         }
1328         CL_UpdateNetworkEntity(ent, 32, true);
1329 }
1330
1331 // note this is a recursive function, but it can never get in a runaway loop (because of the delayedlink flags)
1332 void CL_LinkNetworkEntity(entity_t *e)
1333 {
1334         effectnameindex_t trailtype;
1335         vec3_t origin;
1336         vec3_t dlightcolor;
1337         vec_t dlightradius;
1338
1339         // skip inactive entities and world
1340         if (!e->state_current.active || e == cl.entities)
1341                 return;
1342         if (e->state_current.tagentity)
1343         {
1344                 // if the tag entity is currently impossible, skip it
1345                 if (e->state_current.tagentity >= cl.num_entities)
1346                         return;
1347                 // if the tag entity is inactive, skip it
1348                 if (!cl.entities[e->state_current.tagentity].state_current.active)
1349                         return;
1350         }
1351
1352         // create entity dlights associated with this entity
1353         if (e->render.model && e->render.model->soundfromcenter)
1354         {
1355                 // bmodels are treated specially since their origin is usually '0 0 0'
1356                 vec3_t o;
1357                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
1358                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1359         }
1360         else
1361                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1362         trailtype = EFFECT_NONE;
1363         dlightradius = 0;
1364         dlightcolor[0] = 0;
1365         dlightcolor[1] = 0;
1366         dlightcolor[2] = 0;
1367         // LordHavoc: if the entity has no effects, don't check each
1368         if (e->render.effects & (EF_BRIGHTFIELD | EF_DIMLIGHT | EF_BRIGHTLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
1369         {
1370                 if (e->render.effects & EF_BRIGHTFIELD)
1371                 {
1372                         if (gamemode == GAME_NEXUIZ)
1373                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1374                 }
1375                 if (e->render.effects & EF_DIMLIGHT)
1376                 {
1377                         dlightradius = max(dlightradius, 200);
1378                         dlightcolor[0] += 1.50f;
1379                         dlightcolor[1] += 1.50f;
1380                         dlightcolor[2] += 1.50f;
1381                 }
1382                 if (e->render.effects & EF_BRIGHTLIGHT)
1383                 {
1384                         dlightradius = max(dlightradius, 400);
1385                         dlightcolor[0] += 3.00f;
1386                         dlightcolor[1] += 3.00f;
1387                         dlightcolor[2] += 3.00f;
1388                 }
1389                 // LordHavoc: more effects
1390                 if (e->render.effects & EF_RED) // red
1391                 {
1392                         dlightradius = max(dlightradius, 200);
1393                         dlightcolor[0] += 1.50f;
1394                         dlightcolor[1] += 0.15f;
1395                         dlightcolor[2] += 0.15f;
1396                 }
1397                 if (e->render.effects & EF_BLUE) // blue
1398                 {
1399                         dlightradius = max(dlightradius, 200);
1400                         dlightcolor[0] += 0.15f;
1401                         dlightcolor[1] += 0.15f;
1402                         dlightcolor[2] += 1.50f;
1403                 }
1404                 if (e->render.effects & EF_FLAME)
1405                         CL_ParticleTrail(EFFECT_EF_FLAME, 0, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false);
1406                 if (e->render.effects & EF_STARDUST)
1407                         CL_ParticleTrail(EFFECT_EF_STARDUST, 0, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false);
1408         }
1409         // muzzleflash fades over time, and is offset a bit
1410         if (e->persistent.muzzleflash > 0 && r_refdef.scene.numlights < MAX_DLIGHTS)
1411         {
1412                 vec3_t v2;
1413                 vec3_t color;
1414                 trace_t trace;
1415                 matrix4x4_t tempmatrix;
1416                 Matrix4x4_Transform(&e->render.matrix, muzzleflashorigin, v2);
1417                 trace = CL_TraceLine(origin, v2, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID | SUPERCONTENTS_SKY, true, false, NULL, false);
1418                 Matrix4x4_Normalize(&tempmatrix, &e->render.matrix);
1419                 Matrix4x4_SetOrigin(&tempmatrix, trace.endpos[0], trace.endpos[1], trace.endpos[2]);
1420                 Matrix4x4_Scale(&tempmatrix, 150, 1);
1421                 VectorSet(color, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f);
1422                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &tempmatrix, color, -1, NULL, true, 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1423                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1424         }
1425         // LordHavoc: if the model has no flags, don't check each
1426         if (e->render.model && e->render.effects && !(e->render.flags & RENDER_VIEWMODEL))
1427         {
1428                 if (e->render.effects & EF_GIB)
1429                         trailtype = EFFECT_TR_BLOOD;
1430                 else if (e->render.effects & EF_ZOMGIB)
1431                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1432                 else if (e->render.effects & EF_TRACER)
1433                         trailtype = EFFECT_TR_WIZSPIKE;
1434                 else if (e->render.effects & EF_TRACER2)
1435                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1436                 else if (e->render.effects & EF_ROCKET)
1437                         trailtype = EFFECT_TR_ROCKET;
1438                 else if (e->render.effects & EF_GRENADE)
1439                 {
1440                         // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1441                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1442                 }
1443                 else if (e->render.effects & EF_TRACER3)
1444                         trailtype = EFFECT_TR_VORESPIKE;
1445         }
1446         // LordHavoc: customizable glow
1447         if (e->state_current.glowsize)
1448         {
1449                 // * 4 for the expansion from 0-255 to 0-1023 range,
1450                 // / 255 to scale down byte colors
1451                 dlightradius = max(dlightradius, e->state_current.glowsize * 4);
1452                 VectorMA(dlightcolor, (1.0f / 255.0f), palette_rgb[e->state_current.glowcolor], dlightcolor);
1453         }
1454         // custom rtlight
1455         if ((e->state_current.lightpflags & PFLAGS_FULLDYNAMIC) && r_refdef.scene.numlights < MAX_DLIGHTS)
1456         {
1457                 matrix4x4_t dlightmatrix;
1458                 float light[4];
1459                 VectorScale(e->state_current.light, (1.0f / 256.0f), light);
1460                 light[3] = e->state_current.light[3];
1461                 if (light[0] == 0 && light[1] == 0 && light[2] == 0)
1462                         VectorSet(light, 1, 1, 1);
1463                 if (light[3] == 0)
1464                         light[3] = 350;
1465                 // FIXME: add ambient/diffuse/specular scales as an extension ontop of TENEBRAE_GFX_DLIGHTS?
1466                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1467                 Matrix4x4_Scale(&dlightmatrix, light[3], 1);
1468                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &dlightmatrix, light, e->state_current.lightstyle, e->state_current.skin > 0 ? va("cubemaps/%i", e->state_current.skin) : NULL, !(e->state_current.lightpflags & PFLAGS_NOSHADOW), (e->state_current.lightpflags & PFLAGS_CORONA) != 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1469                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1470         }
1471         // make the glow dlight
1472         else if (dlightradius > 0 && (dlightcolor[0] || dlightcolor[1] || dlightcolor[2]) && !(e->render.flags & RENDER_VIEWMODEL) && r_refdef.scene.numlights < MAX_DLIGHTS)
1473         {
1474                 matrix4x4_t dlightmatrix;
1475                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1476                 // hack to make glowing player light shine on their gun
1477                 //if (e->state_current.number == cl.viewentity/* && !chase_active.integer*/)
1478                 //      Matrix4x4_AdjustOrigin(&dlightmatrix, 0, 0, 30);
1479                 Matrix4x4_Scale(&dlightmatrix, dlightradius, 1);
1480                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &dlightmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1481                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1482         }
1483         // do trail light
1484         if (e->render.flags & RENDER_GLOWTRAIL)
1485                 trailtype = EFFECT_TR_GLOWTRAIL;
1486         if (trailtype)
1487                 CL_ParticleTrail(trailtype, 0, origin, origin, vec3_origin, vec3_origin, NULL, e->state_current.glowcolor, true, false);
1488
1489         // don't show viewmodels in certain situations
1490         if (e->render.flags & RENDER_VIEWMODEL)
1491                 if (!r_drawviewmodel.integer || chase_active.integer || r_refdef.envmap)
1492                         return;
1493         // don't show entities with no modelindex (note: this still shows
1494         // entities which have a modelindex that resolved to a NULL model)
1495         if (e->render.model && !(e->render.effects & EF_NODRAW) && r_refdef.scene.numentities < r_refdef.scene.maxentities)
1496                 r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render;
1497         //if (cl.viewentity && e->state_current.number == cl.viewentity)
1498         //      Matrix4x4_Print(&e->render.matrix);
1499 }
1500
1501 void CL_RelinkWorld(void)
1502 {
1503         entity_t *ent = &cl.entities[0];
1504         // FIXME: this should be done at load
1505         ent->render.matrix = identitymatrix;
1506         ent->render.flags = RENDER_SHADOW;
1507         if (!r_fullbright.integer)
1508                 ent->render.flags |= RENDER_LIGHT;
1509         VectorSet(ent->render.colormod, 1, 1, 1);
1510         VectorSet(ent->render.glowmod, 1, 1, 1);
1511         ent->render.allowdecals = true;
1512         CL_UpdateRenderEntity(&ent->render);
1513         r_refdef.scene.worldentity = &ent->render;
1514         r_refdef.scene.worldmodel = cl.worldmodel;
1515 }
1516
1517 static void CL_RelinkStaticEntities(void)
1518 {
1519         int i;
1520         entity_t *e;
1521         for (i = 0, e = cl.static_entities;i < cl.num_static_entities && r_refdef.scene.numentities < r_refdef.scene.maxentities;i++, e++)
1522         {
1523                 e->render.flags = 0;
1524                 // if the model was not loaded when the static entity was created we
1525                 // need to re-fetch the model pointer
1526                 e->render.model = cl.model_precache[e->state_baseline.modelindex];
1527                 // either fullbright or lit
1528                 if(!r_fullbright.integer)
1529                 {
1530                         if (!(e->render.effects & EF_FULLBRIGHT))
1531                                 e->render.flags |= RENDER_LIGHT;
1532                         else if(r_equalize_entities_fullbright.integer)
1533                                 e->render.flags |= RENDER_LIGHT | RENDER_EQUALIZE;
1534                 }
1535                 // hide player shadow during intermission or nehahra movie
1536                 if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST)) && (e->render.alpha >= 1))
1537                         e->render.flags |= RENDER_SHADOW;
1538                 VectorSet(e->render.colormod, 1, 1, 1);
1539                 VectorSet(e->render.glowmod, 1, 1, 1);
1540                 R_LerpAnimation(&e->render);
1541                 e->render.allowdecals = true;
1542                 CL_UpdateRenderEntity(&e->render);
1543                 r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render;
1544         }
1545 }
1546
1547 /*
1548 ===============
1549 CL_RelinkEntities
1550 ===============
1551 */
1552 static void CL_RelinkNetworkEntities(void)
1553 {
1554         entity_t *ent;
1555         int i;
1556
1557         // start on the entity after the world
1558         for (i = 1;i < cl.num_entities;i++)
1559         {
1560                 if (cl.entities_active[i])
1561                 {
1562                         ent = cl.entities + i;
1563                         if (ent->state_current.active)
1564                                 CL_LinkNetworkEntity(ent);
1565                         else
1566                                 cl.entities_active[i] = false;
1567                 }
1568         }
1569 }
1570
1571 static void CL_RelinkEffects(void)
1572 {
1573         int i, intframe;
1574         cl_effect_t *e;
1575         entity_render_t *entrender;
1576         float frame;
1577
1578         for (i = 0, e = cl.effects;i < cl.num_effects;i++, e++)
1579         {
1580                 if (e->active)
1581                 {
1582                         frame = (cl.time - e->starttime) * e->framerate + e->startframe;
1583                         intframe = (int)frame;
1584                         if (intframe < 0 || intframe >= e->endframe)
1585                         {
1586                                 memset(e, 0, sizeof(*e));
1587                                 while (cl.num_effects > 0 && !cl.effects[cl.num_effects - 1].active)
1588                                         cl.num_effects--;
1589                                 continue;
1590                         }
1591
1592                         if (intframe != e->frame)
1593                         {
1594                                 e->frame = intframe;
1595                                 e->frame1time = e->frame2time;
1596                                 e->frame2time = cl.time;
1597                         }
1598
1599                         // if we're drawing effects, get a new temp entity
1600                         // (NewTempEntity adds it to the render entities list for us)
1601                         if (r_draweffects.integer && (entrender = CL_NewTempEntity(e->starttime)))
1602                         {
1603                                 // interpolation stuff
1604                                 entrender->framegroupblend[0].frame = intframe;
1605                                 entrender->framegroupblend[0].lerp = 1 - frame - intframe;
1606                                 entrender->framegroupblend[0].start = e->frame1time;
1607                                 if (intframe + 1 >= e->endframe)
1608                                 {
1609                                         entrender->framegroupblend[1].frame = 0; // disappear
1610                                         entrender->framegroupblend[1].lerp = 0;
1611                                         entrender->framegroupblend[1].start = 0;
1612                                 }
1613                                 else
1614                                 {
1615                                         entrender->framegroupblend[1].frame = intframe + 1;
1616                                         entrender->framegroupblend[1].lerp = frame - intframe;
1617                                         entrender->framegroupblend[1].start = e->frame2time;
1618                                 }
1619
1620                                 // normal stuff
1621                                 if(e->modelindex < MAX_MODELS)
1622                                         entrender->model = cl.model_precache[e->modelindex];
1623                                 else
1624                                         entrender->model = cl.csqc_model_precache[-(e->modelindex+1)];
1625                                 entrender->alpha = 1;
1626                                 VectorSet(entrender->colormod, 1, 1, 1);
1627                                 VectorSet(entrender->glowmod, 1, 1, 1);
1628
1629                                 Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1);
1630                                 CL_UpdateRenderEntity(entrender);
1631                         }
1632                 }
1633         }
1634 }
1635
1636 void CL_Beam_CalculatePositions(const beam_t *b, vec3_t start, vec3_t end)
1637 {
1638         VectorCopy(b->start, start);
1639         VectorCopy(b->end, end);
1640
1641         // if coming from the player, update the start position
1642         if (b->entity == cl.viewentity)
1643         {
1644                 if (cl_beams_quakepositionhack.integer && !chase_active.integer)
1645                 {
1646                         // LordHavoc: this is a stupid hack from Quake that makes your
1647                         // lightning appear to come from your waist and cover less of your
1648                         // view
1649                         // in Quake this hack was applied to all players (causing the
1650                         // infamous crotch-lightning), but in darkplaces and QuakeWorld it
1651                         // only applies to your own lightning, and only in first person
1652                         Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, start);
1653                 }
1654                 if (cl_beams_instantaimhack.integer)
1655                 {
1656                         vec3_t dir, localend;
1657                         vec_t len;
1658                         // LordHavoc: this updates the beam direction to match your
1659                         // viewangles
1660                         VectorSubtract(end, start, dir);
1661                         len = VectorLength(dir);
1662                         VectorNormalize(dir);
1663                         VectorSet(localend, len, 0, 0);
1664                         Matrix4x4_Transform(&r_refdef.view.matrix, localend, end);
1665                 }
1666         }
1667 }
1668
1669 void CL_RelinkBeams(void)
1670 {
1671         int i;
1672         beam_t *b;
1673         vec3_t dist, org, start, end;
1674         float d;
1675         entity_render_t *entrender;
1676         double yaw, pitch;
1677         float forward;
1678         matrix4x4_t tempmatrix;
1679
1680         for (i = 0, b = cl.beams;i < cl.num_beams;i++, b++)
1681         {
1682                 if (!b->model)
1683                         continue;
1684                 if (b->endtime < cl.time)
1685                 {
1686                         b->model = NULL;
1687                         continue;
1688                 }
1689
1690                 CL_Beam_CalculatePositions(b, start, end);
1691
1692                 if (b->lightning)
1693                 {
1694                         if (cl_beams_lightatend.integer && r_refdef.scene.numlights < MAX_DLIGHTS)
1695                         {
1696                                 // FIXME: create a matrix from the beam start/end orientation
1697                                 vec3_t dlightcolor;
1698                                 VectorSet(dlightcolor, 0.3, 0.7, 1);
1699                                 Matrix4x4_CreateFromQuakeEntity(&tempmatrix, end[0], end[1], end[2], 0, 0, 0, 200);
1700                                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &tempmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 1, 0, 0, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1701                                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1702                         }
1703                         if (cl_beams_polygons.integer)
1704                                 continue;
1705                 }
1706
1707                 // calculate pitch and yaw
1708                 // (this is similar to the QuakeC builtin function vectoangles)
1709                 VectorSubtract(end, start, dist);
1710                 if (dist[1] == 0 && dist[0] == 0)
1711                 {
1712                         yaw = 0;
1713                         if (dist[2] > 0)
1714                                 pitch = 90;
1715                         else
1716                                 pitch = 270;
1717                 }
1718                 else
1719                 {
1720                         yaw = atan2(dist[1], dist[0]) * 180 / M_PI;
1721                         if (yaw < 0)
1722                                 yaw += 360;
1723
1724                         forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]);
1725                         pitch = atan2(dist[2], forward) * 180 / M_PI;
1726                         if (pitch < 0)
1727                                 pitch += 360;
1728                 }
1729
1730                 // add new entities for the lightning
1731                 VectorCopy (start, org);
1732                 d = VectorNormalizeLength(dist);
1733                 while (d > 0)
1734                 {
1735                         entrender = CL_NewTempEntity (0);
1736                         if (!entrender)
1737                                 return;
1738                         //VectorCopy (org, ent->render.origin);
1739                         entrender->model = b->model;
1740                         //ent->render.effects = EF_FULLBRIGHT;
1741                         //ent->render.angles[0] = pitch;
1742                         //ent->render.angles[1] = yaw;
1743                         //ent->render.angles[2] = rand()%360;
1744                         Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1);
1745                         CL_UpdateRenderEntity(entrender);
1746                         VectorMA(org, 30, dist, org);
1747                         d -= 30;
1748                 }
1749         }
1750
1751         while (cl.num_beams > 0 && !cl.beams[cl.num_beams - 1].model)
1752                 cl.num_beams--;
1753 }
1754
1755 static void CL_RelinkQWNails(void)
1756 {
1757         int i;
1758         vec_t *v;
1759         entity_render_t *entrender;
1760
1761         for (i = 0;i < cl.qw_num_nails;i++)
1762         {
1763                 v = cl.qw_nails[i];
1764
1765                 // if we're drawing effects, get a new temp entity
1766                 // (NewTempEntity adds it to the render entities list for us)
1767                 if (!(entrender = CL_NewTempEntity(0)))
1768                         continue;
1769
1770                 // normal stuff
1771                 entrender->model = cl.model_precache[cl.qw_modelindex_spike];
1772                 entrender->alpha = 1;
1773                 VectorSet(entrender->colormod, 1, 1, 1);
1774                 VectorSet(entrender->glowmod, 1, 1, 1);
1775
1776                 Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, v[0], v[1], v[2], v[3], v[4], v[5], 1);
1777                 CL_UpdateRenderEntity(entrender);
1778         }
1779 }
1780
1781 void CL_LerpPlayer(float frac)
1782 {
1783         int i;
1784
1785         cl.viewzoom = cl.mviewzoom[1] + frac * (cl.mviewzoom[0] - cl.mviewzoom[1]);
1786         for (i = 0;i < 3;i++)
1787         {
1788                 cl.punchangle[i] = cl.mpunchangle[1][i] + frac * (cl.mpunchangle[0][i] - cl.mpunchangle[1][i]);
1789                 cl.punchvector[i] = cl.mpunchvector[1][i] + frac * (cl.mpunchvector[0][i] - cl.mpunchvector[1][i]);
1790                 cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
1791         }
1792
1793         // interpolate the angles if playing a demo or spectating someone
1794         if (cls.demoplayback || cl.fixangle[0])
1795         {
1796                 for (i = 0;i < 3;i++)
1797                 {
1798                         float d = cl.mviewangles[0][i] - cl.mviewangles[1][i];
1799                         if (d > 180)
1800                                 d -= 360;
1801                         else if (d < -180)
1802                                 d += 360;
1803                         cl.viewangles[i] = cl.mviewangles[1][i] + frac * d;
1804                 }
1805         }
1806 }
1807
1808 void CSQC_RelinkAllEntities (int drawmask)
1809 {
1810         // link stuff
1811         CL_RelinkWorld();
1812         CL_RelinkStaticEntities();
1813         CL_RelinkBeams();
1814         CL_RelinkEffects();
1815
1816         // link stuff
1817         if (drawmask & ENTMASK_ENGINE)
1818         {
1819                 CL_RelinkNetworkEntities();
1820                 if (drawmask & ENTMASK_ENGINEVIEWMODELS)
1821                         CL_LinkNetworkEntity(&cl.viewent); // link gun model
1822                 CL_RelinkQWNails();
1823         }
1824
1825         // update view blend
1826         V_CalcViewBlend();
1827 }
1828
1829 /*
1830 ===============
1831 CL_UpdateWorld
1832
1833 Update client game world for a new frame
1834 ===============
1835 */
1836 void CL_UpdateWorld(void)
1837 {
1838         r_refdef.scene.extraupdate = !r_speeds.integer;
1839         r_refdef.scene.numentities = 0;
1840         r_refdef.scene.numlights = 0;
1841         r_refdef.view.matrix = identitymatrix;
1842         r_refdef.view.quality = 1;
1843
1844         cl.num_brushmodel_entities = 0;
1845
1846         if (cls.state == ca_connected && cls.signon == SIGNONS)
1847         {
1848                 // prepare for a new frame
1849                 CL_LerpPlayer(CL_LerpPoint());
1850                 CL_DecayLightFlashes();
1851                 CL_ClearTempEntities();
1852                 V_DriftPitch();
1853                 V_FadeViewFlashs();
1854
1855                 // if prediction is enabled we have to update all the collidable
1856                 // network entities before the prediction code can be run
1857                 CL_UpdateNetworkCollisionEntities();
1858
1859                 // now update the player prediction
1860                 CL_ClientMovement_Replay();
1861
1862                 // update the player entity (which may be predicted)
1863                 CL_UpdateNetworkEntity(cl.entities + cl.viewentity, 32, true);
1864
1865                 // now update the view (which depends on that player entity)
1866                 V_CalcRefdef();
1867
1868                 // now update all the network entities and create particle trails
1869                 // (some entities may depend on the view)
1870                 CL_UpdateNetworkEntities();
1871
1872                 // update the engine-based viewmodel
1873                 CL_UpdateViewModel();
1874
1875                 CL_RelinkLightFlashes();
1876                 CSQC_RelinkAllEntities(ENTMASK_ENGINE | ENTMASK_ENGINEVIEWMODELS);
1877
1878                 // decals, particles, and explosions will be updated during rneder
1879         }
1880
1881         r_refdef.scene.time = cl.time;
1882 }
1883
1884 // LordHavoc: pausedemo command
1885 static void CL_PauseDemo_f (void)
1886 {
1887         cls.demopaused = !cls.demopaused;
1888         if (cls.demopaused)
1889                 Con_Print("Demo paused\n");
1890         else
1891                 Con_Print("Demo unpaused\n");
1892 }
1893
1894 /*
1895 ======================
1896 CL_Fog_f
1897 ======================
1898 */
1899 static void CL_Fog_f (void)
1900 {
1901         if (Cmd_Argc () == 1)
1902         {
1903                 Con_Printf("\"fog\" is \"%f %f %f %f %f %f %f %f %f\"\n", r_refdef.fog_density, r_refdef.fog_red, r_refdef.fog_green, r_refdef.fog_blue, r_refdef.fog_alpha, r_refdef.fog_start, r_refdef.fog_end, r_refdef.fog_height, r_refdef.fog_fadedepth);
1904                 return;
1905         }
1906         FOG_clear(); // so missing values get good defaults
1907         if(Cmd_Argc() > 1)
1908                 r_refdef.fog_density = atof(Cmd_Argv(1));
1909         if(Cmd_Argc() > 2)
1910                 r_refdef.fog_red = atof(Cmd_Argv(2));
1911         if(Cmd_Argc() > 3)
1912                 r_refdef.fog_green = atof(Cmd_Argv(3));
1913         if(Cmd_Argc() > 4)
1914                 r_refdef.fog_blue = atof(Cmd_Argv(4));
1915         if(Cmd_Argc() > 5)
1916                 r_refdef.fog_alpha = atof(Cmd_Argv(5));
1917         if(Cmd_Argc() > 6)
1918                 r_refdef.fog_start = atof(Cmd_Argv(6));
1919         if(Cmd_Argc() > 7)
1920                 r_refdef.fog_end = atof(Cmd_Argv(7));
1921         if(Cmd_Argc() > 8)
1922                 r_refdef.fog_height = atof(Cmd_Argv(8));
1923         if(Cmd_Argc() > 9)
1924                 r_refdef.fog_fadedepth = atof(Cmd_Argv(9));
1925 }
1926
1927 /*
1928 ====================
1929 CL_TimeRefresh_f
1930
1931 For program optimization
1932 ====================
1933 */
1934 static void CL_TimeRefresh_f (void)
1935 {
1936         int i;
1937         float timestart, timedelta;
1938
1939         r_refdef.scene.extraupdate = false;
1940
1941         timestart = Sys_DoubleTime();
1942         for (i = 0;i < 128;i++)
1943         {
1944                 Matrix4x4_CreateFromQuakeEntity(&r_refdef.view.matrix, r_refdef.view.origin[0], r_refdef.view.origin[1], r_refdef.view.origin[2], 0, i / 128.0 * 360.0, 0, 1);
1945                 r_refdef.view.quality = 1;
1946                 CL_UpdateScreen();
1947         }
1948         timedelta = Sys_DoubleTime() - timestart;
1949
1950         Con_Printf("%f seconds (%f fps)\n", timedelta, 128/timedelta);
1951 }
1952
1953 void CL_AreaStats_f(void)
1954 {
1955         World_PrintAreaStats(&cl.world, "client");
1956 }
1957
1958 cl_locnode_t *CL_Locs_FindNearest(const vec3_t point)
1959 {
1960         int i;
1961         cl_locnode_t *loc;
1962         cl_locnode_t *best;
1963         vec3_t nearestpoint;
1964         vec_t dist, bestdist;
1965         best = NULL;
1966         bestdist = 0;
1967         for (loc = cl.locnodes;loc;loc = loc->next)
1968         {
1969                 for (i = 0;i < 3;i++)
1970                         nearestpoint[i] = bound(loc->mins[i], point[i], loc->maxs[i]);
1971                 dist = VectorDistance2(nearestpoint, point);
1972                 if (bestdist > dist || !best)
1973                 {
1974                         bestdist = dist;
1975                         best = loc;
1976                         if (bestdist < 1)
1977                                 break;
1978                 }
1979         }
1980         return best;
1981 }
1982
1983 void CL_Locs_FindLocationName(char *buffer, size_t buffersize, vec3_t point)
1984 {
1985         cl_locnode_t *loc;
1986         loc = CL_Locs_FindNearest(point);
1987         if (loc)
1988                 strlcpy(buffer, loc->name, buffersize);
1989         else
1990                 dpsnprintf(buffer, buffersize, "LOC=%.0f:%.0f:%.0f", point[0], point[1], point[2]);
1991 }
1992
1993 void CL_Locs_FreeNode(cl_locnode_t *node)
1994 {
1995         cl_locnode_t **pointer, **next;
1996         for (pointer = &cl.locnodes;*pointer;pointer = next)
1997         {
1998                 next = &(*pointer)->next;
1999                 if (*pointer == node)
2000                 {
2001                         *pointer = node->next;
2002                         Mem_Free(node);
2003                         return;
2004                 }
2005         }
2006         Con_Printf("CL_Locs_FreeNode: no such node! (%p)\n", (void *)node);
2007 }
2008
2009 void CL_Locs_AddNode(vec3_t mins, vec3_t maxs, const char *name)
2010 {
2011         cl_locnode_t *node, **pointer;
2012         int namelen;
2013         if (!name)
2014                 name = "";
2015         namelen = strlen(name);
2016         node = (cl_locnode_t *) Mem_Alloc(cls.levelmempool, sizeof(cl_locnode_t) + namelen + 1);
2017         VectorSet(node->mins, min(mins[0], maxs[0]), min(mins[1], maxs[1]), min(mins[2], maxs[2]));
2018         VectorSet(node->maxs, max(mins[0], maxs[0]), max(mins[1], maxs[1]), max(mins[2], maxs[2]));
2019         node->name = (char *)(node + 1);
2020         memcpy(node->name, name, namelen);
2021         node->name[namelen] = 0;
2022         // link it into the tail of the list to preserve the order
2023         for (pointer = &cl.locnodes;*pointer;pointer = &(*pointer)->next)
2024                 ;
2025         *pointer = node;
2026 }
2027
2028 void CL_Locs_Add_f(void)
2029 {
2030         vec3_t mins, maxs;
2031         if (Cmd_Argc() != 5 && Cmd_Argc() != 8)
2032         {
2033                 Con_Printf("usage: %s x y z[ x y z] name\n", Cmd_Argv(0));
2034                 return;
2035         }
2036         mins[0] = atof(Cmd_Argv(1));
2037         mins[1] = atof(Cmd_Argv(2));
2038         mins[2] = atof(Cmd_Argv(3));
2039         if (Cmd_Argc() == 8)
2040         {
2041                 maxs[0] = atof(Cmd_Argv(4));
2042                 maxs[1] = atof(Cmd_Argv(5));
2043                 maxs[2] = atof(Cmd_Argv(6));
2044                 CL_Locs_AddNode(mins, maxs, Cmd_Argv(7));
2045         }
2046         else
2047                 CL_Locs_AddNode(mins, mins, Cmd_Argv(4));
2048 }
2049
2050 void CL_Locs_RemoveNearest_f(void)
2051 {
2052         cl_locnode_t *loc;
2053         loc = CL_Locs_FindNearest(r_refdef.view.origin);
2054         if (loc)
2055                 CL_Locs_FreeNode(loc);
2056         else
2057                 Con_Printf("no loc point or box found for your location\n");
2058 }
2059
2060 void CL_Locs_Clear_f(void)
2061 {
2062         while (cl.locnodes)
2063                 CL_Locs_FreeNode(cl.locnodes);
2064 }
2065
2066 void CL_Locs_Save_f(void)
2067 {
2068         cl_locnode_t *loc;
2069         qfile_t *outfile;
2070         char locfilename[MAX_QPATH];
2071         if (!cl.locnodes)
2072         {
2073                 Con_Printf("No loc points/boxes exist!\n");
2074                 return;
2075         }
2076         if (cls.state != ca_connected || !cl.worldmodel)
2077         {
2078                 Con_Printf("No level loaded!\n");
2079                 return;
2080         }
2081         FS_StripExtension(cl.worldmodel->name, locfilename, sizeof(locfilename));
2082         strlcat(locfilename, ".loc", sizeof(locfilename));
2083
2084         outfile = FS_OpenRealFile(locfilename, "w", false);
2085         if (!outfile)
2086                 return;
2087         // if any boxes are used then this is a proquake-format loc file, which
2088         // allows comments, so add some relevant information at the start
2089         for (loc = cl.locnodes;loc;loc = loc->next)
2090                 if (!VectorCompare(loc->mins, loc->maxs))
2091                         break;
2092         if (loc)
2093         {
2094                 FS_Printf(outfile, "// %s %s saved by %s\n// x,y,z,x,y,z,\"name\"\n\n", locfilename, Sys_TimeString("%Y-%m-%d"), engineversion);
2095                 for (loc = cl.locnodes;loc;loc = loc->next)
2096                         if (VectorCompare(loc->mins, loc->maxs))
2097                                 break;
2098                 if (loc)
2099                         Con_Printf("Warning: writing loc file containing a mixture of qizmo-style points and proquake-style boxes may not work in qizmo or proquake!\n");
2100         }
2101         for (loc = cl.locnodes;loc;loc = loc->next)
2102         {
2103                 if (VectorCompare(loc->mins, loc->maxs))
2104                 {
2105                         int len;
2106                         const char *s;
2107                         const char *in = loc->name;
2108                         char name[MAX_INPUTLINE];
2109                         for (len = 0;len < (int)sizeof(name) - 1 && *in;)
2110                         {
2111                                 if (*in == ' ') {s = "$loc_name_separator";in++;}
2112                                 else if (!strncmp(in, "SSG", 3)) {s = "$loc_name_ssg";in += 3;}
2113                                 else if (!strncmp(in, "NG", 2)) {s = "$loc_name_ng";in += 2;}
2114                                 else if (!strncmp(in, "SNG", 3)) {s = "$loc_name_sng";in += 3;}
2115                                 else if (!strncmp(in, "GL", 2)) {s = "$loc_name_gl";in += 2;}
2116                                 else if (!strncmp(in, "RL", 2)) {s = "$loc_name_rl";in += 2;}
2117                                 else if (!strncmp(in, "LG", 2)) {s = "$loc_name_lg";in += 2;}
2118                                 else if (!strncmp(in, "GA", 2)) {s = "$loc_name_ga";in += 2;}
2119                                 else if (!strncmp(in, "YA", 2)) {s = "$loc_name_ya";in += 2;}
2120                                 else if (!strncmp(in, "RA", 2)) {s = "$loc_name_ra";in += 2;}
2121                                 else if (!strncmp(in, "MEGA", 4)) {s = "$loc_name_mh";in += 4;}
2122                                 else s = NULL;
2123                                 if (s)
2124                                 {
2125                                         while (len < (int)sizeof(name) - 1 && *s)
2126                                                 name[len++] = *s++;
2127                                         continue;
2128                                 }
2129                                 name[len++] = *in++;
2130                         }
2131                         name[len] = 0;
2132                         FS_Printf(outfile, "%.0f %.0f %.0f %s\n", loc->mins[0]*8, loc->mins[1]*8, loc->mins[2]*8, name);
2133                 }
2134                 else
2135                         FS_Printf(outfile, "%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,\"%s\"\n", loc->mins[0], loc->mins[1], loc->mins[2], loc->maxs[0], loc->maxs[1], loc->maxs[2], loc->name);
2136         }
2137         FS_Close(outfile);
2138 }
2139
2140 void CL_Locs_Reload_f(void)
2141 {
2142         int i, linenumber, limit, len;
2143         const char *s;
2144         char *filedata, *text, *textend, *linestart, *linetext, *lineend;
2145         fs_offset_t filesize;
2146         vec3_t mins, maxs;
2147         char locfilename[MAX_QPATH];
2148         char name[MAX_INPUTLINE];
2149
2150         if (cls.state != ca_connected || !cl.worldmodel)
2151         {
2152                 Con_Printf("No level loaded!\n");
2153                 return;
2154         }
2155
2156         CL_Locs_Clear_f();
2157
2158         // try maps/something.loc first (LordHavoc: where I think they should be)
2159         FS_StripExtension(cl.worldmodel->name, locfilename, sizeof(locfilename));
2160         strlcat(locfilename, ".loc", sizeof(locfilename));
2161         filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize);
2162         if (!filedata)
2163         {
2164                 // try proquake name as well (LordHavoc: I hate path mangling)
2165                 FS_StripExtension(va("locs/%s", FS_FileWithoutPath(cl.worldmodel->name)), locfilename, sizeof(locfilename));
2166                 strlcat(locfilename, ".loc", sizeof(locfilename));
2167                 filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize);
2168                 if (!filedata)
2169                         return;
2170         }
2171         text = filedata;
2172         textend = filedata + filesize;
2173         for (linenumber = 1;text < textend;linenumber++)
2174         {
2175                 linestart = text;
2176                 for (;text < textend && *text != '\r' && *text != '\n';text++)
2177                         ;
2178                 lineend = text;
2179                 if (text + 1 < textend && *text == '\r' && text[1] == '\n')
2180                         text++;
2181                 if (text < textend)
2182                         text++;
2183                 // trim trailing whitespace
2184                 while (lineend > linestart && ISWHITESPACE(lineend[-1]))
2185                         lineend--;
2186                 // trim leading whitespace
2187                 while (linestart < lineend && ISWHITESPACE(*linestart))
2188                         linestart++;
2189                 // check if this is a comment
2190                 if (linestart + 2 <= lineend && !strncmp(linestart, "//", 2))
2191                         continue;
2192                 linetext = linestart;
2193                 limit = 3;
2194                 for (i = 0;i < limit;i++)
2195                 {
2196                         if (linetext >= lineend)
2197                                 break;
2198                         // note: a missing number is interpreted as 0
2199                         if (i < 3)
2200                                 mins[i] = atof(linetext);
2201                         else
2202                                 maxs[i - 3] = atof(linetext);
2203                         // now advance past the number
2204                         while (linetext < lineend && !ISWHITESPACE(*linetext) && *linetext != ',')
2205                                 linetext++;
2206                         // advance through whitespace
2207                         if (linetext < lineend)
2208                         {
2209                                 if (*linetext == ',')
2210                                 {
2211                                         linetext++;
2212                                         limit = 6;
2213                                         // note: comma can be followed by whitespace
2214                                 }
2215                                 if (ISWHITESPACE(*linetext))
2216                                 {
2217                                         // skip whitespace
2218                                         while (linetext < lineend && ISWHITESPACE(*linetext))
2219                                                 linetext++;
2220                                 }
2221                         }
2222                 }
2223                 // if this is a quoted name, remove the quotes
2224                 if (i == 6)
2225                 {
2226                         if (linetext >= lineend || *linetext != '"')
2227                                 continue; // proquake location names are always quoted
2228                         lineend--;
2229                         linetext++;
2230                         len = min(lineend - linetext, (int)sizeof(name) - 1);
2231                         memcpy(name, linetext, len);
2232                         name[len] = 0;
2233                         // add the box to the list
2234                         CL_Locs_AddNode(mins, maxs, name);
2235                 }
2236                 // if a point was parsed, it needs to be scaled down by 8 (since
2237                 // point-based loc files were invented by a proxy which dealt
2238                 // directly with quake protocol coordinates, which are *8), turn
2239                 // it into a box
2240                 else if (i == 3)
2241                 {
2242                         // interpret silly fuhquake macros
2243                         for (len = 0;len < (int)sizeof(name) - 1 && linetext < lineend;)
2244                         {
2245                                 if (*linetext == '$')
2246                                 {
2247                                         if (linetext + 18 <= lineend && !strncmp(linetext, "$loc_name_separator", 19)) {s = " ";linetext += 19;}
2248                                         else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_ssg", 13)) {s = "SSG";linetext += 13;}
2249                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ng", 12)) {s = "NG";linetext += 12;}
2250                                         else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_sng", 13)) {s = "SNG";linetext += 13;}
2251                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_gl", 12)) {s = "GL";linetext += 12;}
2252                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_rl", 12)) {s = "RL";linetext += 12;}
2253                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_lg", 12)) {s = "LG";linetext += 12;}
2254                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ga", 12)) {s = "GA";linetext += 12;}
2255                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ya", 12)) {s = "YA";linetext += 12;}
2256                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ra", 12)) {s = "RA";linetext += 12;}
2257                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_mh", 12)) {s = "MEGA";linetext += 12;}
2258                                         else s = NULL;
2259                                         if (s)
2260                                         {
2261                                                 while (len < (int)sizeof(name) - 1 && *s)
2262                                                         name[len++] = *s++;
2263                                                 continue;
2264                                         }
2265                                 }
2266                                 name[len++] = *linetext++;
2267                         }
2268                         name[len] = 0;
2269                         // add the point to the list
2270                         VectorScale(mins, (1.0 / 8.0), mins);
2271                         CL_Locs_AddNode(mins, mins, name);
2272                 }
2273                 else
2274                         continue;
2275         }
2276 }
2277
2278 /*
2279 ===========
2280 CL_Shutdown
2281 ===========
2282 */
2283 void CL_Shutdown (void)
2284 {
2285         CL_Screen_Shutdown();
2286         CL_Particles_Shutdown();
2287         CL_Parse_Shutdown();
2288
2289         Mem_FreePool (&cls.permanentmempool);
2290         Mem_FreePool (&cls.levelmempool);
2291 }
2292
2293 /*
2294 =================
2295 CL_Init
2296 =================
2297 */
2298 void CL_Init (void)
2299 {
2300         cls.levelmempool = Mem_AllocPool("client (per-level memory)", 0, NULL);
2301         cls.permanentmempool = Mem_AllocPool("client (long term memory)", 0, NULL);
2302
2303         memset(&r_refdef, 0, sizeof(r_refdef));
2304         // max entities sent to renderer per frame
2305         r_refdef.scene.maxentities = MAX_EDICTS + 256 + 512;
2306         r_refdef.scene.entities = (entity_render_t **)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t *) * r_refdef.scene.maxentities);
2307
2308         r_refdef.scene.maxtempentities = 4096; // FIXME: make this grow
2309         r_refdef.scene.tempentities = (entity_render_t *)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t) * r_refdef.scene.maxtempentities);
2310
2311         CL_InitInput ();
2312
2313 //
2314 // register our commands
2315 //
2316         Cvar_RegisterVariable (&cl_upspeed);
2317         Cvar_RegisterVariable (&cl_forwardspeed);
2318         Cvar_RegisterVariable (&cl_backspeed);
2319         Cvar_RegisterVariable (&cl_sidespeed);
2320         Cvar_RegisterVariable (&cl_movespeedkey);
2321         Cvar_RegisterVariable (&cl_yawspeed);
2322         Cvar_RegisterVariable (&cl_pitchspeed);
2323         Cvar_RegisterVariable (&cl_anglespeedkey);
2324         Cvar_RegisterVariable (&cl_shownet);
2325         Cvar_RegisterVariable (&cl_nolerp);
2326         Cvar_RegisterVariable (&cl_deathfade);
2327         Cvar_RegisterVariable (&lookspring);
2328         Cvar_RegisterVariable (&lookstrafe);
2329         Cvar_RegisterVariable (&sensitivity);
2330         Cvar_RegisterVariable (&freelook);
2331
2332         Cvar_RegisterVariable (&m_pitch);
2333         Cvar_RegisterVariable (&m_yaw);
2334         Cvar_RegisterVariable (&m_forward);
2335         Cvar_RegisterVariable (&m_side);
2336
2337         Cvar_RegisterVariable (&cl_itembobspeed);
2338         Cvar_RegisterVariable (&cl_itembobheight);
2339
2340         Cmd_AddCommand ("entities", CL_PrintEntities_f, "print information on network entities known to client");
2341         Cmd_AddCommand ("disconnect", CL_Disconnect_f, "disconnect from server (or disconnect all clients if running a server)");
2342         Cmd_AddCommand ("record", CL_Record_f, "record a demo");
2343         Cmd_AddCommand ("stop", CL_Stop_f, "stop recording or playing a demo");
2344         Cmd_AddCommand ("playdemo", CL_PlayDemo_f, "watch a demo file");
2345         Cmd_AddCommand ("timedemo", CL_TimeDemo_f, "play back a demo as fast as possible and save statistics to benchmark.log");
2346
2347         // Support Client-side Model Index List
2348         Cmd_AddCommand ("cl_modelindexlist", CL_ModelIndexList_f, "list information on all models in the client modelindex");
2349         // Support Client-side Sound Index List
2350         Cmd_AddCommand ("cl_soundindexlist", CL_SoundIndexList_f, "list all sounds in the client soundindex");
2351
2352         Cvar_RegisterVariable (&cl_autodemo);
2353         Cvar_RegisterVariable (&cl_autodemo_nameformat);
2354
2355         Cmd_AddCommand ("fog", CL_Fog_f, "set global fog parameters (density red green blue [alpha [mindist maxdist]])");
2356
2357         // LordHavoc: added pausedemo
2358         Cmd_AddCommand ("pausedemo", CL_PauseDemo_f, "pause demo playback (can also safely pause demo recording if using QUAKE, QUAKEDP or NEHAHRAMOVIE protocol, useful for making movies)");
2359
2360         Cmd_AddCommand ("cl_areastats", CL_AreaStats_f, "prints statistics on entity culling during collision traces");
2361
2362         Cvar_RegisterVariable(&r_draweffects);
2363         Cvar_RegisterVariable(&cl_explosions_alpha_start);
2364         Cvar_RegisterVariable(&cl_explosions_alpha_end);
2365         Cvar_RegisterVariable(&cl_explosions_size_start);
2366         Cvar_RegisterVariable(&cl_explosions_size_end);
2367         Cvar_RegisterVariable(&cl_explosions_lifetime);
2368         Cvar_RegisterVariable(&cl_stainmaps);
2369         Cvar_RegisterVariable(&cl_stainmaps_clearonload);
2370         Cvar_RegisterVariable(&cl_beams_polygons);
2371         Cvar_RegisterVariable(&cl_beams_quakepositionhack);
2372         Cvar_RegisterVariable(&cl_beams_instantaimhack);
2373         Cvar_RegisterVariable(&cl_beams_lightatend);
2374         Cvar_RegisterVariable(&cl_noplayershadow);
2375         Cvar_RegisterVariable(&cl_dlights_decayradius);
2376         Cvar_RegisterVariable(&cl_dlights_decaybrightness);
2377
2378         Cvar_RegisterVariable(&cl_prydoncursor);
2379
2380         Cvar_RegisterVariable(&cl_deathnoviewmodel);
2381
2382         // for QW connections
2383         Cvar_RegisterVariable(&qport);
2384         Cvar_SetValueQuick(&qport, (rand() * RAND_MAX + rand()) & 0xffff);
2385
2386         Cmd_AddCommand("timerefresh", CL_TimeRefresh_f, "turn quickly and print rendering statistcs");
2387
2388         Cvar_RegisterVariable(&cl_locs_enable);
2389         Cvar_RegisterVariable(&cl_locs_show);
2390         Cmd_AddCommand("locs_add", CL_Locs_Add_f, "add a point or box location (usage: x y z[ x y z] \"name\", if two sets of xyz are supplied it is a box, otherwise point)");
2391         Cmd_AddCommand("locs_removenearest", CL_Locs_RemoveNearest_f, "remove the nearest point or box (note: you need to be very near a box to remove it)");
2392         Cmd_AddCommand("locs_clear", CL_Locs_Clear_f, "remove all loc points/boxes");
2393         Cmd_AddCommand("locs_reload", CL_Locs_Reload_f, "reload .loc file for this map");
2394         Cmd_AddCommand("locs_save", CL_Locs_Save_f, "save .loc file for this map containing currently defined points and boxes");
2395
2396         CL_Parse_Init();
2397         CL_Particles_Init();
2398         CL_Screen_Init();
2399
2400         CL_Video_Init();
2401         CL_Gecko_Init();
2402 }
2403
2404
2405