r_main.c 27.1 KB
Newer Older
Tyrann's avatar
Tyrann committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
Copyright (C) 1996-1997 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
// r_main.c

22
23
#include <stdint.h>

Tyrann's avatar
Tyrann committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "cmd.h"
#include "console.h"
#include "quakedef.h"
#include "r_local.h"
#include "screen.h"
#include "sound.h"
#include "sys.h"
#include "view.h"

void *colormap;
float r_time1;
int r_numallocatededges;

qboolean r_recursiveaffinetriangles = true;

int r_pixbytes = 1;
float r_aliasuvscale = 1.0;
int r_outofsurfaces;
int r_outofedges;

static vec3_t viewlightvec;
static alight_t r_viewlighting = { 128, 192, viewlightvec };

qboolean r_dowarp, r_dowarpold, r_viewchanged;

mvertex_t *r_pcurrentvertbase;

int c_surf;
int r_maxsurfsseen, r_maxedgesseen;

static int r_cnumsurfs;
static qboolean r_surfsonstack;

byte *r_warpbuffer;

static byte *r_stack_start;

Tyrann's avatar
Tyrann committed
61
62
entity_t r_worldentity;

Tyrann's avatar
Tyrann committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//
// view origin
//
vec3_t vup, base_vup;
vec3_t vpn, base_vpn;
vec3_t vright, base_vright;
vec3_t r_origin;

//
// screen size info
//
refdef_t r_refdef;
float xcenter, ycenter;
float xscale, yscale;
float xscaleinv, yscaleinv;
float xscaleshrink, yscaleshrink;
float aliasxscale, aliasyscale, aliasxcenter, aliasycenter;

int screenwidth;

float pixelAspect;
static float screenAspect;
static float verticalFieldOfView;
static float xOrigin, yOrigin;

mplane_t screenedge[4];

//
// refresh flags
//
int r_framecount = 1;		// so frame counts initialized to 0 don't match
int r_visframecount;
int r_polycount;
int r_drawnpolycount;

mleaf_t *r_viewleaf, *r_oldviewleaf;

texture_t *r_notexture_mip;

float r_aliastransition, r_resfudge;

int d_lightstylevalue[256];	// 8.8 fraction of base light value

cvar_t r_draworder = { "r_draworder", "0" };
cvar_t r_speeds = { "r_speeds", "0" };
108
cvar_t r_graphheight = { "r_graphheight", "15" };
Tyrann's avatar
Tyrann committed
109
110
111
112
113
114
115
116
117
118
119
cvar_t r_clearcolor = { "r_clearcolor", "2" };
cvar_t r_waterwarp = { "r_waterwarp", "1" };
cvar_t r_drawentities = { "r_drawentities", "1" };
cvar_t r_drawviewmodel = { "r_drawviewmodel", "1" };
cvar_t r_ambient = { "r_ambient", "0" };
cvar_t r_numsurfs = { "r_numsurfs", "0" };
cvar_t r_numedges = { "r_numedges", "0" };

cvar_t r_lockpvs = { "r_lockpvs", "0" };
cvar_t r_lockfrustum = { "r_lockfrustum", "0" };

twinaphex's avatar
twinaphex committed
120
cvar_t r_fullbright = { "r_fullbright", "0" };
Tyrann's avatar
Tyrann committed
121

122
123
124
125
126
#ifdef QW_HACK
cvar_t r_netgraph = { "r_netgraph", "0" };
static cvar_t r_zgraph = { "r_zgraph", "0" };
#endif

Tyrann's avatar
Tyrann committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
static cvar_t r_timegraph = { "r_timegraph", "0" };
static cvar_t r_aliasstats = { "r_polymodelstats", "0" };
static cvar_t r_dspeeds = { "r_dspeeds", "0" };
static cvar_t r_reportsurfout = { "r_reportsurfout", "0" };
static cvar_t r_maxsurfs = { "r_maxsurfs", "0" };
static cvar_t r_reportedgeout = { "r_reportedgeout", "0" };
static cvar_t r_maxedges = { "r_maxedges", "0" };
static cvar_t r_aliastransbase = { "r_aliastransbase", "200" };
static cvar_t r_aliastransadj = { "r_aliastransadj", "100" };

/*
==================
R_InitTextures
==================
*/
void
R_InitTextures(void)
{
    int x, y, m;
    byte *dest;

// create a simple checkerboard texture for the default
twinaphex's avatar
twinaphex committed
149
    r_notexture_mip = (texture_t*)Hunk_AllocName(sizeof(texture_t) + 16 * 16 + 8 * 8 + 4 * 4 + 2 * 2,
Tyrann's avatar
Tyrann committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
		       "notexture");

    r_notexture_mip->width = r_notexture_mip->height = 16;
    r_notexture_mip->offsets[0] = sizeof(texture_t);
    r_notexture_mip->offsets[1] = r_notexture_mip->offsets[0] + 16 * 16;
    r_notexture_mip->offsets[2] = r_notexture_mip->offsets[1] + 8 * 8;
    r_notexture_mip->offsets[3] = r_notexture_mip->offsets[2] + 4 * 4;

    for (m = 0; m < 4; m++) {
	dest = (byte *)r_notexture_mip + r_notexture_mip->offsets[m];
	for (y = 0; y < (16 >> m); y++) {
	    for (x = 0; x < (16 >> m); x++) {
		if ((y < (8 >> m)) ^ (x < (8 >> m)))
		    *dest++ = 0;
		else
		    *dest++ = 0xff;
	    }
	}
    }
}


/*
================
R_InitTurb
================
*/
static void
R_InitTurb(void)
{
    int i;

    for (i = 0; i < TURB_TABLE_SIZE; ++i) {
	sintable[i] = TURB_SURF_AMP
	    + sin(i * 3.14159 * 2 / TURB_CYCLE) * TURB_SURF_AMP;
	intsintable[i] = TURB_SCREEN_AMP
	    + sin(i * 3.14159 * 2 / TURB_CYCLE) * TURB_SCREEN_AMP;
    }
}


/*
===============
R_Init
===============
*/
void
R_Init(void)
{
    int dummy;

    // get stack position so we can guess if we are going to overflow
    r_stack_start = (byte *)&dummy;

    R_InitTurb();

    Cmd_AddCommand("timerefresh", R_TimeRefresh_f);
    Cmd_AddCommand("pointfile", R_ReadPointFile_f);

    Cvar_RegisterVariable(&r_draworder);
    Cvar_RegisterVariable(&r_speeds);
    Cvar_RegisterVariable(&r_graphheight);
    Cvar_RegisterVariable(&r_clearcolor);
    Cvar_RegisterVariable(&r_waterwarp);
    Cvar_RegisterVariable(&r_drawentities);
    Cvar_RegisterVariable(&r_drawviewmodel);
    Cvar_RegisterVariable(&r_ambient);
    Cvar_RegisterVariable(&r_numsurfs);
    Cvar_RegisterVariable(&r_numedges);
219
#ifdef NQ_HACK
220
    Cvar_RegisterVariable(&r_lerpmodels);
221
    Cvar_RegisterVariable(&r_lerpmove);
222
#endif
Tyrann's avatar
Tyrann committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
    Cvar_RegisterVariable(&r_lockpvs);
    Cvar_RegisterVariable(&r_lockfrustum);

    Cvar_RegisterVariable(&r_fullbright);

    Cvar_RegisterVariable(&r_timegraph);
    Cvar_RegisterVariable(&r_aliasstats);
    Cvar_RegisterVariable(&r_dspeeds);
    Cvar_RegisterVariable(&r_reportsurfout);
    Cvar_RegisterVariable(&r_maxsurfs);
    Cvar_RegisterVariable(&r_reportedgeout);
    Cvar_RegisterVariable(&r_maxedges);
    Cvar_RegisterVariable(&r_aliastransbase);
    Cvar_RegisterVariable(&r_aliastransadj);

238
239
240
241
242
#ifdef QW_HACK
    Cvar_RegisterVariable(&r_netgraph);
    Cvar_RegisterVariable(&r_zgraph);
#endif

Tyrann's avatar
Tyrann committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
    Cvar_SetValue("r_maxedges", (float)NUMSTACKEDGES);
    Cvar_SetValue("r_maxsurfs", (float)NUMSTACKSURFACES);

    view_clipplanes[0].leftedge = true;
    view_clipplanes[1].rightedge = true;
    view_clipplanes[1].leftedge = view_clipplanes[2].leftedge =
	view_clipplanes[3].leftedge = false;
    view_clipplanes[0].rightedge = view_clipplanes[2].rightedge =
	view_clipplanes[3].rightedge = false;

    r_refdef.xOrigin = XCENTERING;
    r_refdef.yOrigin = YCENTERING;

    R_InitParticles();

    D_Init();
}

261
262
extern void V_NewMap (void);

Tyrann's avatar
Tyrann committed
263
264
265
266
267
268
269
270
271
272
/*
===============
R_NewMap
===============
*/
void
R_NewMap(void)
{
    int i;

Tyrann's avatar
Tyrann committed
273
274
275
    memset(&r_worldentity, 0, sizeof(r_worldentity));
    r_worldentity.model = cl.worldmodel;

Tyrann's avatar
Tyrann committed
276
277
278
279
280
281
282
283
// clear out efrags in case the level hasn't been reloaded
// FIXME: is this one short?
    for (i = 0; i < cl.worldmodel->numleafs; i++)
	cl.worldmodel->leafs[i].efrags = NULL;

    r_viewleaf = NULL;
    R_ClearParticles();

Libretro-Admin's avatar
Libretro-Admin committed
284
    r_cnumsurfs = qclamp((int)r_maxsurfs.value, MINSURFACES, MAXSURFACES);
Tyrann's avatar
Tyrann committed
285
    if (r_cnumsurfs > NUMSTACKSURFACES) {
twinaphex's avatar
twinaphex committed
286
	surfaces = (surf_t*)Hunk_AllocName(r_cnumsurfs * sizeof(surf_t), "surfaces");
Tyrann's avatar
Tyrann committed
287
288
289
290
291
292
293
294
295
296
297
298
299
	surface_p = surfaces;
	surf_max = &surfaces[r_cnumsurfs];
	r_surfsonstack = false;
	// surface 0 doesn't really exist; it's just a dummy because index 0
	// is used to indicate no edge attached to surface
	surfaces--;
    } else {
	r_surfsonstack = true;
    }

    r_maxedgesseen = 0;
    r_maxsurfsseen = 0;

Libretro-Admin's avatar
Libretro-Admin committed
300
    r_numallocatededges = qclamp((int)r_maxedges.value, MINEDGES, MAXEDGES);
Tyrann's avatar
Tyrann committed
301
302
303
    if (r_numallocatededges <= NUMSTACKEDGES) {
	auxedges = NULL;
    } else {
304
	auxedges = (edge_t*)Hunk_AllocName(r_numallocatededges * sizeof(edge_t),
Tyrann's avatar
Tyrann committed
305
306
307
308
309
				  "edges");
    }

    r_dowarpold = false;
    r_viewchanged = false;
310
311

    V_NewMap();
Tyrann's avatar
Tyrann committed
312
313
314
315
316
317
318
319
320
}


/*
===============
R_SetVrect
===============
*/
void
321
R_SetVrect(const vrect_t *pvrectin, vrect_t *pvrect, int lineadj)
Tyrann's avatar
Tyrann committed
322
323
324
{
    int h;
    float size;
Kevin Shanahan's avatar
Kevin Shanahan committed
325
    qboolean full;
Tyrann's avatar
Tyrann committed
326

Kevin Shanahan's avatar
Kevin Shanahan committed
327
328
329
330
331
332
333
#ifdef NQ_HACK
    full = (scr_viewsize.value >= 120.0f);
#endif
#ifdef QW_HACK
    full = (!cl_sbar.value && scr_viewsize.value >= 100.0f);
#endif
    size = qmin(scr_viewsize.value, 100.0f);
Tyrann's avatar
Tyrann committed
334

Kevin Shanahan's avatar
Kevin Shanahan committed
335
    /* Hide the status bar during intermission */
Tyrann's avatar
Tyrann committed
336
    if (cl.intermission) {
337
	full = true;
Tyrann's avatar
Tyrann committed
338
339
340
341
342
	size = 100.0;
	lineadj = 0;
    }
    size /= 100.0;

343
344
345
346
347
    if (full)
	h = pvrectin->height;
    else
	h = pvrectin->height - lineadj;

Kevin Shanahan's avatar
Kevin Shanahan committed
348
    pvrect->width = pvrectin->width * size;
Tyrann's avatar
Tyrann committed
349
350
351
352
353
    if (pvrect->width < 96) {
	size = 96.0 / pvrectin->width;
	pvrect->width = 96;	// min for icons
    }
    pvrect->width &= ~7;
354

Tyrann's avatar
Tyrann committed
355
    pvrect->height = pvrectin->height * size;
356
357
358
359
360
    if (!full) {
	if (pvrect->height > pvrectin->height - lineadj)
	    pvrect->height = pvrectin->height - lineadj;
    } else if (pvrect->height > pvrectin->height)
	pvrect->height = pvrectin->height;
Tyrann's avatar
Tyrann committed
361
362
363
    pvrect->height &= ~1;

    pvrect->x = (pvrectin->width - pvrect->width) / 2;
364
365
366
367
    if (full)
	pvrect->y = 0;
    else
	pvrect->y = (h - pvrect->height) / 2;
Tyrann's avatar
Tyrann committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
}


/*
===============
R_ViewChanged

Called every time the vid structure or r_refdef changes.
Guaranteed to be called before the first refresh
===============
*/
void
R_ViewChanged(vrect_t *pvrect, int lineadj, float aspect)
{
    int i;
    float res_scale;

    r_viewchanged = true;

    R_SetVrect(pvrect, &r_refdef.vrect, lineadj);

    r_refdef.horizontalFieldOfView = 2.0 * tan(r_refdef.fov_x / 360 * M_PI);
    r_refdef.fvrectx = (float)r_refdef.vrect.x;
    r_refdef.fvrectx_adj = (float)r_refdef.vrect.x - 0.5;
    r_refdef.vrect_x_adj_shift20 = (r_refdef.vrect.x << 20) + (1 << 19) - 1;
    r_refdef.fvrecty = (float)r_refdef.vrect.y;
    r_refdef.fvrecty_adj = (float)r_refdef.vrect.y - 0.5;
    r_refdef.vrectright = r_refdef.vrect.x + r_refdef.vrect.width;
    r_refdef.vrectright_adj_shift20 =
	(r_refdef.vrectright << 20) + (1 << 19) - 1;
    r_refdef.fvrectright = (float)r_refdef.vrectright;
    r_refdef.fvrectright_adj = (float)r_refdef.vrectright - 0.5;
    r_refdef.vrectrightedge = (float)r_refdef.vrectright - 0.99;
    r_refdef.vrectbottom = r_refdef.vrect.y + r_refdef.vrect.height;
    r_refdef.fvrectbottom = (float)r_refdef.vrectbottom;
    r_refdef.fvrectbottom_adj = (float)r_refdef.vrectbottom - 0.5;

    r_refdef.aliasvrect.x = (int)(r_refdef.vrect.x * r_aliasuvscale);
    r_refdef.aliasvrect.y = (int)(r_refdef.vrect.y * r_aliasuvscale);
    r_refdef.aliasvrect.width = (int)(r_refdef.vrect.width * r_aliasuvscale);
    r_refdef.aliasvrect.height =
	(int)(r_refdef.vrect.height * r_aliasuvscale);
    r_refdef.aliasvrectright =
	r_refdef.aliasvrect.x + r_refdef.aliasvrect.width;
    r_refdef.aliasvrectbottom =
	r_refdef.aliasvrect.y + r_refdef.aliasvrect.height;

    pixelAspect = aspect;
    xOrigin = r_refdef.xOrigin;
    yOrigin = r_refdef.yOrigin;

    screenAspect = r_refdef.vrect.width * pixelAspect / r_refdef.vrect.height;
// 320*200 1.0 pixelAspect = 1.6 screenAspect
// 320*240 1.0 pixelAspect = 1.3333 screenAspect
// proper 320*200 pixelAspect = 0.8333333

    verticalFieldOfView = r_refdef.horizontalFieldOfView / screenAspect;

// values for perspective projection
// if math were exact, the values would range from 0.5 to to range+0.5
// hopefully they wll be in the 0.000001 to range+.999999 and truncate
// the polygon rasterization will never render in the first row or column
// but will definately render in the [range] row and column, so adjust the
// buffer origin to get an exact edge to edge fill
    xcenter = ((float)r_refdef.vrect.width * XCENTERING) +
	r_refdef.vrect.x - 0.5;
    aliasxcenter = xcenter * r_aliasuvscale;
    ycenter = ((float)r_refdef.vrect.height * YCENTERING) +
	r_refdef.vrect.y - 0.5;
    aliasycenter = ycenter * r_aliasuvscale;

    xscale = r_refdef.vrect.width / r_refdef.horizontalFieldOfView;
    aliasxscale = xscale * r_aliasuvscale;
    xscaleinv = 1.0 / xscale;
    yscale = xscale * pixelAspect;
    aliasyscale = yscale * r_aliasuvscale;
    yscaleinv = 1.0 / yscale;
    xscaleshrink =
	(r_refdef.vrect.width - 6) / r_refdef.horizontalFieldOfView;
    yscaleshrink = xscaleshrink * pixelAspect;

// left side clip
    screenedge[0].normal[0] =
	-1.0 / (xOrigin * r_refdef.horizontalFieldOfView);
    screenedge[0].normal[1] = 0;
    screenedge[0].normal[2] = 1;
    screenedge[0].type = PLANE_ANYZ;

// right side clip
    screenedge[1].normal[0] =
	1.0 / ((1.0 - xOrigin) * r_refdef.horizontalFieldOfView);
    screenedge[1].normal[1] = 0;
    screenedge[1].normal[2] = 1;
    screenedge[1].type = PLANE_ANYZ;

// top side clip
    screenedge[2].normal[0] = 0;
    screenedge[2].normal[1] = -1.0 / (yOrigin * verticalFieldOfView);
    screenedge[2].normal[2] = 1;
    screenedge[2].type = PLANE_ANYZ;

// bottom side clip
    screenedge[3].normal[0] = 0;
    screenedge[3].normal[1] = 1.0 / ((1.0 - yOrigin) * verticalFieldOfView);
    screenedge[3].normal[2] = 1;
    screenedge[3].type = PLANE_ANYZ;

    for (i = 0; i < 4; i++)
	VectorNormalize(screenedge[i].normal);

    res_scale =
	sqrt((double)(r_refdef.vrect.width * r_refdef.vrect.height) /
	     (320.0 * 152.0)) * (2.0 / r_refdef.horizontalFieldOfView);
    r_aliastransition = r_aliastransbase.value * res_scale;
    r_resfudge = r_aliastransadj.value * res_scale;

    D_ViewChanged();
}


/*
===============
490
R_MarkSurfaces
Tyrann's avatar
Tyrann committed
491
492
493
===============
*/
static void
494
R_MarkSurfaces(void)
Tyrann's avatar
Tyrann committed
495
{
496
    const leafbits_t *pvs;
497
    leafblock_t check;
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
    int leafnum, i;
    mleaf_t *leaf;
    mnode_t *node;
    msurface_t **mark;
    qboolean pvs_changed;

    /*
     * If the PVS hasn't changed, no need to update bsp visframes,
     * just store the efrags.
     */
    pvs_changed = (r_viewleaf != r_oldviewleaf && !r_lockpvs.value);
    if (pvs_changed) {
	r_visframecount++;
	r_oldviewleaf = r_viewleaf;
    }
Tyrann's avatar
Tyrann committed
513

514
    pvs = Mod_LeafPVS(cl.worldmodel, r_viewleaf);
515
    foreach_leafbit(pvs, leafnum, check) {
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
	leaf = &cl.worldmodel->leafs[leafnum + 1];
	if (leaf->efrags)
	    R_StoreEfrags(&leaf->efrags);
	if (!pvs_changed)
	    continue;

	/* Mark the surfaces */
	mark = leaf->firstmarksurface;
	for (i = 0; i < leaf->nummarksurfaces; i++) {
	    (*mark)->visframe = r_visframecount;
	    mark++;
	}

	/* Mark the leaf and all parent nodes */
	node = (mnode_t *)leaf;
531
532
533
534
535
536
	do {
	    if (node->visframe == r_visframecount)
		break;
	    node->visframe = r_visframecount;
	    node = node->parent;
	} while (node);
Tyrann's avatar
Tyrann committed
537
538
539
    }
}

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*
=============
R_CullSurfaces
=============
*/
static void
R_CullSurfaces(model_t *model, vec3_t vieworg)
{
    int i, j;
    int side;
    mnode_t *node;
    msurface_t *surf;
    mplane_t *plane;
    vec_t dist;

    node = model->nodes;
    node->clipflags = 15;

    for (;;) {
	if (node->visframe != r_visframecount)
	    goto NodeUp;

	if (node->clipflags) {
	    /* Clip the node against the frustum */
	    for (i = 0; i < 4; i++) {
		if (!(node->clipflags & (1 << i)))
		    continue;
		plane = &view_clipplanes[i].plane;
		side = BoxOnPlaneSide(node->mins, node->maxs, plane);
		if (side == PSIDE_BACK) {
		    node->clipflags = BMODEL_FULLY_CLIPPED;
		    goto NodeUp;
		}
		if (side == PSIDE_FRONT)
		    node->clipflags &= ~(1 << i);
	    }
	}

	if (node->contents < 0)
	    goto NodeUp;

	surf = model->surfaces + node->firstsurface;
	for (i = 0; i < node->numsurfaces; i++, surf++) {
	    /* Clip the surfaces against the frustum */
	    surf->clipflags = node->clipflags;
	    for (j = 0; j < 4; j++) {
		if (!(node->clipflags & (1 << j)))
		    continue;
		plane = &view_clipplanes[j].plane;
		side = BoxOnPlaneSide(surf->mins, surf->maxs, plane);
		if (side == PSIDE_BACK) {
		    surf->clipflags = BMODEL_FULLY_CLIPPED;
		    break;
		}
		if (side == PSIDE_FRONT)
		    surf->clipflags &= ~(1 << j);
	    }
	    if (j < 4)
		continue;

	    /* Cull backward facing surfs */
	    if (surf->plane->type < 3) {
		dist = vieworg[surf->plane->type] - surf->plane->dist;
	    } else {
		dist = DotProduct(vieworg, surf->plane->normal);
		dist -= surf->plane->dist;
	    }
	    if (surf->flags & SURF_PLANEBACK) {
		if (dist > -BACKFACE_EPSILON)
		    surf->clipflags = BMODEL_FULLY_CLIPPED;
	    } else {
		if (dist < BACKFACE_EPSILON)
		    surf->clipflags = BMODEL_FULLY_CLIPPED;
	    }
	}

//  DownLeft:
	/* Don't descend into solid leafs because parent links are broken */
	if (node->children[0]->contents == CONTENTS_SOLID)
	    goto DownRight;
	node->children[0]->clipflags = node->clipflags;
	node = node->children[0];
	continue;

    DownRight:
	/* Don't descent into solid leafs because parent links are broken */
	if (node->children[1]->contents == CONTENTS_SOLID)
	    goto NodeUp;
	node->children[1]->clipflags = node->clipflags;
	node = node->children[1];
	continue;

    NodeUp:
	/* If we just processed the left node, go right */
	if (node->parent && node == node->parent->children[0]) {
	    node = node->parent;
	    goto DownRight;
	}

	/* If we were on a right branch, backtrack */
	while (node->parent && node == node->parent->children[1])
	    node = node->parent;

	/* If we still have a parent, we need to cross to the right */
	if (node->parent) {
	    node = node->parent;
	    goto DownRight;
	}

	/* If no more parents, we are done */
	break;
    }
}
Tyrann's avatar
Tyrann committed
653

654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/*
=============
R_CullSubmodelSurfaces
=============
*/
static void
R_CullSubmodelSurfaces(const model_t *submodel, const vec3_t vieworg,
		       int clipflags)
{
    int i, j, side;
    msurface_t *surf;
    mplane_t *plane;
    vec_t dist;

    surf = submodel->surfaces + submodel->firstmodelsurface;
    for (i = 0; i < submodel->nummodelsurfaces; i++, surf++) {
	/* Clip the surface against the frustum */
	surf->clipflags = clipflags;
	for (j = 0; j < 4; j++) {
673
674
	    if (!(surf->clipflags & (1 << j)))
		continue;
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
	    plane = &view_clipplanes[j].plane;
	    side = BoxOnPlaneSide(surf->mins, surf->maxs, plane);
	    if (side == PSIDE_BACK) {
		surf->clipflags = BMODEL_FULLY_CLIPPED;
		break;
	    }
	    if (side == PSIDE_FRONT)
		surf->clipflags &= ~(1 << j);
	}
	if (j < 4)
	    continue;

	/* Cull backward facing surfs */
	if (surf->plane->type < 3) {
	    dist = vieworg[surf->plane->type] - surf->plane->dist;
	} else {
	    dist = DotProduct(vieworg, surf->plane->normal);
	    dist -= surf->plane->dist;
	}
	if (surf->flags & SURF_PLANEBACK) {
	    if (dist > -BACKFACE_EPSILON)
		surf->clipflags = BMODEL_FULLY_CLIPPED;
	} else {
	    if (dist < BACKFACE_EPSILON)
		surf->clipflags = BMODEL_FULLY_CLIPPED;
	}
    }
}

Tyrann's avatar
Tyrann committed
704
705
706
707
708
709
710
711
/*
=============
R_DrawEntitiesOnList
=============
*/
static void
R_DrawEntitiesOnList(void)
{
712
    entity_t *e;
Tyrann's avatar
Tyrann committed
713
714
715
716
717
718
719
720
721
722
723
724
725
    int i, j;
    int lnum;
    alight_t lighting;

// FIXME: remove and do real lighting
    float lightvec[3] = { -1, 0, 0 };
    vec3_t dist;
    float add;

    if (!r_drawentities.value)
	return;

    for (i = 0; i < cl_numvisedicts; i++) {
726
	e = &cl_visedicts[i];
727
#ifdef NQ_HACK
728
	if (e == &cl_entities[cl.viewentity])
Tyrann's avatar
Tyrann committed
729
	    continue;		// don't draw the player
730
#endif
731
	switch (e->model->type) {
Tyrann's avatar
Tyrann committed
732
	case mod_sprite:
733
	    VectorCopy(e->origin, r_entorigin);
Tyrann's avatar
Tyrann committed
734
	    VectorSubtract(r_origin, r_entorigin, modelorg);
735
	    R_DrawSprite(e);
Tyrann's avatar
Tyrann committed
736
737
738
	    break;

	case mod_alias:
739
740
741
742
743
744
#ifdef NQ_HACK
	    if (r_lerpmove.value) {
		float delta = e->currentorigintime - e->previousorigintime;
		float frac = qclamp((cl.time - e->currentorigintime) / delta, 0.0, 1.0);
		vec3_t lerpvec;

745
746
		/* FIXME - hack to skip the viewent (weapon) */
		if (e == &cl.viewent)
747
		    goto nolerp;
748

749
750
751
752
753
754
755
756
		VectorSubtract(e->currentorigin, e->previousorigin, lerpvec);
		VectorMA(e->previousorigin, frac, lerpvec, r_entorigin);
	    } else
	    nolerp:
#endif
	    {
		VectorCopy(e->origin, r_entorigin);
	    }
Tyrann's avatar
Tyrann committed
757
758
759
760
	    VectorSubtract(r_origin, r_entorigin, modelorg);

	    // see if the bounding box lets us trivially reject, also sets
	    // trivial accept status
761
762
	    if (R_AliasCheckBBox(e)) {
		j = R_LightPoint(e->origin);
Tyrann's avatar
Tyrann committed
763
764
765
766
767
768
769

		lighting.ambientlight = j;
		lighting.shadelight = j;

		lighting.plightvec = lightvec;

		for (lnum = 0; lnum < MAX_DLIGHTS; lnum++) {
770
771
772
773
774
775
776
777
		    if (cl_dlights[lnum].die >= cl.time) {
			VectorSubtract(e->origin, cl_dlights[lnum].origin,
				       dist);
			add = cl_dlights[lnum].radius - Length(dist);

			if (add > 0)
			    lighting.ambientlight += add;
		    }
Tyrann's avatar
Tyrann committed
778
779
780
781
782
783
784
785
		}

		// clamp lighting so it doesn't overbright as much
		if (lighting.ambientlight > 128)
		    lighting.ambientlight = 128;
		if (lighting.ambientlight + lighting.shadelight > 192)
		    lighting.shadelight = 192 - lighting.ambientlight;

786
		R_AliasDrawModel(e, &lighting);
Tyrann's avatar
Tyrann committed
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
	    }
	    break;

	default:
	    break;
	}
    }
}

/*
=============
R_DrawViewModel
=============
*/
static void
R_DrawViewModel(void)
{
804
    entity_t *e;
Tyrann's avatar
Tyrann committed
805
806
807
808
809
810
811
812
// FIXME: remove and do real lighting
    float lightvec[3] = { -1, 0, 0 };
    int j;
    int lnum;
    vec3_t dist;
    float add;
    dlight_t *dl;

813
#ifdef NQ_HACK
814
    if (!r_drawviewmodel.value || chase_active.value)
Tyrann's avatar
Tyrann committed
815
	return;
816
817
#endif
#ifdef QW_HACK
818
    if (!r_drawviewmodel.value || !Cam_DrawViewModel())
819
820
	return;
#endif
Tyrann's avatar
Tyrann committed
821

822
    if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
Tyrann's avatar
Tyrann committed
823
824
825
826
827
	return;

    if (cl.stats[STAT_HEALTH] <= 0)
	return;

828
    e = &cl.viewent;
829
    if (!e->model)
Tyrann's avatar
Tyrann committed
830
831
	return;

832
    VectorCopy(e->origin, r_entorigin);
Tyrann's avatar
Tyrann committed
833
834
835
836
837
    VectorSubtract(r_origin, r_entorigin, modelorg);

    VectorCopy(vup, viewlightvec);
    VectorInverse(viewlightvec);

838
    j = R_LightPoint(e->origin);
Tyrann's avatar
Tyrann committed
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854

    if (j < 24)
	j = 24;			// allways give some light on gun
    r_viewlighting.ambientlight = j;
    r_viewlighting.shadelight = j;

// add dynamic lights
    for (lnum = 0; lnum < MAX_DLIGHTS; lnum++) {
	dl = &cl_dlights[lnum];
	if (!dl->radius)
	    continue;
	if (!dl->radius)
	    continue;
	if (dl->die < cl.time)
	    continue;

855
	VectorSubtract(e->origin, dl->origin, dist);
Tyrann's avatar
Tyrann committed
856
857
858
859
860
861
862
863
864
865
866
867
868
	add = dl->radius - Length(dist);
	if (add > 0)
	    r_viewlighting.ambientlight += add;
    }

// clamp lighting so it doesn't overbright as much
    if (r_viewlighting.ambientlight > 128)
	r_viewlighting.ambientlight = 128;
    if (r_viewlighting.ambientlight + r_viewlighting.shadelight > 192)
	r_viewlighting.shadelight = 192 - r_viewlighting.ambientlight;

    r_viewlighting.plightvec = lightvec;

869
    R_AliasDrawModel(e, &r_viewlighting);
Tyrann's avatar
Tyrann committed
870
871
872
873
874
875
876
877
878
}


/*
=============
R_BmodelCheckBBox
=============
*/
static int
879
880
R_BmodelCheckBBox(const entity_t *e, model_t *clmodel,
		  const vec3_t mins, const vec3_t maxs)
Tyrann's avatar
Tyrann committed
881
{
882
883
    int i, side, clipflags;
    vec_t d;
Tyrann's avatar
Tyrann committed
884
885
886

    clipflags = 0;

887
    if (e->angles[0] || e->angles[1] || e->angles[2]) {
Tyrann's avatar
Tyrann committed
888
	for (i = 0; i < 4; i++) {
889
890
	    d = DotProduct(e->origin, view_clipplanes[i].plane.normal);
	    d -= view_clipplanes[i].plane.dist;
Tyrann's avatar
Tyrann committed
891
892
893
894
895
896
897
898
899

	    if (d <= -clmodel->radius)
		return BMODEL_FULLY_CLIPPED;

	    if (d <= clmodel->radius)
		clipflags |= (1 << i);
	}
    } else {
	for (i = 0; i < 4; i++) {
900
901
	    side = BoxOnPlaneSide(mins, maxs, &view_clipplanes[i].plane);
	    if (side == PSIDE_BACK)
Tyrann's avatar
Tyrann committed
902
		return BMODEL_FULLY_CLIPPED;
903
	    if (side == PSIDE_BOTH)
Tyrann's avatar
Tyrann committed
904
905
906
907
908
909
910
911
912
913
914
915
916
		clipflags |= (1 << i);
	}
    }

    return clipflags;
}


/*
=============
R_DrawBEntitiesOnList
=============
*/
Libretro-Admin's avatar
Libretro-Admin committed
917
static void R_DrawBEntitiesOnList(void)
Tyrann's avatar
Tyrann committed
918
{
919
    entity_t *e;
Libretro-Admin's avatar
Libretro-Admin committed
920
    int i, clipflags;
Tyrann's avatar
Tyrann committed
921
    vec3_t oldorigin;
922
    model_t *model;
923
    vec3_t mins, maxs;
Tyrann's avatar
Tyrann committed
924
925
926
927
928
929
930
931

    if (!r_drawentities.value)
	return;

    VectorCopy(modelorg, oldorigin);
    insubmodel = true;

    for (i = 0; i < cl_numvisedicts; i++) {
932
	e = &cl_visedicts[i];
933
934
	if (e->model->type != mod_brush)
	    continue;
Tyrann's avatar
Tyrann committed
935

936
	model = e->model;
Tyrann's avatar
Tyrann committed
937

938
939
940
941
942
	// see if the bounding box lets us trivially reject, also sets
	// trivial accept status
	VectorAdd(e->origin, model->mins, mins);
	VectorAdd(e->origin, model->maxs, maxs);
	clipflags = R_BmodelCheckBBox(e, model, mins, maxs);
Tyrann's avatar
Tyrann committed
943

944
945
	if (clipflags == BMODEL_FULLY_CLIPPED)
	    continue;
Tyrann's avatar
Tyrann committed
946

947
948
949
	VectorCopy(e->origin, r_entorigin);
	VectorSubtract(r_origin, r_entorigin, modelorg);
	r_pcurrentvertbase = model->vertexes;
950

951
952
	// FIXME: stop transforming twice
	R_RotateBmodel(e);
Tyrann's avatar
Tyrann committed
953

954
955
	// calculate dynamic lighting for bmodel if it's not an
	// instanced model
956
957
	if (model->firstmodelsurface != 0)
       R_PushDlights (model->nodes + model->hulls[0].firstclipnode);  /*qbism - from MH */
Tyrann's avatar
Tyrann committed
958

959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
	r_pefragtopnode = NULL;
	VectorCopy(mins, r_emins);
	VectorCopy(maxs, r_emaxs);
	R_SplitEntityOnNode2(cl.worldmodel->nodes);
	R_CullSubmodelSurfaces(model, modelorg, clipflags);

	if (r_pefragtopnode) {
	    e->topnode = r_pefragtopnode;

	    if (r_pefragtopnode->contents >= 0) {
		// not a leaf; has to be clipped to the world BSP
		R_DrawSolidClippedSubmodelPolygons(e, model);
	    } else {
		// falls entirely in one leaf, so we just put all
		// the edges in the edge list and let 1/z sorting
		// handle drawing order
		R_DrawSubmodelPolygons(e, model, clipflags);
	    }
	    e->topnode = NULL;
Tyrann's avatar
Tyrann committed
978
	}
979
980
981
982
983
984
985
986
987

	// put back world rotation and frustum clipping
	// FIXME: R_RotateBmodel should just work off base_vxx
	VectorCopy(base_vpn, vpn);
	VectorCopy(base_vup, vup);
	VectorCopy(base_vright, vright);
	VectorCopy(base_modelorg, modelorg);
	VectorCopy(oldorigin, modelorg);
	R_TransformFrustum();
Tyrann's avatar
Tyrann committed
988
989
990
991
992
993
994
995
996
997
998
    }

    insubmodel = false;
}


/*
================
R_EdgeDrawing
================
*/
999
static void R_EdgeDrawing(void)
Tyrann's avatar
Tyrann committed
1000
{
frangarcj's avatar
frangarcj committed
1001
1002
   edge_t * ledges = malloc(sizeof(edge_t)*CACHE_PAD_ARRAY(NUMSTACKEDGES, edge_t));
   surf_t * lsurfs = malloc(sizeof(surf_t)*CACHE_PAD_ARRAY(NUMSTACKSURFACES, surf_t));
Tyrann's avatar
Tyrann committed
1003

1004
1005
1006
   if (auxedges) {
      r_edges = auxedges;
   } else {
Libretro-Admin's avatar
Libretro-Admin committed
1007
1008
      r_edges =  (edge_t *)
				(((long)&ledges[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
1009
   }
Tyrann's avatar
Tyrann committed
1010

1011
   if (r_surfsonstack) {
Libretro-Admin's avatar
Libretro-Admin committed
1012
1013
      surfaces =  (surf_t *)
				(((long)&lsurfs[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
1014
1015
1016
1017
1018
      surf_max = &surfaces[r_cnumsurfs];
      // surface 0 doesn't really exist; it's just a dummy because index 0
      // is used to indicate no edge attached to surface
      surfaces--;
   }
Tyrann's avatar
Tyrann committed
1019

1020
   R_BeginEdgeFrame();
Tyrann's avatar
Tyrann committed
1021

1022
   R_RenderWorld();
Tyrann's avatar
Tyrann committed
1023

1024
1025
1026
   // only the world can be drawn back to front with no z reads or compares,
   // just z writes, so have the driver turn z compares on now
   D_TurnZOn();
Tyrann's avatar
Tyrann committed
1027

1028
   R_DrawBEntitiesOnList();
Tyrann's avatar
Tyrann committed
1029

1030
   R_ScanEdges();
frangarcj's avatar
frangarcj committed
1031
1032
1033
1034

   free(lsurfs);
   free(ledges);

Tyrann's avatar
Tyrann committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
}


/*
================
R_RenderView

r_refdef must be set before the first call
================
*/
static void
R_RenderView_(void)
{
    byte warpbuffer[WARP_WIDTH * WARP_HEIGHT];

    r_warpbuffer = warpbuffer;

    R_SetupFrame();
1053
    R_PushDlights (cl.worldmodel->nodes);  /* qbism - moved here from view.c */
1054
    R_MarkSurfaces();		// done here so we know if we're in water
1055
    R_CullSurfaces(r_worldentity.model, r_refdef.vieworg);
Tyrann's avatar
Tyrann committed
1056
1057
1058
1059
1060
1061
1062

    // make FDIV fast. This reduces timing precision after we've been running
    // for a while, so we don't do it globally.  This also sets chop mode, and
    // we do it here so that setup stuff like the refresh area calculations
    // match what's done in screen.c
    Sys_LowFPPrecision();

Tyrann's avatar
Tyrann committed
1063
    if (!r_worldentity.model || !cl.worldmodel)
Tyrann's avatar
Tyrann committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
	Sys_Error("%s: NULL worldmodel", __func__);

    R_EdgeDrawing();

    R_DrawEntitiesOnList();

    R_DrawViewModel();

    R_DrawParticles();

    if (r_dowarp)
	D_WarpScreen();

    V_SetContentsColor(r_viewleaf->contents);

    if (r_aliasstats.value)
	R_PrintAliasStats();

    if (r_reportsurfout.value && r_outofsurfaces)
	Con_Printf("Short %d surfaces\n", r_outofsurfaces);

    if (r_reportedgeout.value && r_outofedges)
	Con_Printf("Short roughly %d edges\n", r_outofedges * 2 / 3);

    // back to high floating-point precision
    Sys_HighFPPrecision();
}

void
R_RenderView(void)
{
    int dummy;
1096

Tyrann's avatar
Tyrann committed
1097
1098
1099
    if (Hunk_LowMark() & 3)
	Sys_Error("Hunk is missaligned");

1100
    if ((intptr_t)(&dummy) & 3)
Tyrann's avatar
Tyrann committed
1101
1102
	Sys_Error("Stack is missaligned");

1103
    if ((intptr_t)(&r_warpbuffer) & 3)
Tyrann's avatar
Tyrann committed
1104
1105
1106
1107
	Sys_Error("Globals are missaligned");

    R_RenderView_();
}