added R_ScrollTexCoord2f (copies while texture coordinates with an offset)
[divverent/darkplaces.git] / cl_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cl_main.c  -- client main loop
21
22 #include "quakedef.h"
23 #include "cl_collision.h"
24 #include "cl_video.h"
25 #include "image.h"
26
27 // we need to declare some mouse variables here, because the menu system
28 // references them even when on a unix system.
29
30 // these two are not intended to be set directly
31 cvar_t cl_name = {CVAR_SAVE, "_cl_name", "player"};
32 cvar_t cl_color = {CVAR_SAVE, "_cl_color", "0"};
33 cvar_t cl_pmodel = {CVAR_SAVE, "_cl_pmodel", "0"};
34
35 cvar_t cl_shownet = {0, "cl_shownet","0"};
36 cvar_t cl_nolerp = {0, "cl_nolerp", "0"};
37
38 cvar_t cl_itembobheight = {0, "cl_itembobheight", "8"};
39 cvar_t cl_itembobspeed = {0, "cl_itembobspeed", "0.5"};
40
41 cvar_t lookspring = {CVAR_SAVE, "lookspring","0"};
42 cvar_t lookstrafe = {CVAR_SAVE, "lookstrafe","0"};
43 cvar_t sensitivity = {CVAR_SAVE, "sensitivity","3", 1, 30};
44
45 cvar_t m_pitch = {CVAR_SAVE, "m_pitch","0.022"};
46 cvar_t m_yaw = {CVAR_SAVE, "m_yaw","0.022"};
47 cvar_t m_forward = {CVAR_SAVE, "m_forward","1"};
48 cvar_t m_side = {CVAR_SAVE, "m_side","0.8"};
49
50 cvar_t freelook = {CVAR_SAVE, "freelook", "1"};
51
52 cvar_t r_draweffects = {0, "r_draweffects", "1"};
53
54 cvar_t cl_explosions = {CVAR_SAVE, "cl_explosions", "1"};
55 cvar_t cl_stainmaps = {CVAR_SAVE, "cl_stainmaps", "1"};
56
57 cvar_t cl_beams_polygons = {CVAR_SAVE, "cl_beams_polygons", "1"};
58 cvar_t cl_beams_relative = {CVAR_SAVE, "cl_beams_relative", "1"};
59 cvar_t cl_beams_lightatend = {CVAR_SAVE, "cl_beams_lightatend", "0"};
60
61 cvar_t cl_noplayershadow = {CVAR_SAVE, "cl_noplayershadow", "0"};
62
63 mempool_t *cl_scores_mempool;
64 mempool_t *cl_refdef_mempool;
65 mempool_t *cl_entities_mempool;
66
67 client_static_t cls;
68 client_state_t  cl;
69
70 int cl_max_entities;
71 int cl_max_static_entities;
72 int cl_max_temp_entities;
73 int cl_max_effects;
74 int cl_max_beams;
75 int cl_max_dlights;
76 int cl_max_lightstyle;
77 int cl_max_brushmodel_entities;
78
79 entity_t *cl_entities;
80 qbyte *cl_entities_active;
81 entity_t *cl_static_entities;
82 entity_t *cl_temp_entities;
83 cl_effect_t *cl_effects;
84 beam_t *cl_beams;
85 dlight_t *cl_dlights;
86 lightstyle_t *cl_lightstyle;
87 entity_render_t **cl_brushmodel_entities;
88
89 int cl_num_entities;
90 int cl_num_static_entities;
91 int cl_num_temp_entities;
92 int cl_num_brushmodel_entities;
93
94 /*
95 =====================
96 CL_ClearState
97
98 =====================
99 */
100 void CL_ClearState (void)
101 {
102         int i;
103
104         if (!sv.active)
105                 Host_ClearMemory ();
106
107         Mem_EmptyPool(cl_scores_mempool);
108         Mem_EmptyPool(cl_entities_mempool);
109
110 // wipe the entire cl structure
111         memset (&cl, 0, sizeof(cl));
112
113         SZ_Clear (&cls.message);
114
115         cl_num_entities = 0;
116         cl_num_static_entities = 0;
117         cl_num_temp_entities = 0;
118         cl_num_brushmodel_entities = 0;
119
120         // tweak these if the game runs out
121         cl_max_entities = MAX_EDICTS;
122         cl_max_static_entities = 256;
123         cl_max_temp_entities = 512;
124         cl_max_effects = 256;
125         cl_max_beams = 24;
126         cl_max_dlights = MAX_DLIGHTS;
127         cl_max_lightstyle = MAX_LIGHTSTYLES;
128         cl_max_brushmodel_entities = MAX_EDICTS;
129
130         cl_entities = Mem_Alloc(cl_entities_mempool, cl_max_entities * sizeof(entity_t));
131         cl_entities_active = Mem_Alloc(cl_entities_mempool, cl_max_entities * sizeof(qbyte));
132         cl_static_entities = Mem_Alloc(cl_entities_mempool, cl_max_static_entities * sizeof(entity_t));
133         cl_temp_entities = Mem_Alloc(cl_entities_mempool, cl_max_temp_entities * sizeof(entity_t));
134         cl_effects = Mem_Alloc(cl_entities_mempool, cl_max_effects * sizeof(cl_effect_t));
135         cl_beams = Mem_Alloc(cl_entities_mempool, cl_max_beams * sizeof(beam_t));
136         cl_dlights = Mem_Alloc(cl_entities_mempool, cl_max_dlights * sizeof(dlight_t));
137         cl_lightstyle = Mem_Alloc(cl_entities_mempool, cl_max_lightstyle * sizeof(lightstyle_t));
138         cl_brushmodel_entities = Mem_Alloc(cl_entities_mempool, cl_max_brushmodel_entities * sizeof(entity_render_t *));
139
140         CL_Screen_NewMap();
141
142         CL_Particles_Clear();
143
144         // LordHavoc: have to set up the baseline info for alpha and other stuff
145         for (i = 0;i < cl_max_entities;i++)
146         {
147                 ClearStateToDefault(&cl_entities[i].state_baseline);
148                 ClearStateToDefault(&cl_entities[i].state_previous);
149                 ClearStateToDefault(&cl_entities[i].state_current);
150         }
151
152         CL_CGVM_Clear();
153 }
154
155 /*
156 =====================
157 CL_Disconnect
158
159 Sends a disconnect message to the server
160 This is also called on Host_Error, so it shouldn't cause any errors
161 =====================
162 */
163 void CL_Disconnect (void)
164 {
165         if (cls.state == ca_dedicated)
166                 return;
167
168 // stop sounds (especially looping!)
169         S_StopAllSounds (true);
170
171         // clear contents blends
172         cl.cshifts[0].percent = 0;
173         cl.cshifts[1].percent = 0;
174         cl.cshifts[2].percent = 0;
175         cl.cshifts[3].percent = 0;
176
177         cl.worldmodel = NULL;
178
179         if (cls.demoplayback)
180                 CL_StopPlayback ();
181         else if (cls.state == ca_connected)
182         {
183                 if (cls.demorecording)
184                         CL_Stop_f ();
185
186                 Con_DPrintf ("Sending clc_disconnect\n");
187                 SZ_Clear (&cls.message);
188                 MSG_WriteByte (&cls.message, clc_disconnect);
189                 NET_SendUnreliableMessage (cls.netcon, &cls.message);
190                 SZ_Clear (&cls.message);
191                 NET_Close (cls.netcon);
192                 cls.state = ca_disconnected; // prevent this code from executing again during Host_ShutdownServer
193                 // if running a local server, shut it down
194                 if (sv.active)
195                         Host_ShutdownServer(false);
196         }
197         cls.state = ca_disconnected;
198
199         cls.demoplayback = cls.timedemo = false;
200         cls.signon = 0;
201 }
202
203 void CL_Disconnect_f (void)
204 {
205         CL_Disconnect ();
206         if (sv.active)
207                 Host_ShutdownServer (false);
208 }
209
210
211
212
213 /*
214 =====================
215 CL_EstablishConnection
216
217 Host should be either "local" or a net address to be passed on
218 =====================
219 */
220 void CL_EstablishConnection (char *host)
221 {
222         if (cls.state == ca_dedicated)
223                 return;
224
225         if (cls.demoplayback)
226                 return;
227
228         CL_Disconnect ();
229
230         cls.netcon = NET_Connect (host);
231         if (!cls.netcon)
232                 Host_Error ("CL_Connect: connect failed\n");
233         Con_DPrintf ("CL_EstablishConnection: connected to %s\n", host);
234
235         cls.demonum = -1;                       // not in the demo loop now
236         cls.state = ca_connected;
237         cls.signon = 0;                         // need all the signon messages before playing
238
239         CL_ClearState ();
240 }
241
242 /*
243 ==============
244 CL_PrintEntities_f
245 ==============
246 */
247 static void CL_PrintEntities_f (void)
248 {
249         entity_t *ent;
250         int i, j;
251         char name[32];
252
253         for (i = 0, ent = cl_entities;i < cl_num_entities;i++, ent++)
254         {
255                 if (!ent->state_current.active)
256                         continue;
257
258                 if (ent->render.model)
259                         strncpy(name, ent->render.model->name, 25);
260                 else
261                         strcpy(name, "--no model--");
262                 name[25] = 0;
263                 for (j = strlen(name);j < 25;j++)
264                         name[j] = ' ';
265                 Con_Printf ("%3i: %s:%04i (%5i %5i %5i) [%3i %3i %3i] %4.2f %5.3f\n", i, name, ent->render.frame, (int) ent->render.origin[0], (int) ent->render.origin[1], (int) ent->render.origin[2], (int) ent->render.angles[0] % 360, (int) ent->render.angles[1] % 360, (int) ent->render.angles[2] % 360, ent->render.scale, ent->render.alpha);
266         }
267 }
268
269 //static const vec3_t nomodelmins = {-16, -16, -16};
270 //static const vec3_t nomodelmaxs = {16, 16, 16};
271 void CL_BoundingBoxForEntity(entity_render_t *ent)
272 {
273         if (ent->model)
274         {
275                 //if (ent->angles[0] || ent->angles[2])
276                 if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0)
277                 {
278                         // pitch or roll
279                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->rotatedmins[0];
280                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->rotatedmins[1];
281                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->rotatedmins[2];
282                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->rotatedmaxs[0];
283                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->rotatedmaxs[1];
284                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->rotatedmaxs[2];
285                         //VectorAdd(ent->origin, ent->model->rotatedmins, ent->mins);
286                         //VectorAdd(ent->origin, ent->model->rotatedmaxs, ent->maxs);
287                 }
288                 //else if (ent->angles[1])
289                 else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0)
290                 {
291                         // yaw
292                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->yawmins[0];
293                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->yawmins[1];
294                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->yawmins[2];
295                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->yawmaxs[0];
296                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->yawmaxs[1];
297                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->yawmaxs[2];
298                         //VectorAdd(ent->origin, ent->model->yawmins, ent->mins);
299                         //VectorAdd(ent->origin, ent->model->yawmaxs, ent->maxs);
300                 }
301                 else
302                 {
303                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->normalmins[0];
304                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->normalmins[1];
305                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->normalmins[2];
306                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->normalmaxs[0];
307                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->normalmaxs[1];
308                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->normalmaxs[2];
309                         //VectorAdd(ent->origin, ent->model->normalmins, ent->mins);
310                         //VectorAdd(ent->origin, ent->model->normalmaxs, ent->maxs);
311                 }
312         }
313         else
314         {
315                 ent->mins[0] = ent->matrix.m[0][3] - 16;
316                 ent->mins[1] = ent->matrix.m[1][3] - 16;
317                 ent->mins[2] = ent->matrix.m[2][3] - 16;
318                 ent->maxs[0] = ent->matrix.m[0][3] + 16;
319                 ent->maxs[1] = ent->matrix.m[1][3] + 16;
320                 ent->maxs[2] = ent->matrix.m[2][3] + 16;
321                 //VectorAdd(ent->origin, nomodelmins, ent->mins);
322                 //VectorAdd(ent->origin, nomodelmaxs, ent->maxs);
323         }
324 }
325
326 void CL_LerpUpdate(entity_t *e)
327 {
328         entity_persistent_t *p;
329         entity_render_t *r;
330         p = &e->persistent;
331         r = &e->render;
332
333         if (p->modelindex != e->state_current.modelindex)
334         {
335                 // reset all interpolation information
336                 p->modelindex = e->state_current.modelindex;
337                 p->frame1 = p->frame2 = e->state_current.frame;
338                 p->frame1time = p->frame2time = cl.time;
339                 p->framelerp = 1;
340         }
341         else if (p->frame2 != e->state_current.frame)
342         {
343                 // transition to new frame
344                 p->frame1 = p->frame2;
345                 p->frame1time = p->frame2time;
346                 p->frame2 = e->state_current.frame;
347                 p->frame2time = cl.time;
348                 p->framelerp = 0;
349         }
350         else
351         {
352                 // update transition
353                 p->framelerp = (cl.time - p->frame2time) * 10;
354                 p->framelerp = bound(0, p->framelerp, 1);
355         }
356
357         r->model = cl.model_precache[e->state_current.modelindex];
358         Mod_CheckLoaded(r->model);
359         r->frame = e->state_current.frame;
360         r->frame1 = p->frame1;
361         r->frame2 = p->frame2;
362         r->framelerp = p->framelerp;
363         r->frame1time = p->frame1time;
364         r->frame2time = p->frame2time;
365 }
366
367 /*
368 ===============
369 CL_LerpPoint
370
371 Determines the fraction between the last two messages that the objects
372 should be put at.
373 ===============
374 */
375 static float CL_LerpPoint (void)
376 {
377         float f;
378
379         // dropped packet, or start of demo
380         if (cl.mtime[1] < cl.mtime[0] - 0.1)
381                 cl.mtime[1] = cl.mtime[0] - 0.1;
382
383         cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
384
385         // LordHavoc: lerp in listen games as the server is being capped below the client (usually)
386         f = cl.mtime[0] - cl.mtime[1];
387         if (!f || cl_nolerp.integer || cls.timedemo || (sv.active && svs.maxclients == 1))
388         {
389                 cl.time = cl.mtime[0];
390                 return 1;
391         }
392
393         f = (cl.time - cl.mtime[1]) / f;
394         return bound(0, f, 1);
395 }
396
397 void CL_ClearTempEntities (void)
398 {
399         cl_num_temp_entities = 0;
400 }
401
402 entity_t *CL_NewTempEntity (void)
403 {
404         entity_t *ent;
405
406         if (r_refdef.numentities >= r_refdef.maxentities)
407                 return NULL;
408         if (cl_num_temp_entities >= cl_max_temp_entities)
409                 return NULL;
410         ent = &cl_temp_entities[cl_num_temp_entities++];
411         memset (ent, 0, sizeof(*ent));
412         r_refdef.entities[r_refdef.numentities++] = &ent->render;
413
414         ent->render.colormap = -1; // no special coloring
415         ent->render.scale = 1;
416         ent->render.alpha = 1;
417         return ent;
418 }
419
420 void CL_AllocDlight (entity_render_t *ent, vec3_t org, float radius, float red, float green, float blue, float decay, float lifetime)
421 {
422         int i;
423         dlight_t *dl;
424
425         /*
426 // first look for an exact key match
427         if (ent)
428         {
429                 dl = cl_dlights;
430                 for (i = 0;i < MAX_DLIGHTS;i++, dl++)
431                         if (dl->ent == ent)
432                                 goto dlightsetup;
433         }
434         */
435
436 // then look for anything else
437         dl = cl_dlights;
438         for (i = 0;i < MAX_DLIGHTS;i++, dl++)
439                 if (!dl->radius)
440                         goto dlightsetup;
441
442         // unable to find one
443         return;
444
445 dlightsetup:
446         //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius);
447         memset (dl, 0, sizeof(*dl));
448         dl->ent = ent;
449         Mod_FindNonSolidLocation(org, dl->origin, cl.worldmodel, 6);
450         //VectorCopy(org, dl->origin);
451         dl->radius = radius;
452         dl->color[0] = red;
453         dl->color[1] = green;
454         dl->color[2] = blue;
455         dl->decay = decay;
456         if (lifetime)
457                 dl->die = cl.time + lifetime;
458         else
459                 dl->die = 0;
460 }
461
462 void CL_DecayLights (void)
463 {
464         int i;
465         dlight_t *dl;
466         float time;
467
468         time = cl.time - cl.oldtime;
469
470         dl = cl_dlights;
471         for (i=0 ; i<MAX_DLIGHTS ; i++, dl++)
472         {
473                 if (!dl->radius)
474                         continue;
475                 if (dl->die < cl.time)
476                 {
477                         dl->radius = 0;
478                         continue;
479                 }
480
481                 dl->radius -= time*dl->decay;
482                 if (dl->radius < 0)
483                         dl->radius = 0;
484         }
485 }
486
487 void CL_RelinkWorld (void)
488 {
489         entity_t *ent = &cl_entities[0];
490         if (cl_num_entities < 1)
491                 cl_num_entities = 1;
492         cl_brushmodel_entities[cl_num_brushmodel_entities++] = &ent->render;
493         Matrix4x4_CreateIdentity(&ent->render.matrix);
494         Matrix4x4_CreateIdentity(&ent->render.inversematrix);
495         CL_BoundingBoxForEntity(&ent->render);
496 }
497
498 static void CL_RelinkStaticEntities(void)
499 {
500         int i;
501         for (i = 0;i < cl_num_static_entities && r_refdef.numentities < r_refdef.maxentities;i++)
502         {
503                 Mod_CheckLoaded(cl_static_entities[i].render.model);
504                 r_refdef.entities[r_refdef.numentities++] = &cl_static_entities[i].render;
505         }
506 }
507
508 /*
509 ===============
510 CL_RelinkEntities
511 ===============
512 */
513 extern qboolean Nehahrademcompatibility;
514 #define MAXVIEWMODELS 32
515 entity_t *viewmodels[MAXVIEWMODELS];
516 int numviewmodels;
517 static void CL_RelinkNetworkEntities(void)
518 {
519         entity_t *ent;
520         int i, effects, temp;
521         float d, bobjrotate, bobjoffset, lerp;
522         vec3_t oldorg, neworg, delta, dlightcolor, v, v2, mins, maxs;
523
524         numviewmodels = 0;
525
526         bobjrotate = ANGLEMOD(100*cl.time);
527         if (cl_itembobheight.value)
528                 bobjoffset = (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value;
529         else
530                 bobjoffset = 0;
531
532         // start on the entity after the world
533         for (i = 1, ent = cl_entities + 1;i < MAX_EDICTS;i++, ent++)
534         {
535                 // if the object isn't active in the current network frame, skip it
536                 if (!cl_entities_active[i])
537                         continue;
538                 if (!ent->state_current.active)
539                 {
540                         cl_entities_active[i] = false;
541                         continue;
542                 }
543
544                 VectorCopy(ent->persistent.trail_origin, oldorg);
545
546                 if (!ent->state_previous.active)
547                 {
548                         // only one state available
549                         VectorCopy (ent->persistent.neworigin, neworg);
550                         VectorCopy (ent->persistent.newangles, ent->render.angles);
551                         VectorCopy (neworg, oldorg);
552                 }
553                 else
554                 {
555                         // if the delta is large, assume a teleport and don't lerp
556                         VectorSubtract(ent->persistent.neworigin, ent->persistent.oldorigin, delta);
557                         if (ent->persistent.lerpdeltatime > 0)
558                         {
559                                 lerp = (cl.time - ent->persistent.lerpstarttime) / ent->persistent.lerpdeltatime;
560                                 if (lerp < 1)
561                                 {
562                                         // interpolate the origin and angles
563                                         VectorMA(ent->persistent.oldorigin, lerp, delta, neworg);
564                                         VectorSubtract(ent->persistent.newangles, ent->persistent.oldangles, delta);
565                                         if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360;
566                                         if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360;
567                                         if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360;
568                                         VectorMA(ent->persistent.oldangles, lerp, delta, ent->render.angles);
569                                 }
570                                 else
571                                 {
572                                         // no interpolation
573                                         VectorCopy (ent->persistent.neworigin, neworg);
574                                         VectorCopy (ent->persistent.newangles, ent->render.angles);
575                                 }
576                         }
577                         else
578                         {
579                                 // no interpolation
580                                 VectorCopy (ent->persistent.neworigin, neworg);
581                                 VectorCopy (ent->persistent.newangles, ent->render.angles);
582                         }
583                 }
584
585                 if (!ent->render.model || ent->render.model->type != mod_brush)
586                         ent->render.angles[0] = -ent->render.angles[0];
587
588                 VectorCopy (neworg, ent->persistent.trail_origin);
589                 // persistent.modelindex will be updated by CL_LerpUpdate
590                 if (ent->state_current.modelindex != ent->persistent.modelindex || !ent->state_previous.active)
591                         VectorCopy(neworg, oldorg);
592
593                 VectorCopy (neworg, ent->render.origin);
594                 ent->render.flags = ent->state_current.flags;
595                 if (i == cl.viewentity)
596                         ent->render.flags |= RENDER_EXTERIORMODEL;
597                 ent->render.effects = effects = ent->state_current.effects;
598                 if (ent->state_current.flags & RENDER_COLORMAPPED)
599                         ent->render.colormap = ent->state_current.colormap;
600                 else if (cl.scores == NULL || !ent->state_current.colormap)
601                         ent->render.colormap = -1; // no special coloring
602                 else
603                         ent->render.colormap = cl.scores[ent->state_current.colormap - 1].colors; // color it
604                 ent->render.skinnum = ent->state_current.skin;
605                 ent->render.alpha = ent->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate?
606                 ent->render.scale = ent->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate?
607
608                 if (ent->render.model && ent->render.model->flags & EF_ROTATE)
609                 {
610                         ent->render.angles[1] = bobjrotate;
611                         ent->render.origin[2] += bobjoffset;
612                 }
613
614                 Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, ent->render.origin[0], ent->render.origin[1], ent->render.origin[2], ent->render.angles[0], ent->render.angles[1], ent->render.angles[2], ent->render.scale);
615
616                 // update interpolation info
617                 CL_LerpUpdate(ent);
618
619                 // handle effects now...
620                 dlightcolor[0] = 0;
621                 dlightcolor[1] = 0;
622                 dlightcolor[2] = 0;
623
624                 // LordHavoc: if the entity has no effects, don't check each
625                 if (effects)
626                 {
627                         if (effects & EF_BRIGHTFIELD)
628                         {
629                                 if (gamemode == GAME_NEXUIZ)
630                                 {
631                                         dlightcolor[0] += 100.0f;
632                                         dlightcolor[1] += 200.0f;
633                                         dlightcolor[2] += 400.0f;
634                                         // don't do trail if we have no previous location
635                                         if (ent->state_previous.active)
636                                                 CL_RocketTrail (oldorg, neworg, 8, ent);
637                                 }
638                                 else
639                                         CL_EntityParticles (ent);
640                         }
641                         if (effects & EF_MUZZLEFLASH)
642                                 ent->persistent.muzzleflash = 100.0f;
643                         if (effects & EF_DIMLIGHT)
644                         {
645                                 dlightcolor[0] += 200.0f;
646                                 dlightcolor[1] += 200.0f;
647                                 dlightcolor[2] += 200.0f;
648                         }
649                         if (effects & EF_BRIGHTLIGHT)
650                         {
651                                 dlightcolor[0] += 400.0f;
652                                 dlightcolor[1] += 400.0f;
653                                 dlightcolor[2] += 400.0f;
654                         }
655                         // LordHavoc: added EF_RED and EF_BLUE
656                         if (effects & EF_RED) // red
657                         {
658                                 dlightcolor[0] += 200.0f;
659                                 dlightcolor[1] +=  20.0f;
660                                 dlightcolor[2] +=  20.0f;
661                         }
662                         if (effects & EF_BLUE) // blue
663                         {
664                                 dlightcolor[0] +=  20.0f;
665                                 dlightcolor[1] +=  20.0f;
666                                 dlightcolor[2] += 200.0f;
667                         }
668                         if (effects & EF_FLAME)
669                         {
670                                 if (ent->render.model)
671                                 {
672                                         mins[0] = neworg[0] - 16.0f;
673                                         mins[1] = neworg[1] - 16.0f;
674                                         mins[2] = neworg[2] - 16.0f;
675                                         maxs[0] = neworg[0] + 16.0f;
676                                         maxs[1] = neworg[1] + 16.0f;
677                                         maxs[2] = neworg[2] + 16.0f;
678                                         // how many flames to make
679                                         temp = (int) (cl.time * 300) - (int) (cl.oldtime * 300);
680                                         CL_FlameCube(mins, maxs, temp);
681                                 }
682                                 d = lhrandom(200, 250);
683                                 dlightcolor[0] += d * 1.0f;
684                                 dlightcolor[1] += d * 0.7f;
685                                 dlightcolor[2] += d * 0.3f;
686                         }
687                         if (effects & EF_STARDUST)
688                         {
689                                 if (ent->render.model)
690                                 {
691                                         mins[0] = neworg[0] - 16.0f;
692                                         mins[1] = neworg[1] - 16.0f;
693                                         mins[2] = neworg[2] - 16.0f;
694                                         maxs[0] = neworg[0] + 16.0f;
695                                         maxs[1] = neworg[1] + 16.0f;
696                                         maxs[2] = neworg[2] + 16.0f;
697                                         // how many particles to make
698                                         temp = (int) (cl.time * 200) - (int) (cl.oldtime * 200);
699                                         CL_Stardust(mins, maxs, temp);
700                                 }
701                                 d = 100;
702                                 dlightcolor[0] += d * 1.0f;
703                                 dlightcolor[1] += d * 0.7f;
704                                 dlightcolor[2] += d * 0.3f;
705                         }
706                 }
707
708                 if (ent->persistent.muzzleflash > 0)
709                 {
710                         v2[0] = ent->render.matrix.m[0][0] * 18 + neworg[0];
711                         v2[1] = ent->render.matrix.m[0][1] * 18 + neworg[1];
712                         v2[2] = ent->render.matrix.m[0][2] * 18 + neworg[2] + 16;
713                         CL_TraceLine(neworg, v2, v, NULL, 0, true, NULL);
714
715                         CL_AllocDlight (NULL, v, ent->persistent.muzzleflash, 1, 1, 1, 0, 0);
716                         ent->persistent.muzzleflash -= cl.frametime * 1000;
717                 }
718
719                 // LordHavoc: if the model has no flags, don't check each
720                 if (ent->render.model && ent->render.model->flags)
721                 {
722                         // note: EF_ROTATE handled above, above matrix calculation
723                         // only do trails if present in the previous frame as well
724                         if (ent->state_previous.active)
725                         {
726                                 if (ent->render.model->flags & EF_GIB)
727                                         CL_RocketTrail (oldorg, neworg, 2, ent);
728                                 else if (ent->render.model->flags & EF_ZOMGIB)
729                                         CL_RocketTrail (oldorg, neworg, 4, ent);
730                                 else if (ent->render.model->flags & EF_TRACER)
731                                 {
732                                         CL_RocketTrail (oldorg, neworg, 3, ent);
733                                         dlightcolor[0] += 0x10;
734                                         dlightcolor[1] += 0x40;
735                                         dlightcolor[2] += 0x10;
736                                 }
737                                 else if (ent->render.model->flags & EF_TRACER2)
738                                 {
739                                         CL_RocketTrail (oldorg, neworg, 5, ent);
740                                         dlightcolor[0] += 0x50;
741                                         dlightcolor[1] += 0x30;
742                                         dlightcolor[2] += 0x10;
743                                 }
744                                 else if (ent->render.model->flags & EF_ROCKET)
745                                 {
746                                         CL_RocketTrail (oldorg, ent->render.origin, 0, ent);
747                                         dlightcolor[0] += 200.0f;
748                                         dlightcolor[1] += 160.0f;
749                                         dlightcolor[2] +=  80.0f;
750                                 }
751                                 else if (ent->render.model->flags & EF_GRENADE)
752                                 {
753                                         if (ent->render.alpha == -1) // LordHavoc: Nehahra dem compatibility (cigar smoke)
754                                                 CL_RocketTrail (oldorg, neworg, 7, ent);
755                                         else
756                                                 CL_RocketTrail (oldorg, neworg, 1, ent);
757                                 }
758                                 else if (ent->render.model->flags & EF_TRACER3)
759                                 {
760                                         CL_RocketTrail (oldorg, neworg, 6, ent);
761                                         dlightcolor[0] += 0x50;
762                                         dlightcolor[1] += 0x20;
763                                         dlightcolor[2] += 0x40;
764                                 }
765                         }
766                 }
767                 // LordHavoc: customizable glow
768                 if (ent->state_current.glowsize)
769                 {
770                         // * 4 for the expansion from 0-255 to 0-1023 range,
771                         // / 255 to scale down byte colors
772                         VectorMA(dlightcolor, ent->state_current.glowsize * (4.0f / 255.0f), (qbyte *)&palette_complete[ent->state_current.glowcolor], dlightcolor);
773                 }
774                 // LordHavoc: customizable trail
775                 if (ent->render.flags & RENDER_GLOWTRAIL)
776                         CL_RocketTrail2 (oldorg, neworg, ent->state_current.glowcolor, ent);
777
778                 if (dlightcolor[0] || dlightcolor[1] || dlightcolor[2])
779                 {
780                         VectorCopy(neworg, v);
781                         // hack to make glowing player light shine on their gun
782                         if (i == cl.viewentity/* && !chase_active.integer*/)
783                                 v[2] += 30;
784                         CL_AllocDlight (&ent->render, v, 1, dlightcolor[0], dlightcolor[1], dlightcolor[2], 0, 0);
785                 }
786
787                 if (chase_active.integer && (ent->render.flags & RENDER_VIEWMODEL))
788                         continue;
789
790                 // don't show entities with no modelindex (note: this still shows
791                 // entities which have a modelindex that resolved to a NULL model)
792                 if (!ent->state_current.modelindex)
793                         continue;
794                 if (effects & EF_NODRAW)
795                         continue;
796
797                 // store a list of view-relative entities for later adjustment in view code
798                 if (ent->render.flags & RENDER_VIEWMODEL)
799                 {
800                         if (numviewmodels < MAXVIEWMODELS)
801                                 viewmodels[numviewmodels++] = ent;
802                         continue;
803                 }
804
805                 Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
806
807                 CL_BoundingBoxForEntity(&ent->render);
808                 if (ent->render.model && ent->render.model->name[0] == '*' && ent->render.model->type == mod_brush)
809                         cl_brushmodel_entities[cl_num_brushmodel_entities++] = &ent->render;
810
811                 // note: the cl.viewentity and intermission check is to hide player
812                 // shadow during intermission and during the Nehahra movie and
813                 // Nehahra cinematics
814                 if (!(ent->state_current.effects & EF_NOSHADOW)
815                  && !(ent->state_current.effects & EF_ADDITIVE)
816                  && (ent->state_current.alpha == 255)
817                  && !(ent->render.flags & RENDER_VIEWMODEL)
818                  && (i != cl.viewentity || (!cl.intermission && !Nehahrademcompatibility && !cl_noplayershadow.integer)))
819                         ent->render.flags |= RENDER_SHADOW;
820
821                 if (r_refdef.numentities < r_refdef.maxentities)
822                         r_refdef.entities[r_refdef.numentities++] = &ent->render;
823
824                 if (cl_num_entities < i + 1)
825                         cl_num_entities = i + 1;
826         }
827 }
828
829 void CL_Effect(vec3_t org, int modelindex, int startframe, int framecount, float framerate)
830 {
831         int i;
832         cl_effect_t *e;
833         if (!modelindex) // sanity check
834                 return;
835         for (i = 0, e = cl_effects;i < cl_max_effects;i++, e++)
836         {
837                 if (e->active)
838                         continue;
839                 e->active = true;
840                 VectorCopy(org, e->origin);
841                 e->modelindex = modelindex;
842                 e->starttime = cl.time;
843                 e->startframe = startframe;
844                 e->endframe = startframe + framecount;
845                 e->framerate = framerate;
846
847                 e->frame = 0;
848                 e->frame1time = cl.time;
849                 e->frame2time = cl.time;
850                 break;
851         }
852 }
853
854 static void CL_RelinkEffects(void)
855 {
856         int i, intframe;
857         cl_effect_t *e;
858         entity_t *ent;
859         float frame;
860
861         for (i = 0, e = cl_effects;i < cl_max_effects;i++, e++)
862         {
863                 if (e->active)
864                 {
865                         frame = (cl.time - e->starttime) * e->framerate + e->startframe;
866                         intframe = frame;
867                         if (intframe < 0 || intframe >= e->endframe)
868                         {
869                                 e->active = false;
870                                 memset(e, 0, sizeof(*e));
871                                 continue;
872                         }
873
874                         if (intframe != e->frame)
875                         {
876                                 e->frame = intframe;
877                                 e->frame1time = e->frame2time;
878                                 e->frame2time = cl.time;
879                         }
880
881                         // if we're drawing effects, get a new temp entity
882                         // (NewTempEntity adds it to the render entities list for us)
883                         if (r_draweffects.integer && (ent = CL_NewTempEntity()))
884                         {
885                                 // interpolation stuff
886                                 ent->render.frame1 = intframe;
887                                 ent->render.frame2 = intframe + 1;
888                                 if (ent->render.frame2 >= e->endframe)
889                                         ent->render.frame2 = -1; // disappear
890                                 ent->render.framelerp = frame - intframe;
891                                 ent->render.frame1time = e->frame1time;
892                                 ent->render.frame2time = e->frame2time;
893
894                                 // normal stuff
895                                 //VectorCopy(e->origin, ent->render.origin);
896                                 ent->render.model = cl.model_precache[e->modelindex];
897                                 ent->render.frame = ent->render.frame2;
898                                 ent->render.colormap = -1; // no special coloring
899                                 //ent->render.scale = 1;
900                                 ent->render.alpha = 1;
901
902                                 Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1);
903                                 Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
904                                 CL_BoundingBoxForEntity(&ent->render);
905                         }
906                 }
907         }
908 }
909
910 void CL_RelinkBeams (void)
911 {
912         int i;
913         beam_t *b;
914         vec3_t dist, org;
915         float d;
916         entity_t *ent;
917         float yaw, pitch;
918         float forward;
919
920         for (i = 0, b = cl_beams;i < cl_max_beams;i++, b++)
921         {
922                 if (!b->model || b->endtime < cl.time)
923                         continue;
924
925                 // if coming from the player, update the start position
926                 //if (b->entity == cl.viewentity)
927                 //      VectorCopy (cl_entities[cl.viewentity].render.origin, b->start);
928                 if (cl_beams_relative.integer && b->entity && cl_entities[b->entity].state_current.active && b->relativestartvalid)
929                 {
930                         entity_state_t *p = &cl_entities[b->entity].state_previous;
931                         //entity_state_t *c = &cl_entities[b->entity].state_current;
932                         entity_render_t *r = &cl_entities[b->entity].render;
933                         matrix4x4_t matrix, imatrix;
934                         if (b->relativestartvalid == 2)
935                         {
936                                 // not really valid yet, we need to get the orientation now
937                                 // (ParseBeam flagged this because it is received before
938                                 //  entities are received, by now they have been received)
939                                 // note: because players create lightning in their think
940                                 // function (which occurs before movement), they actually
941                                 // have some lag in it's location, so compare to the
942                                 // previous player state, not the latest
943                                 if (b->entity == cl.viewentity)
944                                         Matrix4x4_CreateFromQuakeEntity(&matrix, p->origin[0], p->origin[1], p->origin[2] + 16, cl.viewangles[0], cl.viewangles[1], cl.viewangles[2], 1);
945                                 else
946                                         Matrix4x4_CreateFromQuakeEntity(&matrix, p->origin[0], p->origin[1], p->origin[2] + 16, p->angles[0], p->angles[1], p->angles[2], 1);
947                                 Matrix4x4_Invert_Simple(&imatrix, &matrix);
948                                 Matrix4x4_Transform(&imatrix, b->start, b->relativestart);
949                                 Matrix4x4_Transform(&imatrix, b->end, b->relativeend);
950                                 b->relativestartvalid = 1;
951                         }
952                         else
953                         {
954                                 if (b->entity == cl.viewentity)
955                                         Matrix4x4_CreateFromQuakeEntity(&matrix, r->origin[0], r->origin[1], r->origin[2] + 16, cl.viewangles[0], cl.viewangles[1], cl.viewangles[2], 1);
956                                 else
957                                         Matrix4x4_CreateFromQuakeEntity(&matrix, r->origin[0], r->origin[1], r->origin[2] + 16, r->angles[0], r->angles[1], r->angles[2], 1);
958                                 Matrix4x4_Transform(&matrix, b->relativestart, b->start);
959                                 Matrix4x4_Transform(&matrix, b->relativeend, b->end);
960                         }
961                 }
962
963                 if (b->lightning)
964                 {
965                         if (cl_beams_lightatend.integer)
966                                 CL_AllocDlight (NULL, b->end, 200, 0.3, 0.7, 1, 0, 0);
967                         if (cl_beams_polygons.integer)
968                                 continue;
969                 }
970
971                 // calculate pitch and yaw
972                 VectorSubtract (b->end, b->start, dist);
973
974                 if (dist[1] == 0 && dist[0] == 0)
975                 {
976                         yaw = 0;
977                         if (dist[2] > 0)
978                                 pitch = 90;
979                         else
980                                 pitch = 270;
981                 }
982                 else
983                 {
984                         yaw = (int) (atan2(dist[1], dist[0]) * 180 / M_PI);
985                         if (yaw < 0)
986                                 yaw += 360;
987
988                         forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]);
989                         pitch = (int) (atan2(dist[2], forward) * 180 / M_PI);
990                         if (pitch < 0)
991                                 pitch += 360;
992                 }
993
994                 // add new entities for the lightning
995                 VectorCopy (b->start, org);
996                 d = VectorNormalizeLength(dist);
997                 while (d > 0)
998                 {
999                         ent = CL_NewTempEntity ();
1000                         if (!ent)
1001                                 return;
1002                         //VectorCopy (org, ent->render.origin);
1003                         ent->render.model = b->model;
1004                         ent->render.effects = EF_FULLBRIGHT;
1005                         //ent->render.angles[0] = pitch;
1006                         //ent->render.angles[1] = yaw;
1007                         //ent->render.angles[2] = rand()%360;
1008                         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1);
1009                         Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
1010                         CL_BoundingBoxForEntity(&ent->render);
1011                         VectorMA(org, 30, dist, org);
1012                         d -= 30;
1013                 }
1014         }
1015 }
1016
1017 cvar_t r_lightningbeam_thickness = {CVAR_SAVE, "r_lightningbeam_thickness", "4"};
1018 cvar_t r_lightningbeam_scroll = {CVAR_SAVE, "r_lightningbeam_scroll", "5"};
1019 cvar_t r_lightningbeam_repeatdistance = {CVAR_SAVE, "r_lightningbeam_repeatdistance", "1024"};
1020 cvar_t r_lightningbeam_color_red = {CVAR_SAVE, "r_lightningbeam_color_red", "1"};
1021 cvar_t r_lightningbeam_color_green = {CVAR_SAVE, "r_lightningbeam_color_green", "1"};
1022 cvar_t r_lightningbeam_color_blue = {CVAR_SAVE, "r_lightningbeam_color_blue", "1"};
1023 cvar_t r_lightningbeam_qmbtexture = {CVAR_SAVE, "r_lightningbeam_qmbtexture", "0"};
1024
1025 rtexture_t *r_lightningbeamtexture;
1026 rtexture_t *r_lightningbeamqmbtexture;
1027 rtexturepool_t *r_lightningbeamtexturepool;
1028
1029 int r_lightningbeamelements[18] = {0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11};
1030
1031 void r_lightningbeams_start(void)
1032 {
1033         r_lightningbeamtexturepool = R_AllocTexturePool();
1034         r_lightningbeamtexture = NULL;
1035         r_lightningbeamqmbtexture = NULL;
1036 }
1037
1038 void r_lightningbeams_setupqmbtexture(void)
1039 {
1040         r_lightningbeamqmbtexture = loadtextureimage(r_lightningbeamtexturepool, "textures/particles/lightning.pcx", 0, 0, false, TEXF_ALPHA | TEXF_PRECACHE);
1041         if (r_lightningbeamqmbtexture == NULL)
1042                 Cvar_SetValueQuick(&r_lightningbeam_qmbtexture, false);
1043 }
1044
1045 void r_lightningbeams_setuptexture(void)
1046 {
1047 #if 0
1048 #define BEAMWIDTH 128
1049 #define BEAMHEIGHT 64
1050 #define PATHPOINTS 8
1051         int i, j, px, py, nearestpathindex, imagenumber;
1052         float particlex, particley, particlexv, particleyv, dx, dy, s, maxpathstrength;
1053         qbyte *pixels;
1054         int *image;
1055         struct {float x, y, strength;} path[PATHPOINTS], temppath;
1056
1057         image = Mem_Alloc(tempmempool, BEAMWIDTH * BEAMHEIGHT * sizeof(int));
1058         pixels = Mem_Alloc(tempmempool, BEAMWIDTH * BEAMHEIGHT * sizeof(qbyte[4]));
1059
1060         for (imagenumber = 0, maxpathstrength = 0.0339476;maxpathstrength < 0.5;imagenumber++, maxpathstrength += 0.01)
1061         {
1062         for (i = 0;i < PATHPOINTS;i++)
1063         {
1064                 path[i].x = lhrandom(0, 1);
1065                 path[i].y = lhrandom(0.2, 0.8);
1066                 path[i].strength = lhrandom(0, 1);
1067         }
1068         for (i = 0;i < PATHPOINTS;i++)
1069         {
1070                 for (j = i + 1;j < PATHPOINTS;j++)
1071                 {
1072                         if (path[j].x < path[i].x)
1073                         {
1074                                 temppath = path[j];
1075                                 path[j] = path[i];
1076                                 path[i] = temppath;
1077                         }
1078                 }
1079         }
1080         particlex = path[0].x;
1081         particley = path[0].y;
1082         particlexv = lhrandom(0, 0.02);
1083         particlexv = lhrandom(-0.02, 0.02);
1084         memset(image, 0, BEAMWIDTH * BEAMHEIGHT * sizeof(int));
1085         for (i = 0;i < 65536;i++)
1086         {
1087                 for (nearestpathindex = 0;nearestpathindex < PATHPOINTS;nearestpathindex++)
1088                         if (path[nearestpathindex].x > particlex)
1089                                 break;
1090                 nearestpathindex %= PATHPOINTS;
1091                 dx = path[nearestpathindex].x + lhrandom(-0.01, 0.01);dx = bound(0, dx, 1) - particlex;if (dx < 0) dx += 1;
1092                 dy = path[nearestpathindex].y + lhrandom(-0.01, 0.01);dy = bound(0, dy, 1) - particley;
1093                 s = path[nearestpathindex].strength / sqrt(dx*dx+dy*dy);
1094                 particlexv = particlexv /* (1 - lhrandom(0.08, 0.12))*/ + dx * s;
1095                 particleyv = particleyv /* (1 - lhrandom(0.08, 0.12))*/ + dy * s;
1096                 particlex += particlexv * maxpathstrength;particlex -= (int) particlex;
1097                 particley += particleyv * maxpathstrength;particley = bound(0, particley, 1);
1098                 px = particlex * BEAMWIDTH;
1099                 py = particley * BEAMHEIGHT;
1100                 if (px >= 0 && py >= 0 && px < BEAMWIDTH && py < BEAMHEIGHT)
1101                         image[py*BEAMWIDTH+px] += 16;
1102         }
1103
1104         for (py = 0;py < BEAMHEIGHT;py++)
1105         {
1106                 for (px = 0;px < BEAMWIDTH;px++)
1107                 {
1108                         pixels[(py*BEAMWIDTH+px)*4+0] = bound(0, image[py*BEAMWIDTH+px] * 1.0f, 255.0f);
1109                         pixels[(py*BEAMWIDTH+px)*4+1] = bound(0, image[py*BEAMWIDTH+px] * 1.0f, 255.0f);
1110                         pixels[(py*BEAMWIDTH+px)*4+2] = bound(0, image[py*BEAMWIDTH+px] * 1.0f, 255.0f);
1111                         pixels[(py*BEAMWIDTH+px)*4+3] = 255;
1112                 }
1113         }
1114
1115         Image_WriteTGARGBA(va("lightningbeam%i.tga", imagenumber), BEAMWIDTH, BEAMHEIGHT, pixels);
1116         }
1117
1118         r_lightningbeamtexture = R_LoadTexture2D(r_lightningbeamtexturepool, "lightningbeam", BEAMWIDTH, BEAMHEIGHT, pixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
1119
1120         Mem_Free(pixels);
1121         Mem_Free(image);
1122 #else
1123 #define BEAMWIDTH 64
1124 #define BEAMHEIGHT 128
1125         float r, g, b, intensity, fx, width, center;
1126         int x, y;
1127         qbyte *data, *noise1, *noise2;
1128
1129         data = Mem_Alloc(tempmempool, BEAMWIDTH * BEAMHEIGHT * 4);
1130         noise1 = Mem_Alloc(tempmempool, BEAMHEIGHT * BEAMHEIGHT);
1131         noise2 = Mem_Alloc(tempmempool, BEAMHEIGHT * BEAMHEIGHT);
1132         fractalnoise(noise1, BEAMHEIGHT, BEAMHEIGHT / 8);
1133         fractalnoise(noise2, BEAMHEIGHT, BEAMHEIGHT / 16);
1134
1135         for (y = 0;y < BEAMHEIGHT;y++)
1136         {
1137                 width = 0.15;//((noise1[y * BEAMHEIGHT] * (1.0f / 256.0f)) * 0.1f + 0.1f);
1138                 center = (noise1[y * BEAMHEIGHT + (BEAMHEIGHT / 2)] / 256.0f) * (1.0f - width * 2.0f) + width;
1139                 for (x = 0;x < BEAMWIDTH;x++, fx++)
1140                 {
1141                         fx = (((float) x / BEAMWIDTH) - center) / width;
1142                         intensity = 1.0f - sqrt(fx * fx);
1143                         if (intensity > 0)
1144                                 intensity = pow(intensity, 2) * ((noise2[y * BEAMHEIGHT + x] * (1.0f / 256.0f)) * 0.33f + 0.66f);
1145                         intensity = bound(0, intensity, 1);
1146                         r = intensity * 1.0f;
1147                         g = intensity * 1.0f;
1148                         b = intensity * 1.0f;
1149                         data[(y * BEAMWIDTH + x) * 4 + 0] = (qbyte)(bound(0, r, 1) * 255.0f);
1150                         data[(y * BEAMWIDTH + x) * 4 + 1] = (qbyte)(bound(0, g, 1) * 255.0f);
1151                         data[(y * BEAMWIDTH + x) * 4 + 2] = (qbyte)(bound(0, b, 1) * 255.0f);
1152                         data[(y * BEAMWIDTH + x) * 4 + 3] = (qbyte)255;
1153                 }
1154         }
1155
1156         r_lightningbeamtexture = R_LoadTexture2D(r_lightningbeamtexturepool, "lightningbeam", BEAMWIDTH, BEAMHEIGHT, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
1157         Mem_Free(noise1);
1158         Mem_Free(noise2);
1159         Mem_Free(data);
1160 #endif
1161 }
1162
1163 void r_lightningbeams_shutdown(void)
1164 {
1165         r_lightningbeamtexture = NULL;
1166         r_lightningbeamqmbtexture = NULL;
1167         R_FreeTexturePool(&r_lightningbeamtexturepool);
1168 }
1169
1170 void r_lightningbeams_newmap(void)
1171 {
1172 }
1173
1174 void R_LightningBeams_Init(void)
1175 {
1176         Cvar_RegisterVariable(&r_lightningbeam_thickness);
1177         Cvar_RegisterVariable(&r_lightningbeam_scroll);
1178         Cvar_RegisterVariable(&r_lightningbeam_repeatdistance);
1179         Cvar_RegisterVariable(&r_lightningbeam_color_red);
1180         Cvar_RegisterVariable(&r_lightningbeam_color_green);
1181         Cvar_RegisterVariable(&r_lightningbeam_color_blue);
1182         Cvar_RegisterVariable(&r_lightningbeam_qmbtexture);
1183         R_RegisterModule("R_LightningBeams", r_lightningbeams_start, r_lightningbeams_shutdown, r_lightningbeams_newmap);
1184 }
1185
1186 void R_CalcLightningBeamPolygonVertex3f(float *v, const float *start, const float *end, const float *offset)
1187 {
1188         // near right corner
1189         VectorAdd     (start, offset, (v + 0));
1190         // near left corner
1191         VectorSubtract(start, offset, (v + 3));
1192         // far left corner
1193         VectorSubtract(end  , offset, (v + 6));
1194         // far right corner
1195         VectorAdd     (end  , offset, (v + 9));
1196 }
1197
1198 void R_CalcLightningBeamPolygonTexCoord2f(float *tc, float t1, float t2)
1199 {
1200         if (r_lightningbeam_qmbtexture.integer)
1201         {
1202                 // near right corner
1203                 tc[0] = t1;tc[1] = 0;
1204                 // near left corner
1205                 tc[2] = t1;tc[3] = 1;
1206                 // far left corner
1207                 tc[4] = t2;tc[5] = 1;
1208                 // far right corner
1209                 tc[6] = t2;tc[7] = 0;
1210         }
1211         else
1212         {
1213                 // near right corner
1214                 tc[0] = 0;tc[1] = t1;
1215                 // near left corner
1216                 tc[2] = 1;tc[3] = t1;
1217                 // far left corner
1218                 tc[4] = 1;tc[5] = t2;
1219                 // far right corner
1220                 tc[6] = 0;tc[7] = t2;
1221         }
1222 }
1223
1224 void R_FogLightningBeam_Vertex3f_Color4f(const float *v, float *c, int numverts, float r, float g, float b, float a)
1225 {
1226         int i;
1227         vec3_t fogvec;
1228         float ifog;
1229         for (i = 0;i < numverts;i++, v += 3, c += 4)
1230         {
1231                 VectorSubtract(v, r_origin, fogvec);
1232                 ifog = 1 - exp(fogdensity/DotProduct(fogvec,fogvec));
1233                 c[0] = r * ifog;
1234                 c[1] = g * ifog;
1235                 c[2] = b * ifog;
1236                 c[3] = a;
1237         }
1238 }
1239
1240 float beamrepeatscale;
1241
1242 void R_DrawLightningBeamCallback(const void *calldata1, int calldata2)
1243 {
1244         const beam_t *b = calldata1;
1245         rmeshstate_t m;
1246         vec3_t beamdir, right, up, offset;
1247         float length, t1, t2;
1248         memset(&m, 0, sizeof(m));
1249         m.blendfunc1 = GL_SRC_ALPHA;
1250         m.blendfunc2 = GL_ONE;
1251         if (r_lightningbeam_qmbtexture.integer && r_lightningbeamqmbtexture == NULL)
1252                 r_lightningbeams_setupqmbtexture();
1253         if (!r_lightningbeam_qmbtexture.integer && r_lightningbeamtexture == NULL)
1254                 r_lightningbeams_setuptexture();
1255         if (r_lightningbeam_qmbtexture.integer)
1256                 m.tex[0] = R_GetTexture(r_lightningbeamqmbtexture);
1257         else
1258                 m.tex[0] = R_GetTexture(r_lightningbeamtexture);
1259         R_Mesh_State(&m);
1260         R_Mesh_Matrix(&r_identitymatrix);
1261
1262         // calculate beam direction (beamdir) vector and beam length
1263         // get difference vector
1264         VectorSubtract(b->end, b->start, beamdir);
1265         // find length of difference vector
1266         length = sqrt(DotProduct(beamdir, beamdir));
1267         // calculate scale to make beamdir a unit vector (normalized)
1268         t1 = 1.0f / length;
1269         // scale beamdir so it is now normalized
1270         VectorScale(beamdir, t1, beamdir);
1271
1272         // calculate up vector such that it points toward viewer, and rotates around the beamdir
1273         // get direction from start of beam to viewer
1274         VectorSubtract(r_origin, b->start, up);
1275         // remove the portion of the vector that moves along the beam
1276         // (this leaves only a vector pointing directly away from the beam)
1277         t1 = -DotProduct(up, beamdir);
1278         VectorMA(up, t1, beamdir, up);
1279         // now we have a vector pointing away from the beam, now we need to normalize it
1280         VectorNormalizeFast(up);
1281         // generate right vector from forward and up, the result is already normalized
1282         // (CrossProduct returns a vector of multiplied length of the two inputs)
1283         CrossProduct(beamdir, up, right);
1284
1285         // calculate T coordinate scrolling (start and end texcoord along the beam)
1286         t1 = cl.time * -r_lightningbeam_scroll.value;// + beamrepeatscale * DotProduct(b->start, beamdir);
1287         t1 = t1 - (int) t1;
1288         t2 = t1 + beamrepeatscale * length;
1289
1290         // the beam is 3 polygons in this configuration:
1291         //  *   2
1292         //   * *
1293         // 1******
1294         //   * *
1295         //  *   3
1296         // they are showing different portions of the beam texture, creating an
1297         // illusion of a beam that appears to curl around in 3D space
1298         // (and realize that the whole polygon assembly orients itself to face
1299         //  the viewer)
1300
1301         R_Mesh_GetSpace(12);
1302
1303         // polygon 1, verts 0-3
1304         VectorScale(right, r_lightningbeam_thickness.value, offset);
1305         R_CalcLightningBeamPolygonVertex3f(varray_vertex3f, b->start, b->end, offset);
1306         R_CalcLightningBeamPolygonTexCoord2f(varray_texcoord2f[0], t1, t2);
1307
1308         // polygon 2, verts 4-7
1309         VectorAdd(right, up, offset);
1310         VectorScale(offset, r_lightningbeam_thickness.value * 0.70710681f, offset);
1311         R_CalcLightningBeamPolygonVertex3f(varray_vertex3f + 12, b->start, b->end, offset);
1312         R_CalcLightningBeamPolygonTexCoord2f(varray_texcoord2f[0] + 8, t1 + 0.33, t2 + 0.33);
1313
1314         // polygon 3, verts 8-11
1315         VectorSubtract(right, up, offset);
1316         VectorScale(offset, r_lightningbeam_thickness.value * 0.70710681f, offset);
1317         R_CalcLightningBeamPolygonVertex3f(varray_vertex3f + 24, b->start, b->end, offset);
1318         R_CalcLightningBeamPolygonTexCoord2f(varray_texcoord2f[0] + 16, t1 + 0.66, t2 + 0.66);
1319
1320         if (fogenabled)
1321         {
1322                 // per vertex colors if fog is used
1323                 GL_UseColorArray();
1324                 R_FogLightningBeam_Vertex3f_Color4f(varray_vertex3f, varray_color4f, 12, r_lightningbeam_color_red.value, r_lightningbeam_color_green.value, r_lightningbeam_color_blue.value, 1);
1325         }
1326         else
1327         {
1328                 // solid color if fog is not used
1329                 GL_Color(r_lightningbeam_color_red.value, r_lightningbeam_color_green.value, r_lightningbeam_color_blue.value, 1);
1330         }
1331
1332         // draw the 3 polygons as one batch of 6 triangles using the 12 vertices
1333         R_Mesh_Draw(12, 6, r_lightningbeamelements);
1334 }
1335
1336 void R_DrawLightningBeams (void)
1337 {
1338         int i;
1339         beam_t *b;
1340         vec3_t org;
1341
1342         if (!cl_beams_polygons.integer)
1343                 return;
1344
1345         beamrepeatscale = 1.0f / r_lightningbeam_repeatdistance.value;
1346         for (i = 0, b = cl_beams;i < cl_max_beams;i++, b++)
1347         {
1348                 if (b->model && b->endtime >= cl.time && b->lightning)
1349                 {
1350                         VectorAdd(b->start, b->end, org);
1351                         VectorScale(org, 0.5f, org);
1352                         R_MeshQueue_AddTransparent(org, R_DrawLightningBeamCallback, b, 0);
1353                 }
1354         }
1355 }
1356
1357
1358 void CL_LerpPlayer(float frac)
1359 {
1360         int i;
1361         float d;
1362
1363         cl.viewzoom = cl.viewzoomold + frac * (cl.viewzoomnew - cl.viewzoomold);
1364
1365         for (i = 0;i < 3;i++)
1366                 cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
1367
1368         if (cls.demoplayback)
1369         {
1370                 // interpolate the angles
1371                 for (i = 0;i < 3;i++)
1372                 {
1373                         d = cl.mviewangles[0][i] - cl.mviewangles[1][i];
1374                         if (d > 180)
1375                                 d -= 360;
1376                         else if (d < -180)
1377                                 d += 360;
1378                         cl.viewangles[i] = cl.mviewangles[1][i] + frac * d;
1379                 }
1380         }
1381 }
1382
1383 void CL_RelinkEntities (void)
1384 {
1385         float frac;
1386
1387         // fraction from previous network update to current
1388         frac = CL_LerpPoint();
1389
1390         CL_ClearTempEntities();
1391         CL_DecayLights();
1392         CL_RelinkWorld();
1393         CL_RelinkStaticEntities();
1394         CL_RelinkNetworkEntities();
1395         CL_RelinkEffects();
1396         CL_MoveParticles();
1397
1398         CL_LerpPlayer(frac);
1399
1400         CL_RelinkBeams();
1401 }
1402
1403
1404 /*
1405 ===============
1406 CL_ReadFromServer
1407
1408 Read all incoming data from the server
1409 ===============
1410 */
1411 int CL_ReadFromServer (void)
1412 {
1413         int ret, netshown;
1414
1415         cl.oldtime = cl.time;
1416         cl.time += cl.frametime;
1417
1418         netshown = false;
1419         do
1420         {
1421                 ret = CL_GetMessage ();
1422                 if (ret == -1)
1423                         Host_Error ("CL_ReadFromServer: lost server connection");
1424                 if (!ret)
1425                         break;
1426
1427                 cl.last_received_message = realtime;
1428
1429                 if (cl_shownet.integer)
1430                         netshown = true;
1431
1432                 CL_ParseServerMessage ();
1433         }
1434         while (ret && cls.state == ca_connected);
1435
1436         if (netshown)
1437                 Con_Printf ("\n");
1438
1439         r_refdef.numentities = 0;
1440         cl_num_entities = 0;
1441         cl_num_brushmodel_entities = 0;
1442
1443         if (cls.state == ca_connected && cls.signon == SIGNONS)
1444         {
1445                 CL_RelinkEntities ();
1446
1447                 // run cgame code (which can add more entities)
1448                 CL_CGVM_Frame();
1449         }
1450
1451 //
1452 // bring the links up to date
1453 //
1454         return 0;
1455 }
1456
1457 /*
1458 =================
1459 CL_SendCmd
1460 =================
1461 */
1462 void CL_SendCmd (void)
1463 {
1464         usercmd_t               cmd;
1465
1466         if (cls.state != ca_connected)
1467                 return;
1468
1469         if (cls.signon == SIGNONS)
1470         {
1471         // get basic movement from keyboard
1472                 CL_BaseMove (&cmd);
1473
1474                 IN_PreMove(); // OS independent code
1475
1476         // allow mice or other external controllers to add to the move
1477                 IN_Move (&cmd);
1478
1479                 IN_PostMove(); // OS independent code
1480
1481         // send the unreliable message
1482                 CL_SendMove (&cmd);
1483         }
1484         else if (cls.signon == 0 && !cls.demoplayback)
1485         {
1486                 // LordHavoc: fix for NAT routing of netquake:
1487                 // bounce back a clc_nop message to the newly allocated server port,
1488                 // to establish a routing connection for incoming frames,
1489                 // the server waits for this before sending anything
1490                 if (realtime > cl.sendnoptime)
1491                 {
1492                         cl.sendnoptime = realtime + 3;
1493                         Con_DPrintf("sending clc_nop to get server's attention\n");
1494                         {
1495                                 sizebuf_t buf;
1496                                 qbyte data[128];
1497                                 buf.maxsize = 128;
1498                                 buf.cursize = 0;
1499                                 buf.data = data;
1500                                 MSG_WriteByte(&buf, clc_nop);
1501                                 if (NET_SendUnreliableMessage (cls.netcon, &buf) == -1)
1502                                 {
1503                                         Con_Printf ("CL_SendCmd: lost server connection\n");
1504                                         CL_Disconnect ();
1505                                 }
1506                         }
1507                 }
1508         }
1509
1510         if (cls.demoplayback)
1511         {
1512                 SZ_Clear (&cls.message);
1513                 return;
1514         }
1515
1516 // send the reliable message
1517         if (!cls.message.cursize)
1518                 return;         // no message at all
1519
1520         if (!NET_CanSendMessage (cls.netcon))
1521         {
1522                 Con_DPrintf ("CL_WriteToServer: can't send\n");
1523                 if (developer.integer)
1524                         SZ_HexDumpToConsole(&cls.message);
1525                 return;
1526         }
1527
1528         if (NET_SendMessage (cls.netcon, &cls.message) == -1)
1529                 Host_Error ("CL_WriteToServer: lost server connection");
1530
1531         SZ_Clear (&cls.message);
1532 }
1533
1534 // LordHavoc: pausedemo command
1535 static void CL_PauseDemo_f (void)
1536 {
1537         cls.demopaused = !cls.demopaused;
1538         if (cls.demopaused)
1539                 Con_Printf("Demo paused\n");
1540         else
1541                 Con_Printf("Demo unpaused\n");
1542 }
1543
1544 /*
1545 ======================
1546 CL_PModel_f
1547 LordHavoc: Intended for Nehahra, I personally think this is dumb, but Mindcrime won't listen.
1548 ======================
1549 */
1550 static void CL_PModel_f (void)
1551 {
1552         int i;
1553         eval_t *val;
1554
1555         if (Cmd_Argc () == 1)
1556         {
1557                 Con_Printf ("\"pmodel\" is \"%s\"\n", cl_pmodel.string);
1558                 return;
1559         }
1560         i = atoi(Cmd_Argv(1));
1561
1562         if (cmd_source == src_command)
1563         {
1564                 if (cl_pmodel.integer == i)
1565                         return;
1566                 Cvar_SetValue ("_cl_pmodel", i);
1567                 if (cls.state == ca_connected)
1568                         Cmd_ForwardToServer ();
1569                 return;
1570         }
1571
1572         host_client->pmodel = i;
1573         if ((val = GETEDICTFIELDVALUE(sv_player, eval_pmodel)))
1574                 val->_float = i;
1575 }
1576
1577 /*
1578 ======================
1579 CL_Fog_f
1580 ======================
1581 */
1582 static void CL_Fog_f (void)
1583 {
1584         if (Cmd_Argc () == 1)
1585         {
1586                 Con_Printf ("\"fog\" is \"%f %f %f %f\"\n", fog_density, fog_red, fog_green, fog_blue);
1587                 return;
1588         }
1589         fog_density = atof(Cmd_Argv(1));
1590         fog_red = atof(Cmd_Argv(2));
1591         fog_green = atof(Cmd_Argv(3));
1592         fog_blue = atof(Cmd_Argv(4));
1593 }
1594
1595 /*
1596 =================
1597 CL_Init
1598 =================
1599 */
1600 void CL_Init (void)
1601 {
1602         cl_scores_mempool = Mem_AllocPool("client player info");
1603         cl_entities_mempool = Mem_AllocPool("client entities");
1604         cl_refdef_mempool = Mem_AllocPool("refdef");
1605
1606         memset(&r_refdef, 0, sizeof(r_refdef));
1607         // max entities sent to renderer per frame
1608         r_refdef.maxentities = MAX_EDICTS + 256 + 512;
1609         r_refdef.entities = Mem_Alloc(cl_refdef_mempool, sizeof(entity_render_t *) * r_refdef.maxentities);
1610         // 256k drawqueue buffer
1611         r_refdef.maxdrawqueuesize = 256 * 1024;
1612         r_refdef.drawqueue = Mem_Alloc(cl_refdef_mempool, r_refdef.maxdrawqueuesize);
1613
1614         SZ_Alloc (&cls.message, 1024, "cls.message");
1615
1616         CL_InitInput ();
1617         CL_InitTEnts ();
1618
1619 //
1620 // register our commands
1621 //
1622         Cvar_RegisterVariable (&cl_name);
1623         Cvar_RegisterVariable (&cl_color);
1624         if (gamemode == GAME_NEHAHRA)
1625                 Cvar_RegisterVariable (&cl_pmodel);
1626         Cvar_RegisterVariable (&cl_upspeed);
1627         Cvar_RegisterVariable (&cl_forwardspeed);
1628         Cvar_RegisterVariable (&cl_backspeed);
1629         Cvar_RegisterVariable (&cl_sidespeed);
1630         Cvar_RegisterVariable (&cl_movespeedkey);
1631         Cvar_RegisterVariable (&cl_yawspeed);
1632         Cvar_RegisterVariable (&cl_pitchspeed);
1633         Cvar_RegisterVariable (&cl_anglespeedkey);
1634         Cvar_RegisterVariable (&cl_shownet);
1635         Cvar_RegisterVariable (&cl_nolerp);
1636         Cvar_RegisterVariable (&lookspring);
1637         Cvar_RegisterVariable (&lookstrafe);
1638         Cvar_RegisterVariable (&sensitivity);
1639         Cvar_RegisterVariable (&freelook);
1640
1641         Cvar_RegisterVariable (&m_pitch);
1642         Cvar_RegisterVariable (&m_yaw);
1643         Cvar_RegisterVariable (&m_forward);
1644         Cvar_RegisterVariable (&m_side);
1645
1646         Cvar_RegisterVariable (&cl_itembobspeed);
1647         Cvar_RegisterVariable (&cl_itembobheight);
1648
1649         Cmd_AddCommand ("entities", CL_PrintEntities_f);
1650         Cmd_AddCommand ("disconnect", CL_Disconnect_f);
1651         Cmd_AddCommand ("record", CL_Record_f);
1652         Cmd_AddCommand ("stop", CL_Stop_f);
1653         Cmd_AddCommand ("playdemo", CL_PlayDemo_f);
1654         Cmd_AddCommand ("timedemo", CL_TimeDemo_f);
1655
1656         Cmd_AddCommand ("fog", CL_Fog_f);
1657
1658         // LordHavoc: added pausedemo
1659         Cmd_AddCommand ("pausedemo", CL_PauseDemo_f);
1660         if (gamemode == GAME_NEHAHRA)
1661                 Cmd_AddCommand ("pmodel", CL_PModel_f);
1662
1663         Cvar_RegisterVariable(&r_draweffects);
1664         Cvar_RegisterVariable(&cl_explosions);
1665         Cvar_RegisterVariable(&cl_stainmaps);
1666         Cvar_RegisterVariable(&cl_beams_polygons);
1667         Cvar_RegisterVariable(&cl_beams_relative);
1668         Cvar_RegisterVariable(&cl_beams_lightatend);
1669         Cvar_RegisterVariable(&cl_noplayershadow);
1670
1671         R_LightningBeams_Init();
1672
1673         CL_Parse_Init();
1674         CL_Particles_Init();
1675         CL_Screen_Init();
1676         CL_CGVM_Init();
1677
1678         CL_Video_Init();
1679 }
1680