implemented r_render and r_upload cvar options for CPU profiling (not hardware bound...
[divverent/darkplaces.git] / gl_rsurf.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 // r_surf.c: surface-related refresh code
21
22 #include "quakedef.h"
23
24 extern int                     skytexturenum;
25
26 int             lightmap_textures;
27
28 signed blocklights[18*18*3]; // LordHavoc: *3 for colored lighting
29
30 // LordHavoc: skinny but tall lightmaps for quicker subimage uploads
31 #define BLOCK_WIDTH             128
32 #define BLOCK_HEIGHT    128
33 // LordHavoc: increased lightmap limit from 64 to 1024
34 #define MAX_LIGHTMAPS   1024
35 #define LIGHTMAPSIZE    (BLOCK_WIDTH*BLOCK_HEIGHT*4)
36
37 int                     active_lightmaps;
38
39 short allocated[MAX_LIGHTMAPS][BLOCK_WIDTH];
40
41 byte *lightmaps[MAX_LIGHTMAPS];
42 short lightmapupdate[MAX_LIGHTMAPS][2];
43
44 int lightmapalign, lightmapalignmask; // LordHavoc: NVIDIA's broken subimage fix, see BuildLightmaps for notes
45 cvar_t gl_lightmapalign = {"gl_lightmapalign", "4"};
46 cvar_t gl_lightmaprgba = {"gl_lightmaprgba", "0"};
47 cvar_t gl_nosubimagefragments = {"gl_nosubimagefragments", "0"};
48 cvar_t gl_nosubimage = {"gl_nosubimage", "0"};
49 cvar_t r_ambient = {"r_ambient", "0"};
50 cvar_t gl_vertex = {"gl_vertex", "0"};
51 cvar_t gl_texsort = {"gl_texsort", "1"};
52 //cvar_t gl_funnywalls = {"gl_funnywalls", "0"}; // LordHavoc: see BuildSurfaceDisplayList
53
54 qboolean lightmaprgba, nosubimagefragments, nosubimage, skyisvisible;
55 int lightmapbytes;
56
57 extern qboolean gl_arrays;
58
59 extern int r_dlightframecount;
60
61 void gl_surf_start()
62 {
63 }
64
65 void gl_surf_shutdown()
66 {
67 }
68
69 void GL_Surf_Init()
70 {
71         int i;
72         for (i = 0;i < MAX_LIGHTMAPS;i++)
73                 lightmaps[i] = NULL;
74         Cvar_RegisterVariable(&gl_lightmapalign);
75         Cvar_RegisterVariable(&gl_lightmaprgba);
76         Cvar_RegisterVariable(&gl_nosubimagefragments);
77         Cvar_RegisterVariable(&gl_nosubimage);
78         Cvar_RegisterVariable(&r_ambient);
79 //      Cvar_RegisterVariable(&gl_funnywalls);
80         Cvar_RegisterVariable(&gl_vertex);
81         Cvar_RegisterVariable(&gl_texsort);
82         // check if it's the glquake minigl driver
83         if (strncasecmp(gl_vendor,"3Dfx",4)==0)
84         if (!gl_arrays)
85         {
86 //              Cvar_SetValue("gl_nosubimagefragments", 1);
87 //              Cvar_SetValue("gl_nosubimage", 1);
88                 Cvar_SetValue("gl_lightmode", 0);
89         }
90
91         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown);
92 }
93
94 extern qboolean lighthalf;
95 /*
96 ===============
97 R_BuildLightMap
98
99 Combine and scale multiple lightmaps into the 8.8 format in blocklights
100 ===============
101 */
102 void R_BuildLightMap (msurface_t *surf, byte *dest, int stride)
103 {
104         int                     smax, tmax;
105         int                     t;
106         int                     i, j, size;
107         byte            *lightmap;
108         int                     scale;
109         int                     maps;
110         int                     *bl;
111
112         surf->cached_lighthalf = lighthalf;
113         surf->cached_ambient = r_ambient.value;
114
115         smax = (surf->extents[0]>>4)+1;
116         tmax = (surf->extents[1]>>4)+1;
117         size = smax*tmax;
118         lightmap = surf->samples;
119
120 // set to full bright if no light data
121         if (currententity->effects & EF_FULLBRIGHT || !cl.worldmodel->lightdata)
122         {
123                 bl = blocklights;
124                 for (i=0 ; i<size ; i++)
125                 {
126                         *bl++ = 255*256;
127                         *bl++ = 255*256;
128                         *bl++ = 255*256;
129                 }
130         }
131         else
132         {
133 // clear to no light
134                 bl = blocklights;
135                 j = r_ambient.value * 512.0f; // would be 256.0f logically, but using 512.0f to match winquake style
136                 for (i=0 ; i<size ; i++)
137                 {
138                         *bl++ = j;
139                         *bl++ = j;
140                         *bl++ = j;
141                 }
142
143 // add all the lightmaps
144                 if (lightmap)
145                         for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++)
146                         {
147                                 scale = d_lightstylevalue[surf->styles[maps]];
148                                 surf->cached_light[maps] = scale;       // 8.8 fraction
149                                 bl = blocklights;
150                                 for (i=0 ; i<size ; i++)
151                                 {
152                                         *bl++ += *lightmap++ * scale;
153                                         *bl++ += *lightmap++ * scale;
154                                         *bl++ += *lightmap++ * scale;
155                                 }
156                         }
157         }
158         stride -= (smax*lightmapbytes);
159         bl = blocklights;
160         if (lighthalf)
161         {
162                 // LordHavoc: I shift down by 8 unlike GLQuake's 7,
163                 // the image is brightened as a processing pass
164                 if (lightmaprgba)
165                 {
166                         for (i=0 ; i<tmax ; i++, dest += stride)
167                         {
168                                 for (j=0 ; j<smax ; j++)
169                                 {
170                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
171                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
172                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
173                                         *dest++ = 255;
174                                 }
175                         }
176                 }
177                 else
178                 {
179                         for (i=0 ; i<tmax ; i++, dest += stride)
180                         {
181                                 for (j=0 ; j<smax ; j++)
182                                 {
183                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
184                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
185                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
186                                 }
187                         }
188                 }
189         }
190         else
191         {
192                 if (lightmaprgba)
193                 {
194                         for (i=0 ; i<tmax ; i++, dest += stride)
195                         {
196                                 for (j=0 ; j<smax ; j++)
197                                 {
198                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
199                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
200                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
201                                         *dest++ = 255;
202                                 }
203                         }
204                 }
205                 else
206                 {
207                         for (i=0 ; i<tmax ; i++, dest += stride)
208                         {
209                                 for (j=0 ; j<smax ; j++)
210                                 {
211                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
212                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
213                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
214                                 }
215                         }
216                 }
217         }
218 }
219
220 byte templight[32*32*4];
221
222 void R_UpdateLightmap(msurface_t *s, int lnum)
223 {
224         int smax, tmax;
225         // upload the new lightmap texture fragment
226         if(r_upload.value)
227                 glBindTexture(GL_TEXTURE_2D, lightmap_textures + lnum);
228         if (nosubimage || nosubimagefragments)
229         {
230                 if (lightmapupdate[lnum][0] > s->light_t)
231                         lightmapupdate[lnum][0] = s->light_t;
232                 if (lightmapupdate[lnum][1] < (s->light_t + ((s->extents[1]>>4)+1)))
233                         lightmapupdate[lnum][1] = (s->light_t + ((s->extents[1]>>4)+1));
234                 if (lightmaprgba)
235                         R_BuildLightMap (s, lightmaps[s->lightmaptexturenum] + (s->light_t * BLOCK_WIDTH + s->light_s) * 4, BLOCK_WIDTH * 4);
236                 else
237                         R_BuildLightMap (s, lightmaps[s->lightmaptexturenum] + (s->light_t * BLOCK_WIDTH + s->light_s) * 3, BLOCK_WIDTH * 3);
238         }
239         else
240         {
241                 smax = ((s->extents[0]>>4)+lightmapalign) & lightmapalignmask;
242                 tmax = (s->extents[1]>>4)+1;
243                 if (lightmaprgba)
244                 {
245                         R_BuildLightMap (s, templight, smax * 4);
246                         if(r_upload.value)
247                                 glTexSubImage2D(GL_TEXTURE_2D, 0, s->light_s, s->light_t, smax, tmax, GL_RGBA, GL_UNSIGNED_BYTE, templight);
248                 }
249                 else
250                 {
251                         R_BuildLightMap (s, templight, smax * 3);
252                         if(r_upload.value)
253                                 glTexSubImage2D(GL_TEXTURE_2D, 0, s->light_s, s->light_t, smax, tmax, GL_RGB , GL_UNSIGNED_BYTE, templight);
254                 }
255         }
256 }
257
258
259 /*
260 ===============
261 R_TextureAnimation
262
263 Returns the proper texture for a given time and base texture
264 ===============
265 */
266 texture_t *R_TextureAnimation (texture_t *base)
267 {
268         texture_t *original;
269         int             relative;
270         int             count;
271
272         if (currententity->frame)
273         {
274                 if (base->alternate_anims)
275                         base = base->alternate_anims;
276         }
277         
278         if (!base->anim_total)
279                 return base;
280
281         original = base;
282
283         relative = (int)(cl.time*10) % base->anim_total;
284
285         count = 0;      
286         while (base->anim_min > relative || base->anim_max <= relative)
287         {
288                 base = base->anim_next;
289                 if (!base)
290                 {
291                         Con_Printf("R_TextureAnimation: broken cycle");
292                         return original;
293                 }
294                 if (++count > 100)
295                 {
296                         Con_Printf("R_TextureAnimation: infinite cycle");
297                         return original;
298                 }
299         }
300
301         return base;
302 }
303
304
305 /*
306 =============================================================
307
308         BRUSH MODELS
309
310 =============================================================
311 */
312
313
314 extern  int             solidskytexture;
315 extern  int             alphaskytexture;
316 extern  float   speedscale;             // for top sky and bottom sky
317
318 extern char skyname[];
319
320 void R_DynamicLightPoint(vec3_t color, vec3_t org, int *dlightbits);
321 float   turbsin[256] =
322 {
323         #include "gl_warp_sin.h"
324 };
325 #define TURBSCALE (256.0 / (2 * M_PI))
326
327
328 void UploadLightmaps()
329 {
330         int i;
331         if (nosubimage || nosubimagefragments)
332         {
333                 for (i = 0;i < MAX_LIGHTMAPS;i++)
334                 {
335                         if (lightmapupdate[i][0] < lightmapupdate[i][1])
336                         {
337                                 if(r_upload.value)
338                                 {
339                                         glBindTexture(GL_TEXTURE_2D, lightmap_textures + i);
340                                         if (nosubimage)
341                                         {
342                                                 if (lightmaprgba)
343                                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i]);
344                                                 else
345                                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i]);
346                                         }
347                                         else
348                                         {
349                                                 if (lightmaprgba)
350                                                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, lightmapupdate[i][0], BLOCK_WIDTH, lightmapupdate[i][1] - lightmapupdate[i][0], GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i] + (BLOCK_WIDTH * 4 * lightmapupdate[i][0]));
351                                                 else
352                                                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, lightmapupdate[i][0], BLOCK_WIDTH, lightmapupdate[i][1] - lightmapupdate[i][0], GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i] + (BLOCK_WIDTH * 3 * lightmapupdate[i][0]));
353                                         }
354                                 }
355                         }
356                         lightmapupdate[i][0] = BLOCK_HEIGHT;
357                         lightmapupdate[i][1] = 0;
358                 }
359         }
360 }
361
362 float   wvert[1024*6]; // used by the following functions
363
364 void RSurf_DrawSky(msurface_t *s, int transform)
365 {
366         glpoly_t *p;
367         int i;
368         float *v;
369         for (p=s->polys ; p ; p=p->next)
370         {
371                 if (currentskypoly < MAX_SKYPOLYS && currentskyvert + p->numverts <= MAX_SKYVERTS)
372                 {
373                         skypoly[currentskypoly].firstvert = currentskyvert;
374                         skypoly[currentskypoly++].verts = p->numverts;
375                         if (transform)
376                         {
377                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
378                                 {
379                                         softwaretransform(v, skyvert[currentskyvert].v);
380                                         currentskyvert++;
381                                 }
382                         }
383                         else
384                         {
385                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
386                                 {
387                                         skyvert[currentskyvert].v[0] = v[0];
388                                         skyvert[currentskyvert].v[1] = v[1];
389                                         skyvert[currentskyvert++].v[2] = v[2];
390                                 }
391                         }
392                 }
393         }
394 }
395
396 int RSurf_Light(int *dlightbits, glpoly_t *polys)
397 {
398         float           cr, cg, cb, radius, radius2, f, *v, *wv;
399         int                     i, a, b, lit = false;
400         unsigned int c, d;
401         dlight_t        *light;
402         vec_t           *lightorigin;
403         glpoly_t        *p;
404         for (a = 0;a < 8;a++)
405         {
406                 if ((c = dlightbits[a]))
407                 {
408                         for (b = 0, d = 1;c;b++, d <<= 1)
409                         {
410                                 if (c & d)
411                                 {
412                                         c -= d;
413                                         light = &cl_dlights[a * 32 + b];
414                                         lightorigin = light->origin;
415                                         cr = light->color[0];
416                                         cg = light->color[1];
417                                         cb = light->color[2];
418                                         radius = light->radius*light->radius*LIGHTSCALE;
419                                         radius2 = radius * (256.0f / LIGHTSCALE);
420                                         wv = wvert;
421                                         for (p = polys;p;p = p->next)
422                                         {
423                                                 for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
424                                                 {
425                                                         f = VectorDistance2(wv, lightorigin);
426                                                         if (f < radius)
427                                                         {
428                                                                 f = radius2 / (f + LIGHTOFFSET);
429                                                                 wv[3] += cr * f;
430                                                                 wv[4] += cg * f;
431                                                                 wv[5] += cb * f;
432                                                                 lit = true;
433                                                         }
434                                                         wv += 6;
435                                                 }
436                                         }
437                                 }
438                         }
439                 }
440         }
441         return lit;
442 }
443
444 void RSurf_DrawWater(msurface_t *s, texture_t *t, int transform, int alpha)
445 {
446         int             i;
447         float   os = turbsin[(int)(realtime * TURBSCALE) & 255], ot = turbsin[(int)(realtime * TURBSCALE + 96.0) & 255];
448         glpoly_t *p;
449         float   *wv, *v;
450         wv = wvert;
451         for (p = s->polys;p;p = p->next)
452         {
453                 for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
454                 {
455                         if (transform)
456                                 softwaretransform(v, wv);
457                         else
458                                 VectorCopy(v, wv);
459                         if (r_waterripple.value)
460                                 wv[2] += r_waterripple.value * turbsin[(int)((wv[0]*(1.0f/32.0f)+realtime) * TURBSCALE) & 255] * turbsin[(int)((wv[1]*(1.0f/32.0f)+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f);
461                         wv[3] = wv[4] = wv[5] = 128.0f;
462                         wv += 6;
463                 }
464         }
465         if (s->dlightframe == r_dlightframecount && r_dynamic.value)
466                 RSurf_Light(s->dlightbits, s->polys);
467         wv = wvert;
468         // FIXME: make fog texture if water texture is transparent?
469         for (p=s->polys ; p ; p=p->next)
470         {
471                 transpolybegin(t->gl_texturenum, t->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
472                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE, wv += 6)
473                         transpolyvert(wv[0], wv[1], wv[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), wv[3], wv[4], wv[5], alpha);
474                 transpolyend();
475         }
476 }
477
478 void RSurf_CheckLightmap(msurface_t *s)
479 {
480         if (r_dynamic.value)
481         {
482                 if (r_ambient.value != s->cached_ambient || lighthalf != s->cached_lighthalf
483                 || (s->styles[0] != 255 && d_lightstylevalue[s->styles[0]] != s->cached_light[0])
484                 || (s->styles[1] != 255 && d_lightstylevalue[s->styles[1]] != s->cached_light[1])
485                 || (s->styles[2] != 255 && d_lightstylevalue[s->styles[2]] != s->cached_light[2])
486                 || (s->styles[3] != 255 && d_lightstylevalue[s->styles[3]] != s->cached_light[3]))
487                         R_UpdateLightmap(s, s->lightmaptexturenum);
488         }
489 }
490
491 void RSurf_Transform(glpoly_t *p, int transform)
492 {
493         int             i;
494         float   *v, *wv = wvert;
495         for (;p;p = p->next)
496         {
497                 for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
498                 {
499                         if (transform)
500                                 softwaretransform(v, wv);
501                         else
502                                 VectorCopy(v, wv);
503                         wv[3] = wv[4] = wv[5] = 0.0f;
504                         wv += 6;
505                 }
506         }
507 }
508
509 void RSurf_EmitWallpolys(int lightmap, glpoly_t *p, texture_t *t, int lit)
510 {
511         int             i;
512         float   *v, *wv = wvert;
513         wallpoly_t *wp = &wallpoly[currentwallpoly];
514         wallvert_t *out = &wallvert[currentwallvert];
515         for (;p;p = p->next)
516         {
517                 if (currentwallpoly >= MAX_WALLPOLYS)
518                         break;
519                 if (currentwallvert+p->numverts > MAX_WALLVERTS)
520                         break;
521                 v = p->verts[0];
522                 wp->texnum = (unsigned short) t->gl_texturenum;
523                 wp->lighttexnum = (unsigned short) lightmap;
524                 wp->glowtexnum = (unsigned short) t->gl_glowtexturenum;
525                 wp->firstvert = currentwallvert;
526                 wp->numverts = p->numverts;
527                 wp->lit = lit;
528                 wp++;
529                 currentwallpoly++;
530                 currentwallvert += p->numverts;
531                 for (i = 0;i < p->numverts;i++, v += VERTEXSIZE, wv += 6, out++)
532                 {
533                         if (lit)
534                         {
535                                 if (lighthalf)
536                                 {
537                                         out->r = (byte) (bound(0, (int) wv[3] >> 1, 255));
538                                         out->g = (byte) (bound(0, (int) wv[4] >> 1, 255));
539                                         out->b = (byte) (bound(0, (int) wv[5] >> 1, 255));
540                                         out->a = 255;
541                                 }
542                                 else
543                                 {
544                                         out->r = (byte) (bound(0, (int) wv[3], 255));
545                                         out->g = (byte) (bound(0, (int) wv[4], 255));
546                                         out->b = (byte) (bound(0, (int) wv[5], 255));
547                                         out->a = 255;
548                                 }
549                         }
550                         out->vert[0] = wv[0];
551                         out->vert[1] = wv[1];
552                         out->vert[2] = wv[2];
553                         out->s = v[3];
554                         out->t = v[4];
555                         out->u = v[5];
556                         out->v = v[6];
557                 }
558         }
559 }
560
561 void RSurf_DrawWall(msurface_t *s, texture_t *t, int transform)
562 {
563         int                     lit = false;
564         // check for lightmap modification
565         RSurf_CheckLightmap(s);
566         RSurf_Transform(s->polys, transform);
567         if (s->dlightframe == r_dlightframecount && r_dynamic.value)
568                 lit = RSurf_Light(s->dlightbits, s->polys);
569         RSurf_EmitWallpolys(lightmap_textures + s->lightmaptexturenum, s->polys, t, lit);
570 }
571
572 // LordHavoc: transparent brush models
573 extern int r_dlightframecount;
574 extern float modelalpha;
575
576 void RSurf_EmitWallVertex(glpoly_t *p, texture_t *t, int modulate, int alpha)
577 {
578         int i;
579         float *v, *wv = wvert;
580         if (modulate)
581         {
582                 for (;p;p = p->next)
583                 {
584                         v = p->verts[0];
585                         transpolybegin(t->gl_texturenum, t->gl_glowtexturenum, 0, currententity->effects & EF_ADDITIVE ? TPOLYTYPE_ADD : TPOLYTYPE_ALPHA);
586                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE, wv += 6)
587                                 transpolyvert(wv[0], wv[1], wv[2], v[3], v[4], wv[3] * currententity->colormod[0], wv[4] * currententity->colormod[1], wv[5] * currententity->colormod[2], alpha);
588                         transpolyend();
589                 }
590         }
591         else
592         {
593                 for (;p;p = p->next)
594                 {
595                         v = p->verts[0];
596                         transpolybegin(t->gl_texturenum, t->gl_glowtexturenum, 0, currententity->effects & EF_ADDITIVE ? TPOLYTYPE_ADD : TPOLYTYPE_ALPHA);
597                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE, wv += 6)
598                                 transpolyvert(wv[0], wv[1], wv[2], v[3], v[4], wv[3], wv[4], wv[5], alpha);
599                         transpolyend();
600                 }
601         }
602 }
603
604 void RSurf_WallVertexTransform(msurface_t *s, texture_t *t, int transform)
605 {
606         int                     i;
607         glpoly_t        *p;
608         float           *wv, *v;
609         int                     size3;
610         float           scale;
611         byte            *lm;
612         size3 = ((s->extents[0]>>4)+1)*((s->extents[1]>>4)+1)*3; // *3 for colored lighting
613         wv = wvert;
614         for (p = s->polys;p;p = p->next)
615         {
616                 for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
617                 {
618                         if (transform)
619                                 softwaretransform(v, wv);
620                         else
621                                 VectorCopy(v, wv);
622                         wv[3] = wv[4] = wv[5] = r_ambient.value * 2.0f;
623                         if (s->styles[0] != 255)
624                         {
625                                 lm = (byte *)((long) s->samples + (int) v[7]);
626                                 scale = d_lightstylevalue[s->styles[0]] * (1.0f / 128.0f);wv[3] += lm[size3*0+0] * scale;wv[4] += lm[size3*0+1] * scale;wv[5] += lm[size3*0+2] * scale;
627                                 if (s->styles[1] != 255)
628                                 {
629                                         scale = d_lightstylevalue[s->styles[1]] * (1.0f / 128.0f);wv[3] += lm[size3*1+0] * scale;wv[4] += lm[size3*1+1] * scale;wv[5] += lm[size3*1+2] * scale;
630                                         if (s->styles[2] != 255)
631                                         {
632                                                 scale = d_lightstylevalue[s->styles[2]] * (1.0f / 128.0f);wv[3] += lm[size3*2+0] * scale;wv[4] += lm[size3*2+1] * scale;wv[5] += lm[size3*2+2] * scale;
633                                                 if (s->styles[3] != 255)
634                                                 {
635                                                         scale = d_lightstylevalue[s->styles[3]] * (1.0f / 128.0f);wv[3] += lm[size3*3+0] * scale;wv[4] += lm[size3*3+1] * scale;wv[5] += lm[size3*3+2] * scale;
636                                                 }
637                                         }
638                                 }
639                         }
640                         wv += 6;
641                 }
642         }
643 }
644
645 void RSurf_DrawWallVertex(msurface_t *s, texture_t *t, int transform, int isbmodel)
646 {
647         RSurf_WallVertexTransform(s, t, transform);
648         if (s->dlightframe == r_dlightframecount && r_dynamic.value)
649                 RSurf_Light(s->dlightbits, s->polys);
650         RSurf_EmitWallVertex(s->polys, t, isbmodel && (currententity->colormod[0] != 1 || currententity->colormod[1] != 1 || currententity->colormod[2] != 1), (int) (modelalpha * 255.0f));
651 }
652
653 /*
654 ================
655 DrawTextureChains
656 ================
657 */
658 extern qboolean hlbsp;
659 extern char skyname[];
660 void R_DrawSurf(msurface_t *s, int isbmodel, int vertexlit)
661 {
662         texture_t *t;
663         if (s->flags & SURF_DRAWSKY)
664         {
665                 skyisvisible = true;
666                 if (!hlbsp) // LordHavoc: HalfLife maps have freaky skypolys...
667                         RSurf_DrawSky(s, false);
668                 return;
669         }
670         t = R_TextureAnimation (s->texinfo->texture);
671         if (s->flags & SURF_DRAWTURB)
672         {
673                 RSurf_DrawWater(s, t, false, s->flags & SURF_DRAWNOALPHA ? 255 : r_wateralpha.value*255.0f);
674                 return;
675         }
676         if (vertexlit)
677                 RSurf_DrawWallVertex(s, t, false, false);
678         else
679                 RSurf_DrawWall(s, t, false);
680 }
681
682 void DrawTextureChains (void)
683 {
684         int                     n;
685         msurface_t      *s;
686         texture_t       *t;
687
688         for (n = 0;n < cl.worldmodel->numtextures;n++)
689         {
690                 if (!cl.worldmodel->textures[n] || !(s = cl.worldmodel->textures[n]->texturechain))
691                         continue;
692                 cl.worldmodel->textures[n]->texturechain = NULL;
693 //              for (;s;s = s->texturechain)
694 //                      R_DrawSurf(s, false, gl_vertex.value);
695                 // LordHavoc: decide the render type only once, because the surface properties were determined by texture anyway
696                 // sky
697                 if (s->flags & SURF_DRAWSKY)
698                 {
699                         skyisvisible = true;
700                         if (!hlbsp) // LordHavoc: HalfLife maps have freaky skypolys...
701                                 for (;s;s = s->texturechain)
702                                         RSurf_DrawSky(s, false);
703                         continue;
704                 }
705                 t = R_TextureAnimation (cl.worldmodel->textures[n]);
706                 // subdivided water surface warp
707                 if (s->flags & SURF_DRAWTURB)
708                 {
709                         int alpha = s->flags & SURF_DRAWNOALPHA ? 255 : r_wateralpha.value*255.0f;
710                         for (;s;s = s->texturechain)
711                                 RSurf_DrawWater(s, t, false, alpha);
712                         continue;
713                 }
714                 if (gl_vertex.value)
715                         for (;s;s = s->texturechain)
716                                 RSurf_DrawWallVertex(s, t, false, false);
717                 else
718                         for (;s;s = s->texturechain)
719                                 RSurf_DrawWall(s, t, false);
720         }
721 }
722
723 void R_NoVisMarkLights (vec3_t lightorigin, dlight_t *light, int bit, int bitindex, model_t *model);
724
725 /*
726 =================
727 R_DrawBrushModel
728 =================
729 */
730 void R_DrawBrushModel (entity_t *e)
731 {
732         int                     i;
733         vec3_t          mins, maxs;
734         msurface_t      *s;
735         model_t         *clmodel;
736         int     rotated, vertexlit = false;
737         texture_t       *t;
738         vec3_t          org;
739
740         currententity = e;
741
742         clmodel = e->model;
743
744         if (e->angles[0] || e->angles[1] || e->angles[2])
745         {
746                 rotated = true;
747                 for (i=0 ; i<3 ; i++)
748                 {
749                         mins[i] = e->origin[i] - clmodel->radius;
750                         maxs[i] = e->origin[i] + clmodel->radius;
751                 }
752         }
753         else
754         {
755                 rotated = false;
756                 VectorAdd (e->origin, clmodel->mins, mins);
757                 VectorAdd (e->origin, clmodel->maxs, maxs);
758         }
759
760         if (R_CullBox (mins, maxs))
761                 return;
762
763         VectorSubtract (r_refdef.vieworg, e->origin, modelorg);
764         if (rotated)
765         {
766                 vec3_t  temp;
767                 vec3_t  forward, right, up;
768
769                 VectorCopy (modelorg, temp);
770                 AngleVectors (e->angles, forward, right, up);
771                 modelorg[0] = DotProduct (temp, forward);
772                 modelorg[1] = -DotProduct (temp, right);
773                 modelorg[2] = DotProduct (temp, up);
774         }
775
776         s = &clmodel->surfaces[clmodel->firstmodelsurface];
777
778 // calculate dynamic lighting for bmodel if it's not an
779 // instanced model
780         for (i = 0;i < MAX_DLIGHTS;i++)
781         {
782                 if ((cl_dlights[i].die < cl.time) || (!cl_dlights[i].radius))
783                         continue;
784
785                 VectorSubtract(cl_dlights[i].origin, currententity->origin, org);
786                 R_NoVisMarkLights (org, &cl_dlights[i], 1<<(i&31), i >> 5, clmodel);
787         }
788         vertexlit = modelalpha != 1 || clmodel->firstmodelsurface == 0 || (currententity->effects & EF_FULLBRIGHT) || currententity->colormod[0] != 1 || currententity->colormod[2] != 1 || currententity->colormod[2] != 1;
789
790 e->angles[0] = -e->angles[0];   // stupid quake bug
791         softwaretransformforentity (e);
792 e->angles[0] = -e->angles[0];   // stupid quake bug
793
794         // draw texture
795         for (i = 0;i < clmodel->nummodelsurfaces;i++, s++)
796         {
797                 if (((s->flags & SURF_PLANEBACK) == 0) == (PlaneDiff(modelorg, s->plane) >= 0))
798                 {
799 //                      R_DrawSurf(s, true, vertexlit || s->texinfo->texture->transparent);
800                         if (s->flags & SURF_DRAWSKY)
801                         {
802                                 RSurf_DrawSky(s, true);
803                                 continue;
804                         }
805                         t = R_TextureAnimation (s->texinfo->texture);
806                         if (s->flags & SURF_DRAWTURB)
807                         {
808                                 RSurf_DrawWater(s, t, true, s->flags & SURF_DRAWNOALPHA ? 255 : r_wateralpha.value*255.0f);
809                                 continue;
810                         }
811                         if (vertexlit || s->texinfo->texture->transparent)
812                                 RSurf_DrawWallVertex(s, t, true, true);
813                         else
814                                 RSurf_DrawWall(s, t, true);
815                 }
816         }
817         UploadLightmaps();
818 }
819
820 /*
821 =============================================================
822
823         WORLD MODEL
824
825 =============================================================
826 */
827
828 void R_StoreEfrags (efrag_t **ppefrag);
829
830 struct nodestack_s
831 {
832         int side;
833         mnode_t *node;
834 } nodestack[8192];
835
836 /*
837 ================
838 R_WorldNode
839 ================
840 */
841 void R_WorldNode ()
842 {
843         int side, texsort, vertex;
844         struct nodestack_s *nstack;
845         mnode_t *node;
846         mleaf_t *pleaf;
847         msurface_t *surf, *endsurf, **mark, **endmark;
848         nstack = nodestack;
849         texsort = gl_texsort.value;
850         vertex = gl_vertex.value;
851
852         if (!(node = cl.worldmodel->nodes))
853                 return;
854
855         while(1)
856         {
857         // if a leaf node, draw stuff
858                 if (node->contents < 0)
859                 {
860                         if (node->contents != CONTENTS_SOLID)
861                         {
862                                 pleaf = (mleaf_t *)node;
863
864                                 c_leafs++;
865                                 if (pleaf->nummarksurfaces)
866                                 {
867                                         mark = pleaf->firstmarksurface;
868                                         endmark = mark + pleaf->nummarksurfaces;
869                                         do
870                                         {
871                                                 (*mark)->visframe = r_framecount;
872                                                 mark++;
873                                         }
874                                         while (mark < endmark);
875                                 }
876
877                                 // deal with model fragments in this leaf
878                                 if (pleaf->efrags)
879                                         R_StoreEfrags (&pleaf->efrags);
880                         }
881
882                         if (nstack <= nodestack)
883                                 break;
884                         nstack--;
885                         node = nstack->node;
886                         side = nstack->side;
887                         goto loc0;
888                 }
889
890                 c_nodes++;
891
892                 // node is just a decision point, so go down the apropriate sides
893
894                 // find which side of the node we are on
895                 side = PlaneDist(modelorg, node->plane) < node->plane->dist;
896
897                 // recurse down the children, front side first
898                 if (node->children[side]->visframe == r_visframecount && R_NotCulledBox(node->children[side]->minmaxs, node->children[side]->minmaxs+3))
899                 {
900                         nstack->node = node;
901                         nstack->side = !side; // go down back side when we come back up
902                         nstack++;
903                         node = node->children[side];
904                         continue;
905                 }
906                 side = !side;
907 loc0:
908
909         // draw stuff
910                 if (node->numsurfaces)
911                 {
912                         surf = cl.worldmodel->surfaces + node->firstsurface;
913                         endsurf = surf + node->numsurfaces;
914
915                         if (texsort)
916                         {
917                                 if (side)
918                                 {
919                                         do
920                                         {
921                                                 if (surf->visframe == r_framecount && !(surf->flags & SURF_PLANEBACK))
922                                                 {
923                                                         surf->texturechain = surf->texinfo->texture->texturechain;
924                                                         surf->texinfo->texture->texturechain = surf;
925                                                 }
926                                                 surf++;
927                                         }
928                                         while (surf < endsurf);
929                                 }
930                                 else
931                                 {
932                                         do
933                                         {
934                                                 if (surf->visframe == r_framecount && (surf->flags & SURF_PLANEBACK))
935                                                 {
936                                                         surf->texturechain = surf->texinfo->texture->texturechain;
937                                                         surf->texinfo->texture->texturechain = surf;
938                                                 }
939                                                 surf++;
940                                         }
941                                         while (surf < endsurf);
942                                 }
943                         }
944                         else
945                         {
946                                 if (side)
947                                 {
948                                         do
949                                         {
950                                                 if (surf->visframe == r_framecount && !(surf->flags & SURF_PLANEBACK))
951                                                         R_DrawSurf(surf, false, vertex);
952                                                 surf++;
953                                         }
954                                         while (surf < endsurf);
955                                 }
956                                 else
957                                 {
958                                         do
959                                         {
960                                                 if (surf->visframe == r_framecount && (surf->flags & SURF_PLANEBACK))
961                                                         R_DrawSurf(surf, false, vertex);
962                                                 surf++;
963                                         }
964                                         while (surf < endsurf);
965                                 }
966                         }
967                 }
968
969         // recurse down the back side
970                 if (node->children[side]->visframe == r_visframecount && R_NotCulledBox(node->children[side]->minmaxs, node->children[side]->minmaxs+3))
971                 {
972                         node = node->children[side];
973                         continue;
974                 }
975
976                 if (nstack <= nodestack)
977                         break;
978                 nstack--;
979                 node = nstack->node;
980                 side = nstack->side;
981                 goto loc0;
982         }
983 }
984
985
986 /*
987 =============
988 R_DrawWorld
989 =============
990 */
991 void R_DrawWorld (void)
992 {
993         entity_t        ent;
994
995         memset (&ent, 0, sizeof(ent));
996         ent.model = cl.worldmodel;
997         ent.colormod[0] = ent.colormod[1] = ent.colormod[2] = 1;
998         modelalpha = ent.alpha = 1;
999         ent.scale = 1;
1000
1001         VectorCopy (r_refdef.vieworg, modelorg);
1002
1003         currententity = &ent;
1004
1005         softwaretransformidentity(); // LordHavoc: clear transform
1006
1007         if (cl.worldmodel)
1008                 R_WorldNode ();
1009
1010         R_PushDlights (); // now mark the lit surfaces
1011
1012         DrawTextureChains ();
1013 }
1014
1015
1016 /*
1017 ===============
1018 R_MarkLeaves
1019 ===============
1020 */
1021 void R_MarkLeaves (void)
1022 {
1023         byte    *vis;
1024         mnode_t *node;
1025         int             i;
1026
1027         if (r_oldviewleaf == r_viewleaf && !r_novis.value)
1028                 return;
1029         
1030         r_visframecount++;
1031         r_oldviewleaf = r_viewleaf;
1032
1033         if (r_novis.value)
1034         {
1035                 for (i=0 ; i<cl.worldmodel->numleafs ; i++)
1036                 {
1037                         node = (mnode_t *)&cl.worldmodel->leafs[i+1];
1038                         do
1039                         {
1040                                 if (node->visframe == r_visframecount)
1041                                         break;
1042                                 node->visframe = r_visframecount;
1043                                 node = node->parent;
1044                         } while (node);
1045                 }
1046         }
1047         else
1048         {
1049                 vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel);
1050                 
1051                 for (i=0 ; i<cl.worldmodel->numleafs ; i++)
1052                 {
1053                         if (vis[i>>3] & (1<<(i&7)))
1054                         {
1055                                 node = (mnode_t *)&cl.worldmodel->leafs[i+1];
1056                                 do
1057                                 {
1058                                         if (node->visframe == r_visframecount)
1059                                                 break;
1060                                         node->visframe = r_visframecount;
1061                                         node = node->parent;
1062                                 } while (node);
1063                         }
1064                 }
1065         }
1066 }
1067
1068
1069
1070 /*
1071 =============================================================================
1072
1073   LIGHTMAP ALLOCATION
1074
1075 =============================================================================
1076 */
1077
1078 // returns a texture number and the position inside it
1079 int AllocBlock (int w, int h, short *x, short *y)
1080 {
1081         int             i, j;
1082         int             best, best2;
1083         int             texnum;
1084
1085         for (texnum=0 ; texnum<MAX_LIGHTMAPS ; texnum++)
1086         {
1087                 best = BLOCK_HEIGHT;
1088
1089                 for (i=0 ; i<BLOCK_WIDTH-w ; i+=lightmapalign) // LordHavoc: NVIDIA has broken subimage, so align the lightmaps
1090                 {
1091                         best2 = 0;
1092
1093                         for (j=0 ; j<w ; j++)
1094                         {
1095                                 if (allocated[texnum][i+j] >= best)
1096                                         break;
1097                                 if (allocated[texnum][i+j] > best2)
1098                                         best2 = allocated[texnum][i+j];
1099                         }
1100                         if (j == w)
1101                         {       // this is a valid spot
1102                                 *x = i;
1103                                 *y = best = best2;
1104                         }
1105                 }
1106
1107                 if (best + h > BLOCK_HEIGHT)
1108                         continue;
1109
1110                 if (nosubimagefragments || nosubimage)
1111                 {
1112                         if (!lightmaps[texnum])
1113                                 lightmaps[texnum] = calloc(BLOCK_WIDTH*BLOCK_HEIGHT*4, 1);
1114                 }
1115                 // LordHavoc: clear texture to blank image, fragments are uploaded using subimage
1116                 else if (!allocated[texnum][0])
1117                 {
1118                         byte blank[BLOCK_WIDTH*BLOCK_HEIGHT*3];
1119                         memset(blank, 0, sizeof(blank));
1120                         if(r_upload.value)
1121                         {
1122                                 glBindTexture(GL_TEXTURE_2D, lightmap_textures + texnum);
1123                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1124                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1125                                 if (lightmaprgba)
1126                                         glTexImage2D (GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, blank);
1127                                 else
1128                                         glTexImage2D (GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, blank);
1129                         }
1130                 }
1131
1132                 for (i=0 ; i<w ; i++)
1133                         allocated[texnum][*x + i] = best + h;
1134
1135                 return texnum;
1136         }
1137
1138         Sys_Error ("AllocBlock: full");
1139         return 0;
1140 }
1141
1142
1143 mvertex_t       *r_pcurrentvertbase;
1144 model_t         *currentmodel;
1145
1146 int     nColinElim;
1147
1148 /*
1149 ================
1150 BuildSurfaceDisplayList
1151 ================
1152 */
1153 void BuildSurfaceDisplayList (msurface_t *fa)
1154 {
1155         int                     i, j, lindex, lnumverts;
1156         medge_t         *pedges, *r_pedge;
1157         int                     vertpage;
1158         float           *vec;
1159         float           s, t;
1160         glpoly_t        *poly;
1161
1162 // reconstruct the polygon
1163         pedges = currentmodel->edges;
1164         lnumverts = fa->numedges;
1165         vertpage = 0;
1166
1167         //
1168         // draw texture
1169         //
1170         poly = Hunk_Alloc (sizeof(glpoly_t) + (lnumverts-4) * VERTEXSIZE*sizeof(float));
1171         poly->next = fa->polys;
1172         poly->flags = fa->flags;
1173         fa->polys = poly;
1174         poly->numverts = lnumverts;
1175
1176         for (i=0 ; i<lnumverts ; i++)
1177         {
1178                 lindex = currentmodel->surfedges[fa->firstedge + i];
1179
1180                 if (lindex > 0)
1181                 {
1182                         r_pedge = &pedges[lindex];
1183                         vec = r_pcurrentvertbase[r_pedge->v[0]].position;
1184                 }
1185                 else
1186                 {
1187                         r_pedge = &pedges[-lindex];
1188                         vec = r_pcurrentvertbase[r_pedge->v[1]].position;
1189                 }
1190                 s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3];
1191                 t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3];
1192
1193                 VectorCopy (vec, poly->verts[i]);
1194                 poly->verts[i][3] = s / fa->texinfo->texture->width;
1195                 poly->verts[i][4] = t / fa->texinfo->texture->height;
1196
1197                 //
1198                 // lightmap texture coordinates
1199                 //
1200                 s -= fa->texturemins[0];
1201                 t -= fa->texturemins[1];
1202                 s += 8;
1203                 t += 8;
1204                 // LordHavoc: calc lightmap data offset
1205                 j = (bound(0l, (int)t>>4, fa->extents[1]>>4) * ((fa->extents[0]>>4)+1) + bound(0l, (int)s>>4, fa->extents[0]>>4)) * 3;
1206                 poly->verts[i][7] = j;
1207                 s += fa->light_s*16;
1208                 s /= BLOCK_WIDTH*16; //fa->texinfo->texture->width;
1209
1210                 t += fa->light_t*16;
1211                 t /= BLOCK_HEIGHT*16; //fa->texinfo->texture->height;
1212
1213                 poly->verts[i][5] = s;
1214                 poly->verts[i][6] = t;
1215         }
1216
1217         //
1218         // remove co-linear points - Ed
1219         //
1220         /*
1221         if (!gl_keeptjunctions.value)
1222         {
1223                 for (i = 0 ; i < lnumverts ; ++i)
1224                 {
1225                         vec3_t v1, v2;
1226                         float *prev, *this, *next;
1227
1228                         prev = poly->verts[(i + lnumverts - 1) % lnumverts];
1229                         this = poly->verts[i];
1230                         next = poly->verts[(i + 1) % lnumverts];
1231
1232                         VectorSubtract( this, prev, v1 );
1233                         VectorNormalize( v1 );
1234                         VectorSubtract( next, prev, v2 );
1235                         VectorNormalize( v2 );
1236
1237                         // skip co-linear points
1238                         #define COLINEAR_EPSILON 0.001
1239                         if ((fabs( v1[0] - v2[0] ) <= COLINEAR_EPSILON) &&
1240                                 (fabs( v1[1] - v2[1] ) <= COLINEAR_EPSILON) && 
1241                                 (fabs( v1[2] - v2[2] ) <= COLINEAR_EPSILON))
1242                         {
1243                                 int j;
1244                                 for (j = i + 1; j < lnumverts; ++j)
1245                                 {
1246                                         int k;
1247                                         for (k = 0; k < VERTEXSIZE; ++k)
1248                                                 poly->verts[j - 1][k] = poly->verts[j][k];
1249                                 }
1250                                 --lnumverts;
1251                                 ++nColinElim;
1252                                 // retry next vertex next time, which is now current vertex
1253                                 --i;
1254                         }
1255                 }
1256         }
1257         */
1258         poly->numverts = lnumverts;
1259 }
1260
1261 /*
1262 ========================
1263 GL_CreateSurfaceLightmap
1264 ========================
1265 */
1266 void GL_CreateSurfaceLightmap (msurface_t *surf)
1267 {
1268         int             smax, tmax;
1269
1270         if (surf->flags & (SURF_DRAWSKY|SURF_DRAWTURB))
1271                 return;
1272
1273         smax = (surf->extents[0]>>4)+1;
1274         tmax = (surf->extents[1]>>4)+1;
1275
1276         surf->lightmaptexturenum = AllocBlock (smax, tmax, &surf->light_s, &surf->light_t);
1277         if (nosubimage || nosubimagefragments)
1278                 return;
1279         glBindTexture(GL_TEXTURE_2D, lightmap_textures + surf->lightmaptexturenum);
1280         smax = ((surf->extents[0]>>4)+lightmapalign) & lightmapalignmask;
1281         if (lightmaprgba)
1282         {
1283                 R_BuildLightMap (surf, templight, smax * 4);
1284                 if(r_upload.value)
1285                         glTexSubImage2D(GL_TEXTURE_2D, 0, surf->light_s, surf->light_t, smax, tmax, GL_RGBA, GL_UNSIGNED_BYTE, templight);
1286         }
1287         else
1288         {
1289                 R_BuildLightMap (surf, templight, smax * 3);
1290                 if(r_upload.value)
1291                         glTexSubImage2D(GL_TEXTURE_2D, 0, surf->light_s, surf->light_t, smax, tmax, GL_RGB , GL_UNSIGNED_BYTE, templight);
1292         }
1293 }
1294
1295
1296 /*
1297 ==================
1298 GL_BuildLightmaps
1299
1300 Builds the lightmap texture
1301 with all the surfaces from all brush models
1302 ==================
1303 */
1304 void GL_BuildLightmaps (void)
1305 {
1306         int             i, j;
1307         model_t *m;
1308
1309         memset (allocated, 0, sizeof(allocated));
1310
1311         r_framecount = 1;               // no dlightcache
1312
1313         if (gl_nosubimagefragments.value)
1314                 nosubimagefragments = 1;
1315         else
1316                 nosubimagefragments = 0;
1317
1318         if (gl_nosubimage.value)
1319                 nosubimage = 1;
1320         else
1321                 nosubimage = 0;
1322
1323         if (gl_lightmaprgba.value)
1324         {
1325                 lightmaprgba = true;
1326                 lightmapbytes = 4;
1327         }
1328         else
1329         {
1330                 lightmaprgba = false;
1331                 lightmapbytes = 3;
1332         }
1333
1334         // LordHavoc: NVIDIA seems to have a broken glTexSubImage2D,
1335         //            it needs to be aligned on 4 pixel boundaries...
1336         //            so I implemented an adjustable lightmap alignment
1337         if (gl_lightmapalign.value < 1)
1338                 gl_lightmapalign.value = 1;
1339         if (gl_lightmapalign.value > 16)
1340                 gl_lightmapalign.value = 16;
1341         lightmapalign = 1;
1342         while (lightmapalign < gl_lightmapalign.value)
1343                 lightmapalign <<= 1;
1344         gl_lightmapalign.value = lightmapalign;
1345         lightmapalignmask = ~(lightmapalign - 1);
1346         if (nosubimagefragments || nosubimage)
1347         {
1348                 lightmapalign = 1;
1349                 lightmapalignmask = ~0;
1350         }
1351
1352         if (!lightmap_textures)
1353         {
1354                 lightmap_textures = texture_extension_number;
1355                 texture_extension_number += MAX_LIGHTMAPS;
1356         }
1357
1358         for (j=1 ; j<MAX_MODELS ; j++)
1359         {
1360                 m = cl.model_precache[j];
1361                 if (!m)
1362                         break;
1363                 if (m->name[0] == '*')
1364                         continue;
1365                 r_pcurrentvertbase = m->vertexes;
1366                 currentmodel = m;
1367                 for (i=0 ; i<m->numsurfaces ; i++)
1368                 {
1369                         if ( m->surfaces[i].flags & SURF_DRAWTURB )
1370                                 continue;
1371                         if ( m->surfaces[i].flags & SURF_DRAWSKY )
1372                                 continue;
1373                         GL_CreateSurfaceLightmap (m->surfaces + i);
1374                         BuildSurfaceDisplayList (m->surfaces + i);
1375                 }
1376         }
1377
1378         if (nosubimage || nosubimagefragments)
1379         {
1380                 if(r_upload.value)
1381                         if (gl_mtexable)
1382                                 qglSelectTexture(gl_mtex_enum+1);
1383                 for (i = 0;i < MAX_LIGHTMAPS;i++)
1384                 {
1385                         if (!allocated[i][0])
1386                                 break;
1387                         lightmapupdate[i][0] = BLOCK_HEIGHT;
1388                         lightmapupdate[i][1] = 0;
1389                         if(r_upload.value)
1390                         {
1391                                 glBindTexture(GL_TEXTURE_2D, lightmap_textures + i);
1392                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1393                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1394                                 if (lightmaprgba)
1395                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i]);
1396                                 else
1397                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i]);
1398                         }
1399                 }
1400                 if(r_upload.value)
1401                         if (gl_mtexable)
1402                                 qglSelectTexture(gl_mtex_enum+0);
1403         }
1404 }
1405