]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - gl_rmain.c
colormod values above 1 1 1 should work properly with r_glsl now
[xonotic/darkplaces.git] / gl_rmain.c
index 034e54149975e763870b8c8cf57aba9db2045a2f..c9f0c2071ab04932919321240a6c569ffbd69748 100644 (file)
@@ -20,6 +20,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 // r_main.c
 
 #include "quakedef.h"
+#include "cl_dyntexture.h"
 #include "r_shadow.h"
 #include "polygon.h"
 #include "image.h"
@@ -63,6 +64,7 @@ cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "
 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
 cvar_t r_polygonoffset_submodel_factor = {0, "r_polygonoffset_submodel_factor", "0", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "2", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
+cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
 
 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
@@ -71,6 +73,7 @@ cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (fo
 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
+cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
 
 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of hardware texture units reported by driver (note: setting this to 1 turns off gl_combine)"};
 
@@ -89,6 +92,7 @@ cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "h
 
 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "1", "enables animation smoothing on sprites (requires r_lerpmodels 1)"};
 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
+cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
 
 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
@@ -112,6 +116,10 @@ cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture
 
 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
+cvar_t r_track_sprites = {CVAR_SAVE, "r_track_sprites", "1", "track SPR_LABEL* sprites by putting them as indicator at the screen border to rotate to"};
+cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
+cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
+cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
 
 extern qboolean v_flipped_state;
 
@@ -240,44 +248,54 @@ void FOG_clear(void)
                Cvar_Set("gl_foggreen", "0.3");
                Cvar_Set("gl_fogblue", "0.3");
        }
-       r_refdef.fog_density = r_refdef.fog_red = r_refdef.fog_green = r_refdef.fog_blue = 0.0f;
+       r_refdef.fog_density = 0;
+       r_refdef.fog_red = 0;
+       r_refdef.fog_green = 0;
+       r_refdef.fog_blue = 0;
+       r_refdef.fog_alpha = 1;
+       r_refdef.fog_start = 0;
+       r_refdef.fog_end = 0;
 }
 
-float FogPoint_World(const vec3_t p)
+float FogForDistance(vec_t dist)
 {
-       int fogmasktableindex = (int)(VectorDistance((p), r_view.origin) * r_refdef.fogmasktabledistmultiplier);
+       unsigned int fogmasktableindex = (unsigned int)(dist * r_refdef.fogmasktabledistmultiplier);
        return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
 }
 
+float FogPoint_World(const vec3_t p)
+{
+       return FogForDistance(VectorDistance((p), r_view.origin));
+}
+
 float FogPoint_Model(const vec3_t p)
 {
-       int fogmasktableindex = (int)(VectorDistance((p), rsurface.modelorg) * r_refdef.fogmasktabledistmultiplier);
-       return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
+       return FogForDistance(VectorDistance((p), rsurface.modelorg));
 }
 
 static void R_BuildBlankTextures(void)
 {
        unsigned char data[4];
-       data[0] = 128; // normal X
+       data[2] = 128; // normal X
        data[1] = 128; // normal Y
-       data[2] = 255; // normal Z
+       data[0] = 255; // normal Z
        data[3] = 128; // height
-       r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
+       r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
        data[0] = 255;
        data[1] = 255;
        data[2] = 255;
        data[3] = 255;
-       r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
+       r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
        data[0] = 128;
        data[1] = 128;
        data[2] = 128;
        data[3] = 255;
-       r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
+       r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
        data[0] = 0;
        data[1] = 0;
        data[2] = 0;
        data[3] = 255;
-       r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
+       r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
 }
 
 static void R_BuildNoTexture(void)
@@ -305,19 +323,14 @@ static void R_BuildNoTexture(void)
                        }
                }
        }
-       r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_RGBA, TEXF_MIPMAP, NULL);
+       r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, NULL);
 }
 
 static void R_BuildWhiteCube(void)
 {
        unsigned char data[6*1*1*4];
-       data[ 0] = 255;data[ 1] = 255;data[ 2] = 255;data[ 3] = 255;
-       data[ 4] = 255;data[ 5] = 255;data[ 6] = 255;data[ 7] = 255;
-       data[ 8] = 255;data[ 9] = 255;data[10] = 255;data[11] = 255;
-       data[12] = 255;data[13] = 255;data[14] = 255;data[15] = 255;
-       data[16] = 255;data[17] = 255;data[18] = 255;data[19] = 255;
-       data[20] = 255;data[21] = 255;data[22] = 255;data[23] = 255;
-       r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
+       memset(data, 255, sizeof(data));
+       r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
 }
 
 static void R_BuildNormalizationCube(void)
@@ -370,22 +383,45 @@ static void R_BuildNormalizationCube(void)
                                        break;
                                }
                                intensity = 127.0f / sqrt(DotProduct(v, v));
-                               data[side][y][x][0] = (unsigned char)(128.0f + intensity * v[0]);
+                               data[side][y][x][2] = (unsigned char)(128.0f + intensity * v[0]);
                                data[side][y][x][1] = (unsigned char)(128.0f + intensity * v[1]);
-                               data[side][y][x][2] = (unsigned char)(128.0f + intensity * v[2]);
+                               data[side][y][x][0] = (unsigned char)(128.0f + intensity * v[2]);
                                data[side][y][x][3] = 255;
                        }
                }
        }
-       r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, &data[0][0][0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
+       r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, &data[0][0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
 }
 
 static void R_BuildFogTexture(void)
 {
        int x, b;
-#define FOGWIDTH 64
+#define FOGWIDTH 256
        unsigned char data1[FOGWIDTH][4];
        //unsigned char data2[FOGWIDTH][4];
+       double d, r, alpha;
+
+       r_refdef.fogmasktable_start = r_refdef.fog_start;
+       r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
+       r_refdef.fogmasktable_range = r_refdef.fogrange;
+       r_refdef.fogmasktable_density = r_refdef.fog_density;
+
+       r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
+       for (x = 0;x < FOGMASKTABLEWIDTH;x++)
+       {
+               d = (x * r - r_refdef.fogmasktable_start);
+               Con_Printf("%f ", d);
+               d = max(0, d);
+               if (r_fog_exp2.integer)
+                       alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
+               else
+                       alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
+               Con_Printf(" : %f ", alpha);
+               alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
+               Con_Printf(" = %f\n", alpha);
+               r_refdef.fogmasktable[x] = bound(0, alpha, 1);
+       }
+
        for (x = 0;x < FOGWIDTH;x++)
        {
                b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
@@ -398,8 +434,16 @@ static void R_BuildFogTexture(void)
                //data2[x][2] = 255 - b;
                //data2[x][3] = 255;
        }
-       r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
-       //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
+       if (r_texture_fogattenuation)
+       {
+               R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
+               //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
+       }
+       else
+       {
+               r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
+               //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
+       }
 }
 
 static const char *builtinshaderstring =
@@ -567,6 +611,9 @@ static const char *builtinshaderstring =
 "uniform myhvec3 Color_Shirt;\n"
 "uniform myhvec3 FogColor;\n"
 "\n"
+"uniform myhvec4 TintColor;\n"
+"\n"
+"\n"
 "//#ifdef MODE_WATER\n"
 "uniform vec4 DistortScaleRefractReflect;\n"
 "uniform vec4 ScreenScaleRefractReflect;\n"
@@ -740,7 +787,6 @@ static const char *builtinshaderstring =
 "      //color.rgb *= normalize(CubeVector) * 0.5 + 0.5;//vec3(textureCube(Texture_Cube, CubeVector));\n"
 "      color.rgb *= myhvec3(textureCube(Texture_Cube, CubeVector));\n"
 "# endif\n"
-"      color *= myhvec4(gl_Color);\n"
 "#endif // MODE_LIGHTSOURCE\n"
 "\n"
 "\n"
@@ -748,18 +794,29 @@ static const char *builtinshaderstring =
 "\n"
 "#ifdef MODE_LIGHTDIRECTION\n"
 "      // directional model lighting\n"
-"\n"
+"# ifdef USESPECULAR\n"
 "      // get the surface normal and light normal\n"
 "      myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
 "      myhvec3 diffusenormal = myhvec3(LightVector);\n"
 "\n"
 "      // calculate directional shading\n"
 "      color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
-"# ifdef USESPECULAR\n"
 "      myhvec3 specularnormal = normalize(diffusenormal + myhvec3(normalize(EyeVector)));\n"
 "      color.rgb += myhvec3(texture2D(Texture_Gloss, TexCoord)) * SpecularColor * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
+"# else\n"
+"#  ifdef USEDIFFUSE\n"
+"      // get the surface normal and light normal\n"
+"      myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
+"      myhvec3 diffusenormal = myhvec3(LightVector);\n"
+"\n"
+"      // calculate directional shading\n"
+"      color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
+"#  else\n"
+"      color.rgb *= AmbientColor;\n"
+"#  endif\n"
 "# endif\n"
-"      color *= myhvec4(gl_Color);\n"
+"\n"
+"      color.a *= TintColor.a;\n"
 "#endif // MODE_LIGHTDIRECTION\n"
 "\n"
 "\n"
@@ -781,7 +838,9 @@ static const char *builtinshaderstring =
 "# endif\n"
 "\n"
 "      // apply lightmap color\n"
-"      color.rgb = myhvec4(tempcolor,1) * myhvec4(texture2D(Texture_Lightmap, TexCoordLightmap)) * myhvec4(gl_Color) + myhvec4(color.rgb * AmbientScale, 0);\n"
+"      color.rgb = color.rgb * AmbientScale + tempcolor * myhvec3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
+"\n"
+"      color *= TintColor;\n"
 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
 "\n"
 "\n"
@@ -802,7 +861,9 @@ static const char *builtinshaderstring =
 "# endif\n"
 "\n"
 "      // apply lightmap color\n"
-"      color = myhvec4(tempcolor, 1) * myhvec4(texture2D(Texture_Lightmap, TexCoordLightmap)) * myhvec4(gl_Color) + myhvec4(color.rgb * AmbientScale, 0);\n"
+"      color.rgb = color.rgb * AmbientScale + tempcolor * myhvec3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
+"\n"
+"      color *= TintColor;\n"
 "#endif // MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
 "\n"
 "\n"
@@ -810,12 +871,31 @@ static const char *builtinshaderstring =
 "\n"
 "#ifdef MODE_LIGHTMAP\n"
 "      // apply lightmap color\n"
-"      color *= myhvec4(texture2D(Texture_Lightmap, TexCoordLightmap)) * myhvec4(gl_Color) * myhvec4(myhvec3(DiffuseScale), 1) + myhvec4(myhvec3(AmbientScale), 0);\n"
+"      color.rgb = color.rgb * myhvec3(texture2D(Texture_Lightmap, TexCoordLightmap)) * DiffuseScale + color.rgb * AmbientScale;\n"
+"\n"
+"      color *= TintColor;\n"
 "#endif // MODE_LIGHTMAP\n"
 "\n"
 "\n"
 "\n"
 "\n"
+"#ifdef MODE_VERTEXCOLOR\n"
+"      // apply lightmap color\n"
+"      color.rgb = color.rgb * myhvec3(gl_Color.rgb) * DiffuseScale + color.rgb * AmbientScale;\n"
+"\n"
+"      color *= TintColor;\n"
+"#endif // MODE_VERTEXCOLOR\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"#ifdef MODE_FLATCOLOR\n"
+"      color *= TintColor;\n"
+"#endif // MODE_FLATCOLOR\n"
+"\n"
+"\n"
+"\n"
+"\n"
 "\n"
 "\n"
 "\n"
@@ -830,18 +910,17 @@ static const char *builtinshaderstring =
 "\n"
 "      color.rgb *= SceneBrightness;\n"
 "\n"
-"#ifndef MODE_LIGHTSOURCE\n"
-"# ifdef USEREFLECTION\n"
+"      // apply fog after Contrastboost/SceneBrightness because its color is already modified appropriately\n"
+"#ifdef USEFOG\n"
+"      color.rgb = mix(FogColor, color.rgb, myhalf(texture2D(Texture_FogMask, myhvec2(length(EyeVectorModelSpace)*FogRangeRecip, 0.0))));\n"
+"#endif\n"
+"\n"
+"      // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
+"#ifdef USEREFLECTION\n"
 "      vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
 "      //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
 "      vec4 ScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect + vec3(normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
 "      color.rgb = mix(color.rgb, myhvec3(texture2D(Texture_Reflection, ScreenTexCoord.zw)) * ReflectColor.rgb, ReflectColor.a);\n"
-"# endif\n"
-"#endif\n"
-"\n"
-"#ifdef USEFOG\n"
-"      // apply fog\n"
-"      color.rgb = mix(FogColor, color.rgb, myhalf(texture2D(Texture_FogMask, myhvec2(length(EyeVectorModelSpace)*FogRangeRecip, 0.0))));\n"
 "#endif\n"
 "\n"
 "      gl_FragColor = vec4(color);\n"
@@ -883,9 +962,11 @@ const char *shaderpermutationinfo[][2] =
 // this enum is multiplied by SHADERPERMUTATION_MODEBASE
 typedef enum shadermode_e
 {
-       SHADERMODE_LIGHTMAP, // (lightmap) use directional pixel shading from fixed light direction (q3bsp)
-       SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, // (lightmap) use directional pixel shading from texture containing modelspace light directions (deluxemap)
-       SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, // (lightmap) use directional pixel shading from texture containing tangentspace light directions (deluxemap)
+       SHADERMODE_FLATCOLOR, // (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
+       SHADERMODE_VERTEXCOLOR, // (lightmap) modulate texture by vertex colors (q3bsp)
+       SHADERMODE_LIGHTMAP, // (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
+       SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, // (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
+       SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, // (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
        SHADERMODE_LIGHTDIRECTION, // (lightmap) use directional pixel shading from fixed light direction (q3bsp)
        SHADERMODE_LIGHTSOURCE, // (lightsource) use directional pixel shading from light source (rtlight)
        SHADERMODE_REFRACTION, // refract background (the material is rendered normally after this pass)
@@ -897,6 +978,8 @@ shadermode_t;
 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
 const char *shadermodeinfo[][2] =
 {
+       {"#define MODE_FLATCOLOR\n", " flatcolor"},
+       {"#define MODE_VERTEXCOLOR\n", " vertexcolor"},
        {"#define MODE_LIGHTMAP\n", " lightmap"},
        {"#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
        {"#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
@@ -943,6 +1026,7 @@ typedef struct r_glsl_permutation_s
        int loc_GlowScale;
        int loc_SceneBrightness; // or: Scenebrightness * ContrastBoost
        int loc_OffsetMapping_Scale;
+       int loc_TintColor;
        int loc_AmbientColor;
        int loc_DiffuseColor;
        int loc_SpecularColor;
@@ -1074,6 +1158,7 @@ static void R_GLSL_CompilePermutation(const char *filename, int permutation, int
                p->loc_GlowScale           = qglGetUniformLocationARB(p->program, "GlowScale");
                p->loc_SceneBrightness     = qglGetUniformLocationARB(p->program, "SceneBrightness");
                p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
+               p->loc_TintColor       = qglGetUniformLocationARB(p->program, "TintColor");
                p->loc_AmbientColor        = qglGetUniformLocationARB(p->program, "AmbientColor");
                p->loc_DiffuseColor        = qglGetUniformLocationARB(p->program, "DiffuseColor");
                p->loc_SpecularColor       = qglGetUniformLocationARB(p->program, "SpecularColor");
@@ -1196,13 +1281,11 @@ int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, fl
                        permutation |= SHADERPERMUTATION_COLORMAPPING;
                if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
                        permutation |= SHADERPERMUTATION_CONTRASTBOOST;
-               if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
-                       permutation |= SHADERPERMUTATION_REFLECTION;
        }
        else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
        {
-               // bright unshaded geometry
-               mode = SHADERMODE_LIGHTMAP;
+               // unshaded geometry (fullbright or ambient model lighting)
+               mode = SHADERMODE_FLATCOLOR;
                if (rsurface.texture->currentskinframe->glow)
                        permutation |= SHADERPERMUTATION_GLOW;
                if (r_refdef.fogenabled)
@@ -1220,12 +1303,13 @@ int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, fl
                if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
                        permutation |= SHADERPERMUTATION_REFLECTION;
        }
-       else if (modellighting)
+       else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
        {
                // directional model lighting
                mode = SHADERMODE_LIGHTDIRECTION;
                if (rsurface.texture->currentskinframe->glow)
                        permutation |= SHADERPERMUTATION_GLOW;
+               permutation |= SHADERPERMUTATION_DIFFUSE;
                if (specularscale > 0)
                        permutation |= SHADERPERMUTATION_SPECULAR;
                if (r_refdef.fogenabled)
@@ -1237,6 +1321,21 @@ int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, fl
                if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
                        permutation |= SHADERPERMUTATION_REFLECTION;
        }
+       else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
+       {
+               // ambient model lighting
+               mode = SHADERMODE_LIGHTDIRECTION;
+               if (rsurface.texture->currentskinframe->glow)
+                       permutation |= SHADERPERMUTATION_GLOW;
+               if (r_refdef.fogenabled)
+                       permutation |= SHADERPERMUTATION_FOG;
+               if (rsurface.texture->colormapping)
+                       permutation |= SHADERPERMUTATION_COLORMAPPING;
+               if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
+                       permutation |= SHADERPERMUTATION_CONTRASTBOOST;
+               if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
+                       permutation |= SHADERPERMUTATION_REFLECTION;
+       }
        else
        {
                // lightmapped wall
@@ -1248,20 +1347,25 @@ int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, fl
                        else
                                mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
                        if (specularscale > 0)
-                               permutation |= SHADERPERMUTATION_SPECULAR;
+                               permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
                }
                else if (r_glsl_deluxemapping.integer >= 2)
                {
                        // fake deluxemapping (uniform light direction in tangentspace)
                        mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
                        if (specularscale > 0)
-                               permutation |= SHADERPERMUTATION_SPECULAR;
+                               permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
                }
-               else
+               else if (rsurface.uselightmaptexture)
                {
-                       // ordinary lightmapping
+                       // ordinary lightmapping (q1bsp, q3bsp)
                        mode = SHADERMODE_LIGHTMAP;
                }
+               else
+               {
+                       // ordinary vertex coloring (q3bsp)
+                       mode = SHADERMODE_VERTEXCOLOR;
+               }
                if (rsurface.texture->currentskinframe->glow)
                        permutation |= SHADERPERMUTATION_GLOW;
                if (r_refdef.fogenabled)
@@ -1326,20 +1430,21 @@ int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, fl
        else if (mode == SHADERMODE_LIGHTDIRECTION)
        {
                if (r_glsl_permutation->loc_AmbientColor >= 0)
-                       qglUniform3fARB(r_glsl_permutation->loc_AmbientColor, rsurface.modellight_ambient[0] * ambientscale, rsurface.modellight_ambient[1] * ambientscale, rsurface.modellight_ambient[2] * ambientscale);
+                       qglUniform3fARB(r_glsl_permutation->loc_AmbientColor , rsurface.modellight_ambient[0] * ambientscale  * rsurface.texture->lightmapcolor[0] * 0.5f, rsurface.modellight_ambient[1] * ambientscale  * rsurface.texture->lightmapcolor[1] * 0.5f, rsurface.modellight_ambient[2] * ambientscale  * rsurface.texture->lightmapcolor[2] * 0.5f);
                if (r_glsl_permutation->loc_DiffuseColor >= 0)
-                       qglUniform3fARB(r_glsl_permutation->loc_DiffuseColor, rsurface.modellight_diffuse[0] * diffusescale, rsurface.modellight_diffuse[1] * diffusescale, rsurface.modellight_diffuse[2] * diffusescale);
+                       qglUniform3fARB(r_glsl_permutation->loc_DiffuseColor , rsurface.modellight_diffuse[0] * diffusescale  * rsurface.texture->lightmapcolor[0] * 0.5f, rsurface.modellight_diffuse[1] * diffusescale  * rsurface.texture->lightmapcolor[1] * 0.5f, rsurface.modellight_diffuse[2] * diffusescale  * rsurface.texture->lightmapcolor[2] * 0.5f);
                if (r_glsl_permutation->loc_SpecularColor >= 0)
-                       qglUniform3fARB(r_glsl_permutation->loc_SpecularColor, rsurface.modellight_diffuse[0] * specularscale, rsurface.modellight_diffuse[1] * specularscale, rsurface.modellight_diffuse[2] * specularscale);
+                       qglUniform3fARB(r_glsl_permutation->loc_SpecularColor, rsurface.modellight_diffuse[0] * specularscale * rsurface.texture->lightmapcolor[0] * 0.5f, rsurface.modellight_diffuse[1] * specularscale * rsurface.texture->lightmapcolor[1] * 0.5f, rsurface.modellight_diffuse[2] * specularscale * rsurface.texture->lightmapcolor[2] * 0.5f);
                if (r_glsl_permutation->loc_LightDir >= 0)
                        qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
        }
        else
        {
-               if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, r_ambient.value * 2.0f / 128.0f);
-               if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, r_refdef.lightmapintensity * 2.0f);
-               if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, r_refdef.lightmapintensity * specularscale * 2.0f);
+               if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, r_ambient.value * 1.0f / 128.0f);
+               if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, r_refdef.lightmapintensity);
+               if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, r_refdef.lightmapintensity * specularscale);
        }
+       if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2], rsurface.texture->lightmapcolor[3]);
        if (r_glsl_permutation->loc_GlowScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_GlowScale, r_hdr_glowintensity.value);
        if (r_glsl_permutation->loc_ContrastBoostCoeff >= 0)
        {
@@ -1363,21 +1468,6 @@ int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, fl
                if (rsurface.rtlight || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD))
                        qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
                else
-               /*
-               {
-                       vec3_t fogvec;
-                       //   color.rgb *= SceneBrightness;
-                       VectorScale(r_refdef.fogcolor, r_view.colorscale, fogvec);
-                       if(r_glsl_permutation->loc_ContrastBoostCoeff >= 0) // need to support contrast boost
-                       {
-                               //   color.rgb *= ContrastBoost / ((ContrastBoost - 1) * color.rgb + 1);
-                               fogvec[0] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[0] + 1);
-                               fogvec[1] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[1] + 1);
-                               fogvec[2] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[2] + 1);
-                       }
-                       qglUniform3fARB(r_glsl_permutation->loc_FogColor, fogvec[0], fogvec[1], fogvec[2]);
-               }
-               */
                        qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
        }
        if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.modelorg[0], rsurface.modelorg[1], rsurface.modelorg[2]);
@@ -1445,24 +1535,47 @@ void R_SkinFrame_Purge(void)
                {
                        if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
                        {
-                               if (s->base == r_texture_notexture)     s->base   = NULL;
-                               if (s->nmap == r_texture_blanknormalmap)s->nmap   = NULL;
-                               if (s->merged == s->base)               s->merged = NULL;
-                               if (s->stain ) R_FreeTexture(s->stain );s->stain  = NULL;
-                               if (s->merged) R_FreeTexture(s->merged);s->merged = NULL;
-                               if (s->base  ) R_FreeTexture(s->base  );s->base   = NULL;
-                               if (s->pants ) R_FreeTexture(s->pants );s->pants  = NULL;
-                               if (s->shirt ) R_FreeTexture(s->shirt );s->shirt  = NULL;
-                               if (s->nmap  ) R_FreeTexture(s->nmap  );s->nmap   = NULL;
-                               if (s->gloss ) R_FreeTexture(s->gloss );s->gloss  = NULL;
-                               if (s->glow  ) R_FreeTexture(s->glow  );s->glow   = NULL;
-                               if (s->fog   ) R_FreeTexture(s->fog   );s->fog    = NULL;
+                               if (s->merged == s->base)
+                                       s->merged = NULL;
+                               // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
+                               R_PurgeTexture(s->stain );s->stain  = NULL;
+                               R_PurgeTexture(s->merged);s->merged = NULL;
+                               R_PurgeTexture(s->base  );s->base   = NULL;
+                               R_PurgeTexture(s->pants );s->pants  = NULL;
+                               R_PurgeTexture(s->shirt );s->shirt  = NULL;
+                               R_PurgeTexture(s->nmap  );s->nmap   = NULL;
+                               R_PurgeTexture(s->gloss );s->gloss  = NULL;
+                               R_PurgeTexture(s->glow  );s->glow   = NULL;
+                               R_PurgeTexture(s->fog   );s->fog    = NULL;
                                s->loadsequence = 0;
                        }
                }
        }
 }
 
+skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
+       skinframe_t *item;
+       char basename[MAX_QPATH];
+
+       Image_StripImageExtension(name, basename, sizeof(basename));
+
+       if( last == NULL ) {
+               int hashindex;
+               hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
+               item = r_skinframe.hash[hashindex];
+       } else {
+               item = last->next;
+       }
+
+       // linearly search through the hash bucket
+       for( ; item ; item = item->next ) {
+               if( !strcmp( item->basename, basename ) ) {
+                       return item;
+               }
+       }
+       return NULL;
+}
+
 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
 {
        skinframe_t *item;
@@ -1475,13 +1588,17 @@ skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewid
        for (item = r_skinframe.hash[hashindex];item;item = item->next)
                if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
                        break;
-       if (!item)
-       {
-               if (!add)
+
+       if (!item) {
+               rtexture_t *dyntexture;
+               // check whether its a dynamic texture
+               dyntexture = CL_GetDynTexture( basename );
+               if (!add && !dyntexture)
                        return NULL;
                item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
                memset(item, 0, sizeof(*item));
                strlcpy(item->basename, basename, sizeof(item->basename));
+               item->base = dyntexture; // either NULL or dyntexture handle
                item->textureflags = textureflags;
                item->comparewidth = comparewidth;
                item->compareheight = compareheight;
@@ -1489,6 +1606,15 @@ skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewid
                item->next = r_skinframe.hash[hashindex];
                r_skinframe.hash[hashindex] = item;
        }
+       else if( item->base == NULL )
+       {
+               rtexture_t *dyntexture;
+               // check whether its a dynamic texture
+               // this only needs to be done because Purge doesnt delete skinframes - only sets the texture pointers to NULL and we need to restore it before returing.. [11/29/2007 Black]
+               dyntexture = CL_GetDynTexture( basename );
+               item->base = dyntexture; // either NULL or dyntexture handle
+       }
+
        R_SkinFrame_MarkUsed(item);
        return item;
 }
@@ -1520,7 +1646,7 @@ skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboole
        if (skinframe && skinframe->base)
                return skinframe;
 
-       basepixels = loadimagepixels(name, complain, 0, 0);
+       basepixels = loadimagepixelsbgra(name, complain, true);
        if (basepixels == NULL)
                return NULL;
 
@@ -1539,7 +1665,7 @@ skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboole
 
        basepixels_width = image_width;
        basepixels_height = image_height;
-       skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
+       skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
 
        if (textureflags & TEXF_ALPHA)
        {
@@ -1557,7 +1683,7 @@ skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboole
                                pixels[j+2] = 255;
                                pixels[j+3] = basepixels[j+3];
                        }
-                       skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
+                       skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
                        Mem_Free(pixels);
                }
        }
@@ -1565,35 +1691,35 @@ skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboole
        // _norm is the name used by tenebrae and has been adopted as standard
        if (loadnormalmap)
        {
-               if ((pixels = loadimagepixels(va("%s_norm", skinframe->basename), false, 0, 0)) != NULL)
+               if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false)) != NULL)
                {
-                       skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
+                       skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
                        Mem_Free(pixels);
                        pixels = NULL;
                }
-               else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixels(va("%s_bump", skinframe->basename), false, 0, 0)) != NULL)
+               else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false)) != NULL)
                {
                        pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
-                       Image_HeightmapToNormalmap(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
-                       skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
+                       Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
+                       skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
                        Mem_Free(pixels);
                        Mem_Free(bumppixels);
                }
                else if (r_shadow_bumpscale_basetexture.value > 0)
                {
                        pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
-                       Image_HeightmapToNormalmap(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
-                       skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
+                       Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
+                       skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
                        Mem_Free(pixels);
                }
        }
        // _luma is supported for tenebrae compatibility
        // (I think it's a very stupid name, but oh well)
        // _glow is the preferred name
-       if (loadglow          && ((pixels = loadimagepixels(va("%s_glow", skinframe->basename), false, 0, 0)) != NULL || (pixels = loadimagepixels(va("%s_luma", skinframe->basename), false, 0, 0)) != NULL)) {skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
-       if (loadgloss         && (pixels = loadimagepixels(va("%s_gloss", skinframe->basename), false, 0, 0)) != NULL) {skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
-       if (loadpantsandshirt && (pixels = loadimagepixels(va("%s_pants", skinframe->basename), false, 0, 0)) != NULL) {skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
-       if (loadpantsandshirt && (pixels = loadimagepixels(va("%s_shirt", skinframe->basename), false, 0, 0)) != NULL) {skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
+       if (loadglow          && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false)) != NULL || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false)) != NULL)) {skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
+       if (loadgloss         && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false)) != NULL) {skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
+       if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false)) != NULL) {skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
+       if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false)) != NULL) {skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
 
        if (basepixels)
                Mem_Free(basepixels);
@@ -1615,7 +1741,8 @@ static rtexture_t *R_SkinFrame_TextureForSkinLayer(const unsigned char *in, int
        return R_LoadTexture2D (r_main_texturepool, name, width, height, in, TEXTYPE_PALETTE, textureflags, palette);
 }
 
-skinframe_t *R_SkinFrame_LoadInternal(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height, int bitsperpixel, const unsigned int *palette, const unsigned int *alphapalette)
+// this is only used by .spr32 sprites, HL .spr files, HL .bsp files
+skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
 {
        int i;
        unsigned char *temp1, *temp2;
@@ -1625,7 +1752,7 @@ skinframe_t *R_SkinFrame_LoadInternal(const char *name, int textureflags, int lo
                return NULL;
 
        // if already loaded just return it, otherwise make a new skinframe
-       skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*bitsperpixel/8) : 0, true);
+       skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
        if (skinframe && skinframe->base)
                return skinframe;
 
@@ -1643,77 +1770,95 @@ skinframe_t *R_SkinFrame_LoadInternal(const char *name, int textureflags, int lo
        if (!skindata)
                return NULL;
 
-       if (bitsperpixel == 32)
+       if (r_shadow_bumpscale_basetexture.value > 0)
        {
-               if (r_shadow_bumpscale_basetexture.value > 0)
-               {
-                       temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
-                       temp2 = temp1 + width * height * 4;
-                       Image_HeightmapToNormalmap(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
-                       skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_RGBA, skinframe->textureflags | TEXF_ALPHA, NULL);
-                       Mem_Free(temp1);
-               }
-               skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_RGBA, skinframe->textureflags, NULL);
-               if (textureflags & TEXF_ALPHA)
-               {
-                       for (i = 3;i < width * height * 4;i += 4)
-                               if (skindata[i] < 255)
-                                       break;
-                       if (i < width * height * 4)
-                       {
-                               unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
-                               memcpy(fogpixels, skindata, width * height * 4);
-                               for (i = 0;i < width * height * 4;i += 4)
-                                       fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
-                               skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
-                               Mem_Free(fogpixels);
-                       }
-               }
+               temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
+               temp2 = temp1 + width * height * 4;
+               Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
+               skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
+               Mem_Free(temp1);
        }
-       else if (bitsperpixel == 8)
+       skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, skinframe->textureflags, NULL);
+       if (textureflags & TEXF_ALPHA)
        {
-               if (r_shadow_bumpscale_basetexture.value > 0)
-               {
-                       temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
-                       temp2 = temp1 + width * height * 4;
-                       if (bitsperpixel == 32)
-                               Image_HeightmapToNormalmap(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
-                       else
-                       {
-                               // use either a custom palette or the quake palette
-                               Image_Copy8bitRGBA(skindata, temp1, width * height, palette ? palette : palette_complete);
-                               Image_HeightmapToNormalmap(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
-                       }
-                       skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_RGBA, skinframe->textureflags | TEXF_ALPHA, NULL);
-                       Mem_Free(temp1);
-               }
-               // use either a custom palette, or the quake palette
-               skinframe->base = skinframe->merged = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_merged", skinframe->basename), palette ? palette : (loadglowtexture ? palette_nofullbrights : ((skinframe->textureflags & TEXF_ALPHA) ? palette_transparent : palette_complete)), skinframe->textureflags, true); // all
-               if (!palette && loadglowtexture)
-                       skinframe->glow = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_glow", skinframe->basename), palette_onlyfullbrights, skinframe->textureflags, false); // glow
-               if (!palette && loadpantsandshirt)
-               {
-                       skinframe->pants = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_pants", skinframe->basename), palette_pantsaswhite, skinframe->textureflags, false); // pants
-                       skinframe->shirt = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_shirt", skinframe->basename), palette_shirtaswhite, skinframe->textureflags, false); // shirt
-               }
-               if (skinframe->pants || skinframe->shirt)
-                       skinframe->base = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", skinframe->basename),loadglowtexture ? palette_nocolormapnofullbrights : palette_nocolormap, skinframe->textureflags, false); // no special colors
-               if (textureflags & TEXF_ALPHA)
+               for (i = 3;i < width * height * 4;i += 4)
+                       if (skindata[i] < 255)
+                               break;
+               if (i < width * height * 4)
                {
-                       // if not using a custom alphapalette, use the quake one
-                       if (!alphapalette)
-                               alphapalette = palette_alpha;
-                       for (i = 0;i < width * height;i++)
-                               if (((unsigned char *)alphapalette)[skindata[i]*4+3] < 255)
-                                       break;
-                       if (i < width * height)
-                               skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), alphapalette, skinframe->textureflags, true); // fog mask
+                       unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
+                       memcpy(fogpixels, skindata, width * height * 4);
+                       for (i = 0;i < width * height * 4;i += 4)
+                               fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
+                       skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, skinframe->textureflags, NULL);
+                       Mem_Free(fogpixels);
                }
        }
 
        return skinframe;
 }
 
+skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
+{
+       int i;
+       unsigned char *temp1, *temp2;
+       skinframe_t *skinframe;
+
+       if (cls.state == ca_dedicated)
+               return NULL;
+
+       // if already loaded just return it, otherwise make a new skinframe
+       skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
+       if (skinframe && skinframe->base)
+               return skinframe;
+
+       skinframe->stain = NULL;
+       skinframe->merged = NULL;
+       skinframe->base = r_texture_notexture;
+       skinframe->pants = NULL;
+       skinframe->shirt = NULL;
+       skinframe->nmap = r_texture_blanknormalmap;
+       skinframe->gloss = NULL;
+       skinframe->glow = NULL;
+       skinframe->fog = NULL;
+
+       // if no data was provided, then clearly the caller wanted to get a blank skinframe
+       if (!skindata)
+               return NULL;
+
+       if (r_shadow_bumpscale_basetexture.value > 0)
+       {
+               temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
+               temp2 = temp1 + width * height * 4;
+               // use either a custom palette or the quake palette
+               Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
+               Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
+               skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
+               Mem_Free(temp1);
+       }
+       // use either a custom palette, or the quake palette
+       skinframe->base = skinframe->merged = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_merged", skinframe->basename), (loadglowtexture ? palette_bgra_nofullbrights : ((skinframe->textureflags & TEXF_ALPHA) ? palette_bgra_transparent : palette_bgra_complete)), skinframe->textureflags, true); // all
+       if (loadglowtexture)
+               skinframe->glow = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_glow", skinframe->basename), palette_bgra_onlyfullbrights, skinframe->textureflags, false); // glow
+       if (loadpantsandshirt)
+       {
+               skinframe->pants = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_pants", skinframe->basename), palette_bgra_pantsaswhite, skinframe->textureflags, false); // pants
+               skinframe->shirt = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_shirt", skinframe->basename), palette_bgra_shirtaswhite, skinframe->textureflags, false); // shirt
+       }
+       if (skinframe->pants || skinframe->shirt)
+               skinframe->base = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", skinframe->basename), loadglowtexture ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap, skinframe->textureflags, false); // no special colors
+       if (textureflags & TEXF_ALPHA)
+       {
+               for (i = 0;i < width * height;i++)
+                       if (((unsigned char *)palette_bgra_alpha)[skindata[i]*4+3] < 255)
+                               break;
+               if (i < width * height)
+                       skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), palette_bgra_alpha, skinframe->textureflags, true); // fog mask
+       }
+
+       return skinframe;
+}
+
 skinframe_t *R_SkinFrame_LoadMissing(void)
 {
        skinframe_t *skinframe;
@@ -1737,18 +1882,6 @@ skinframe_t *R_SkinFrame_LoadMissing(void)
 
 void gl_main_start(void)
 {
-       int x;
-       double r, alpha;
-
-       r = (-1.0/256.0) * (FOGMASKTABLEWIDTH * FOGMASKTABLEWIDTH);
-       for (x = 0;x < FOGMASKTABLEWIDTH;x++)
-       {
-               alpha = 1 - exp(r / ((double)x*(double)x));
-               if (x == FOGMASKTABLEWIDTH - 1)
-                       alpha = 0;
-               r_refdef.fogmasktable[x] = bound(0, alpha, 1);
-       }
-
        memset(r_qwskincache, 0, sizeof(r_qwskincache));
        memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
 
@@ -1765,7 +1898,8 @@ void gl_main_start(void)
                R_BuildWhiteCube();
                R_BuildNormalizationCube();
        }
-       R_BuildFogTexture();
+       r_texture_fogattenuation = NULL;
+       //r_texture_fogintensity = NULL;
        memset(&r_bloomstate, 0, sizeof(r_bloomstate));
        memset(&r_waterstate, 0, sizeof(r_waterstate));
        memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
@@ -1791,6 +1925,8 @@ void gl_main_shutdown(void)
        r_texture_black = NULL;
        r_texture_whitecube = NULL;
        r_texture_normalizationcube = NULL;
+       r_texture_fogattenuation = NULL;
+       //r_texture_fogintensity = NULL;
        memset(&r_bloomstate, 0, sizeof(r_bloomstate));
        memset(&r_waterstate, 0, sizeof(r_waterstate));
        R_GLSL_Restart_f();
@@ -1837,6 +1973,7 @@ void GL_Main_Init(void)
                Cvar_RegisterVariable (&gl_fogblue);
                Cvar_RegisterVariable (&gl_fogstart);
                Cvar_RegisterVariable (&gl_fogend);
+               Cvar_RegisterVariable (&gl_skyclip);
        }
        Cvar_RegisterVariable(&r_depthfirst);
        Cvar_RegisterVariable(&r_nearclip);
@@ -1867,6 +2004,7 @@ void GL_Main_Init(void)
        Cvar_RegisterVariable(&r_q1bsp_skymasking);
        Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
        Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
+       Cvar_RegisterVariable(&r_fog_exp2);
        Cvar_RegisterVariable(&r_textureunits);
        Cvar_RegisterVariable(&r_glsl);
        Cvar_RegisterVariable(&r_glsl_offsetmapping);
@@ -1880,6 +2018,7 @@ void GL_Main_Init(void)
        Cvar_RegisterVariable(&r_water_reflectdistort);
        Cvar_RegisterVariable(&r_lerpsprites);
        Cvar_RegisterVariable(&r_lerpmodels);
+       Cvar_RegisterVariable(&r_lerplightstyles);
        Cvar_RegisterVariable(&r_waterscroll);
        Cvar_RegisterVariable(&r_bloom);
        Cvar_RegisterVariable(&r_bloom_colorscale);
@@ -1901,6 +2040,11 @@ void GL_Main_Init(void)
        if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
                Cvar_SetValue("r_fullbrights", 0);
        R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
+
+       Cvar_RegisterVariable(&r_track_sprites);
+       Cvar_RegisterVariable(&r_track_sprites_flags);
+       Cvar_RegisterVariable(&r_track_sprites_scalew);
+       Cvar_RegisterVariable(&r_track_sprites_scaleh);
 }
 
 extern void R_Textures_Init(void);
@@ -1909,7 +2053,6 @@ extern void GL_Main_Init(void);
 extern void R_Shadow_Init(void);
 extern void R_Sky_Init(void);
 extern void GL_Surf_Init(void);
-extern void R_Light_Init(void);
 extern void R_Particles_Init(void);
 extern void R_Explosion_Init(void);
 extern void gl_backend_init(void);
@@ -1927,7 +2070,6 @@ void Render_Init(void)
        R_Sky_Init();
        GL_Surf_Init();
        Sbar_Init();
-       R_Light_Init();
        R_Particles_Init();
        R_Explosion_Init();
        R_LightningBeams_Init();
@@ -2052,43 +2194,6 @@ int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, c
 
 //==================================================================================
 
-static void R_UpdateEntityLighting(entity_render_t *ent)
-{
-       vec3_t tempdiffusenormal;
-
-       // fetch the lighting from the worldmodel data
-       VectorSet(ent->modellight_ambient, r_ambient.value * (2.0f / 128.0f), r_ambient.value * (2.0f / 128.0f), r_ambient.value * (2.0f / 128.0f));
-       VectorClear(ent->modellight_diffuse);
-       VectorClear(tempdiffusenormal);
-       if ((ent->flags & RENDER_LIGHT) && r_refdef.worldmodel && r_refdef.worldmodel->brush.LightPoint)
-       {
-               vec3_t org;
-               Matrix4x4_OriginFromMatrix(&ent->matrix, org);
-               r_refdef.worldmodel->brush.LightPoint(r_refdef.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
-       }
-       else // highly rare
-               VectorSet(ent->modellight_ambient, 1, 1, 1);
-
-       // move the light direction into modelspace coordinates for lighting code
-       Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
-       if(VectorLength2(ent->modellight_lightdir) > 0)
-       {
-               VectorNormalize(ent->modellight_lightdir);
-       }
-       else
-       {
-               VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
-       }
-
-       // scale ambient and directional light contributions according to rendering variables
-       ent->modellight_ambient[0] *= ent->colormod[0] * r_refdef.lightmapintensity;
-       ent->modellight_ambient[1] *= ent->colormod[1] * r_refdef.lightmapintensity;
-       ent->modellight_ambient[2] *= ent->colormod[2] * r_refdef.lightmapintensity;
-       ent->modellight_diffuse[0] *= ent->colormod[0] * r_refdef.lightmapintensity;
-       ent->modellight_diffuse[1] *= ent->colormod[1] * r_refdef.lightmapintensity;
-       ent->modellight_diffuse[2] *= ent->colormod[2] * r_refdef.lightmapintensity;
-}
-
 static void R_View_UpdateEntityVisible (void)
 {
        int i, renderimask;
@@ -2104,7 +2209,8 @@ static void R_View_UpdateEntityVisible (void)
                for (i = 0;i < r_refdef.numentities;i++)
                {
                        ent = r_refdef.entities[i];
-                       r_viewcache.entityvisible[i] = !(ent->flags & renderimask) && !R_CullBox(ent->mins, ent->maxs) && ((ent->effects & EF_NODEPTHTEST) || (ent->flags & RENDER_VIEWMODEL) || r_refdef.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.worldmodel, r_viewcache.world_leafvisible, ent->mins, ent->maxs));
+                       r_viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs)) && ((ent->effects & EF_NODEPTHTEST) || (ent->flags & RENDER_VIEWMODEL) || r_refdef.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.worldmodel, r_viewcache.world_leafvisible, ent->mins, ent->maxs));
+
                }
                if(r_cullentities_trace.integer)
                {
@@ -2127,13 +2233,9 @@ static void R_View_UpdateEntityVisible (void)
                for (i = 0;i < r_refdef.numentities;i++)
                {
                        ent = r_refdef.entities[i];
-                       r_viewcache.entityvisible[i] = !(ent->flags & renderimask) && !R_CullBox(ent->mins, ent->maxs);
+                       r_viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
                }
        }
-
-       // update entity lighting (even on hidden entities for r_shadows)
-       for (i = 0;i < r_refdef.numentities;i++)
-               R_UpdateEntityLighting(r_refdef.entities[i]);
 }
 
 // only used if skyrendermasked, and normally returns false
@@ -2194,7 +2296,6 @@ static void R_DrawModelsDepth(void)
                if (!r_viewcache.entityvisible[i])
                        continue;
                ent = r_refdef.entities[i];
-               r_refdef.stats.entities++;
                if (ent->model && ent->model->DrawDepth != NULL)
                        ent->model->DrawDepth(ent);
        }
@@ -2213,7 +2314,6 @@ static void R_DrawModelsDebug(void)
                if (!r_viewcache.entityvisible[i])
                        continue;
                ent = r_refdef.entities[i];
-               r_refdef.stats.entities++;
                if (ent->model && ent->model->DrawDebug != NULL)
                        ent->model->DrawDebug(ent);
        }
@@ -2232,7 +2332,6 @@ static void R_DrawModelsAddWaterPlanes(void)
                if (!r_viewcache.entityvisible[i])
                        continue;
                ent = r_refdef.entities[i];
-               r_refdef.stats.entities++;
                if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
                        ent->model->DrawAddWaterPlanes(ent);
        }
@@ -2309,8 +2408,6 @@ static void R_View_SetFrustum(void)
        r_view.frustum[5].dist = m[15] + m[14];
 #endif
 
-
-
        if (r_view.useperspective)
        {
                slopex = 1.0 / r_view.frustum_x;
@@ -2321,6 +2418,14 @@ static void R_View_SetFrustum(void)
                VectorMA(r_view.forward,  slopey, r_view.up  , r_view.frustum[3].normal);
                VectorCopy(r_view.forward, r_view.frustum[4].normal);
 
+               // Leaving those out was a mistake, those were in the old code, and they
+               // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
+               // I couldn't reproduce it after adding those normalizations. --blub
+               VectorNormalize(r_view.frustum[0].normal);
+               VectorNormalize(r_view.frustum[1].normal);
+               VectorNormalize(r_view.frustum[2].normal);
+               VectorNormalize(r_view.frustum[3].normal);
+
                // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
                VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward, -1024 * slopex, r_view.left, -1024 * slopey, r_view.up, r_view.frustumcorner[0]);
                VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward,  1024 * slopex, r_view.left, -1024 * slopey, r_view.up, r_view.frustumcorner[1]);
@@ -2610,14 +2715,12 @@ static void R_Water_AddWaterPlane(msurface_t *surface)
 {
        int triangleindex, planeindex;
        const int *e;
-       vec_t f;
        vec3_t vert[3];
        vec3_t normal;
        vec3_t center;
        r_waterstate_waterplane_t *p;
        // just use the first triangle with a valid normal for any decisions
        VectorClear(normal);
-       VectorClear(center);
        for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
        {
                Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
@@ -2627,14 +2730,6 @@ static void R_Water_AddWaterPlane(msurface_t *surface)
                if (VectorLength2(normal) >= 0.001)
                        break;
        }
-       // now find the center of this surface
-       for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles*3;triangleindex++, e++)
-       {
-               Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
-               VectorAdd(center, vert[0], center);
-       }
-       f = 1.0 / surface->num_triangles*3;
-       VectorScale(center, f, center);
 
        // find a matching plane if there is one
        for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
@@ -2666,9 +2761,11 @@ static void R_Water_AddWaterPlane(msurface_t *surface)
        // merge this surface's materialflags into the waterplane
        p->materialflags |= surface->texture->currentframe->currentmaterialflags;
        // merge this surface's PVS into the waterplane
-       if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) && r_refdef.worldmodel && r_refdef.worldmodel->brush.FatPVS)
+       VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
+       if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) && r_refdef.worldmodel && r_refdef.worldmodel->brush.FatPVS
+        && r_refdef.worldmodel->brush.PointInLeaf && r_refdef.worldmodel->brush.PointInLeaf(r_refdef.worldmodel, center)->clusterindex >= 0)
        {
-               r_refdef.worldmodel->brush.FatPVS(r_refdef.worldmodel, r_view.origin, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
+               r_refdef.worldmodel->brush.FatPVS(r_refdef.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
                p->pvsvalid = true;
        }
 }
@@ -2687,7 +2784,7 @@ static void R_Water_ProcessPlanes(void)
                if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
                {
                        if (!p->texture_refraction)
-                               p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_RGBA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
+                               p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
                        if (!p->texture_refraction)
                                goto error;
                }
@@ -2695,7 +2792,7 @@ static void R_Water_ProcessPlanes(void)
                if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
                {
                        if (!p->texture_reflection)
-                               p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_RGBA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
+                               p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
                        if (!p->texture_reflection)
                                goto error;
                }
@@ -2746,7 +2843,9 @@ static void R_Water_ProcessPlanes(void)
                        }
 
                        R_ResetViewRendering3D();
-                       R_ClearScreen();
+                       R_ClearScreen(r_refdef.fogenabled);
+                       if (r_timereport_active)
+                               R_TimeReport("viewclear");
 
                        R_RenderScene(false);
 
@@ -2756,10 +2855,13 @@ static void R_Water_ProcessPlanes(void)
                        qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_view.x, vid.height - (r_view.y + r_view.height), r_view.width, r_view.height);CHECKGLERROR
 
                        R_ResetViewRendering3D();
-                       R_ClearScreen();
+                       R_ClearScreen(r_refdef.fogenabled);
+                       if (r_timereport_active)
+                               R_TimeReport("viewclear");
                }
 
                r_view = originalview;
+               r_view.clear = true;
                r_waterstate.renderingscene = false;
        }
        return;
@@ -2834,7 +2936,7 @@ void R_Bloom_StartFrame(void)
                r_bloomstate.screentexturewidth = screentexturewidth;
                r_bloomstate.screentextureheight = screentextureheight;
                if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
-                       r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
+                       r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_BGRA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
        }
        if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
        {
@@ -2844,7 +2946,7 @@ void R_Bloom_StartFrame(void)
                r_bloomstate.bloomtexturewidth = bloomtexturewidth;
                r_bloomstate.bloomtextureheight = bloomtextureheight;
                if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
-                       r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_RGBA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
+                       r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
        }
 
        // set up a texcoord array for the full resolution screen image
@@ -3024,7 +3126,9 @@ void R_Bloom_MakeTexture(void)
 void R_HDR_RenderBloomTexture(void)
 {
        int oldwidth, oldheight;
+       float oldcolorscale;
 
+       oldcolorscale = r_view.colorscale;
        oldwidth = r_view.width;
        oldheight = r_view.height;
        r_view.width = r_bloomstate.bloomwidth;
@@ -3035,9 +3139,12 @@ void R_HDR_RenderBloomTexture(void)
        // TODO: add fp16 framebuffer support
 
        r_view.showdebug = false;
-       r_view.colorscale = r_bloom_colorscale.value * r_hdr_scenebrightness.value;
-       if (r_hdr.integer)
-               r_view.colorscale /= r_hdr_range.value;
+       r_view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
+
+       R_ClearScreen(r_refdef.fogenabled);
+       if (r_timereport_active)
+               R_TimeReport("HDRclear");
+
        r_waterstate.numwaterplanes = 0;
        R_RenderScene(r_waterstate.enabled);
        r_view.showdebug = true;
@@ -3047,16 +3154,16 @@ void R_HDR_RenderBloomTexture(void)
        R_Bloom_CopyHDRTexture();
        R_Bloom_MakeTexture();
 
-       R_ResetViewRendering3D();
-
-       R_ClearScreen();
-       if (r_timereport_active)
-               R_TimeReport("clear");
-
-
        // restore the view settings
        r_view.width = oldwidth;
        r_view.height = oldheight;
+       r_view.colorscale = oldcolorscale;
+
+       R_ResetViewRendering3D();
+
+       R_ClearScreen(r_refdef.fogenabled);
+       if (r_timereport_active)
+               R_TimeReport("viewclear");
 }
 
 static void R_BlendView(void)
@@ -3127,6 +3234,33 @@ void R_RenderScene(qboolean addwaterplanes);
 
 matrix4x4_t r_waterscrollmatrix;
 
+void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
+{
+       if (r_refdef.fog_density)
+       {
+               r_refdef.fogcolor[0] = r_refdef.fog_red;
+               r_refdef.fogcolor[1] = r_refdef.fog_green;
+               r_refdef.fogcolor[2] = r_refdef.fog_blue;
+
+               {
+                       vec3_t fogvec;
+                       VectorCopy(r_refdef.fogcolor, fogvec);
+                       //   color.rgb *= SceneBrightness;
+                       if(r_glsl.integer && (r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)) // need to support contrast boost
+                       {
+                               //   color.rgb *= ContrastBoost / ((ContrastBoost - 1) * color.rgb + 1);
+                               fogvec[0] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[0] + 1);
+                               fogvec[1] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[1] + 1);
+                               fogvec[2] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[2] + 1);
+                       }
+                       VectorScale(fogvec, r_view.colorscale, fogvec);
+                       r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
+                       r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
+                       r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
+               }
+       }
+}
+
 void R_UpdateVariables(void)
 {
        R_Textures_Frame();
@@ -3166,6 +3300,9 @@ void R_UpdateVariables(void)
                        r_refdef.fog_red = gl_fogred.value;
                        r_refdef.fog_green = gl_foggreen.value;
                        r_refdef.fog_blue = gl_fogblue.value;
+                       r_refdef.fog_alpha = 1;
+                       r_refdef.fog_start = 0;
+                       r_refdef.fog_end = gl_skyclip.value;
                }
                else if (r_refdef.oldgl_fogenable)
                {
@@ -3174,24 +3311,35 @@ void R_UpdateVariables(void)
                        r_refdef.fog_red = 0;
                        r_refdef.fog_green = 0;
                        r_refdef.fog_blue = 0;
+                       r_refdef.fog_alpha = 0;
+                       r_refdef.fog_start = 0;
+                       r_refdef.fog_end = 0;
                }
        }
-       if (r_refdef.fog_density)
-       {
-               r_refdef.fogcolor[0] = bound(0.0f, r_refdef.fog_red  , 1.0f);
-               r_refdef.fogcolor[1] = bound(0.0f, r_refdef.fog_green, 1.0f);
-               r_refdef.fogcolor[2] = bound(0.0f, r_refdef.fog_blue , 1.0f);
-       }
+
+       r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
+       r_refdef.fog_start = max(0, r_refdef.fog_start);
+       r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
+
+       R_UpdateFogColor();
+
        if (r_refdef.fog_density)
        {
                r_refdef.fogenabled = true;
                // this is the point where the fog reaches 0.9986 alpha, which we
                // consider a good enough cutoff point for the texture
                // (0.9986 * 256 == 255.6)
-               r_refdef.fogrange = 400 / r_refdef.fog_density;
+               if (r_fog_exp2.integer)
+                       r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
+               else
+                       r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
+               r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
                r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
                r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
                // fog color was already set
+               // update the fog texture
+               if (r_refdef.fogmasktable_start != r_refdef.fog_start || r_refdef.fogmasktable_alpha != r_refdef.fog_alpha || r_refdef.fogmasktable_density != r_refdef.fog_density || r_refdef.fogmasktable_range != r_refdef.fogrange)
+                       R_BuildFogTexture();
        }
        else
                r_refdef.fogenabled = false;
@@ -3207,6 +3355,8 @@ void R_RenderView(void)
        if (!r_refdef.entities/* || !r_refdef.worldmodel*/)
                return; //Host_Error ("R_RenderView: NULL worldmodel");
 
+       r_view.colorscale = r_hdr_scenebrightness.value;
+
        R_Shadow_UpdateWorldLightSelection();
 
        R_Bloom_StartFrame();
@@ -3214,13 +3364,17 @@ void R_RenderView(void)
 
        CHECKGLERROR
        if (r_timereport_active)
-               R_TimeReport("setup");
+               R_TimeReport("viewsetup");
 
        R_ResetViewRendering3D();
 
-       R_ClearScreen();
-       if (r_timereport_active)
-               R_TimeReport("clear");
+       if (r_view.clear || r_refdef.fogenabled)
+       {
+               R_ClearScreen(r_refdef.fogenabled);
+               if (r_timereport_active)
+                       R_TimeReport("viewclear");
+       }
+       r_view.clear = true;
 
        r_view.showdebug = true;
 
@@ -3228,7 +3382,6 @@ void R_RenderView(void)
        if (r_hdr.integer)
                R_HDR_RenderBloomTexture();
 
-       r_view.colorscale = r_hdr_scenebrightness.value;
        r_waterstate.numwaterplanes = 0;
        R_RenderScene(r_waterstate.enabled);
 
@@ -3249,6 +3402,8 @@ static void R_DrawLocs(void);
 static void R_DrawEntityBBoxes(void);
 void R_RenderScene(qboolean addwaterplanes)
 {
+       R_UpdateFogColor();
+
        if (addwaterplanes)
        {
                R_ResetViewRendering3D();
@@ -3367,6 +3522,10 @@ void R_RenderScene(qboolean addwaterplanes)
                if (r_timereport_active)
                        R_TimeReport("lightning");
 
+               R_DrawDecals();
+               if (r_timereport_active)
+                       R_TimeReport("decals");
+
                R_DrawParticles();
                if (r_timereport_active)
                        R_TimeReport("particles");
@@ -3729,7 +3888,7 @@ void R_DrawSprite(int blendfunc1, int blendfunc2, rtexture_t *texture, rtexture_
                R_Mesh_TexBind(0, R_GetTexture(fogtexture));
                GL_BlendFunc(blendfunc1, GL_ONE);
                fog = 1 - fog;
-               GL_Color(r_refdef.fogcolor[0] * fog * r_view.colorscale, r_refdef.fogcolor[1] * fog * r_view.colorscale, r_refdef.fogcolor[2] * fog * r_view.colorscale, ca);
+               GL_Color(r_refdef.fogcolor[0] * fog, r_refdef.fogcolor[1] * fog, r_refdef.fogcolor[2] * fog, ca);
                R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
        }
 }
@@ -3950,6 +4109,14 @@ void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
                t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION);
        if (!(ent->flags & RENDER_LIGHT))
                t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
+       else if (rsurface.modeltexcoordlightmap2f == NULL)
+       {
+               // pick a model lighting mode
+               if (VectorLength2(ent->modellight_diffuse) >= (1.0f / 256.0f))
+                       t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
+               else
+                       t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
+       }
        if (ent->effects & EF_ADDITIVE)
                t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
        else if (t->currentalpha < 1)
@@ -3963,7 +4130,12 @@ void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
        if (t->backgroundnumskinframes && !(t->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
                t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
 
-       for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && (tcmod->tcmod || i < 1);i++, tcmod++)
+       // make sure that the waterscroll matrix is used on water surfaces when
+       // there is no tcmod
+       if (t->currentmaterialflags & MATERIALFLAG_WATER && r_waterscroll.value != 0)
+               t->currenttexmatrix = r_waterscrollmatrix;
+
+       for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
        {
                matrix4x4_t matrix;
                switch(tcmod->tcmod)
@@ -4053,17 +4225,6 @@ void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
                t->specularscale = 0;
        }
 
-       t->currentpolygonfactor = r_refdef.polygonfactor + t->basepolygonfactor;
-       t->currentpolygonoffset = r_refdef.polygonoffset + t->basepolygonoffset;
-       // submodels are biased to avoid z-fighting with world surfaces that they
-       // may be exactly overlapping (avoids z-fighting artifacts on certain
-       // doors and things in Quake maps)
-       if (ent->model->brush.submodel)
-       {
-               t->currentpolygonfactor += r_polygonoffset_submodel_factor.value;
-               t->currentpolygonoffset += r_polygonoffset_submodel_offset.value;
-       }
-
        VectorClear(t->dlightcolor);
        t->currentnumlayers = 0;
        if (!(t->currentmaterialflags & MATERIALFLAG_NODRAW))
@@ -4119,8 +4280,9 @@ void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
                                        // applied to the color
                                        // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
                                        if (ent->model->type == mod_brushq3)
-                                               colorscale *= r_refdef.lightstylevalue[0] * (1.0f / 256.0f);
+                                               colorscale *= r_refdef.rtlightstylevalue[0];
                                        colorscale *= r_refdef.lightmapintensity;
+                                       Vector4Set(t->lightmapcolor, ent->colormod[0] * colorscale, ent->colormod[1] * colorscale, ent->colormod[2] * colorscale, t->currentalpha);
                                        R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, currentbasetexture, &t->currenttexmatrix, ent->colormod[0] * colorscale, ent->colormod[1] * colorscale, ent->colormod[2] * colorscale, t->currentalpha);
                                        if (r_ambient.value >= (1.0f/64.0f))
                                                R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, ent->colormod[0] * r_ambient.value * (1.0f / 64.0f), ent->colormod[1] * r_ambient.value * (1.0f / 64.0f), ent->colormod[2] * r_ambient.value * (1.0f / 64.0f), t->currentalpha);
@@ -4227,6 +4389,8 @@ void RSurf_ActiveWorldEntity(void)
        rsurface.frameblend[2].lerp = 0;
        rsurface.frameblend[3].frame = 0;
        rsurface.frameblend[3].lerp = 0;
+       rsurface.basepolygonfactor = r_refdef.polygonfactor;
+       rsurface.basepolygonoffset = r_refdef.polygonoffset;
        rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
        rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
        rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
@@ -4280,7 +4444,12 @@ void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, q
        rsurface.inversematrix = ent->inversematrix;
        R_Mesh_Matrix(&rsurface.matrix);
        Matrix4x4_Transform(&rsurface.inversematrix, r_view.origin, rsurface.modelorg);
-       VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
+       rsurface.modellight_ambient[0] = ent->modellight_ambient[0] * ent->colormod[0];
+       rsurface.modellight_ambient[1] = ent->modellight_ambient[1] * ent->colormod[1];
+       rsurface.modellight_ambient[2] = ent->modellight_ambient[2] * ent->colormod[2];
+       rsurface.modellight_diffuse[0] = ent->modellight_diffuse[0] * ent->colormod[0];
+       rsurface.modellight_diffuse[1] = ent->modellight_diffuse[1] * ent->colormod[1];
+       rsurface.modellight_diffuse[2] = ent->modellight_diffuse[2] * ent->colormod[2];
        VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
        VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
        VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
@@ -4289,6 +4458,13 @@ void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, q
        rsurface.frameblend[1] = ent->frameblend[1];
        rsurface.frameblend[2] = ent->frameblend[2];
        rsurface.frameblend[3] = ent->frameblend[3];
+       rsurface.basepolygonfactor = r_refdef.polygonfactor;
+       rsurface.basepolygonoffset = r_refdef.polygonoffset;
+       if (ent->model->brush.submodel)
+       {
+               rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
+               rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
+       }
        if (model->surfmesh.isanimated && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].frame != 0))
        {
                if (wanttangents)
@@ -5220,12 +5396,13 @@ static void RSurf_DrawBatch_GL11_VertexShade(int texturenumsurfaces, msurface_t
        // TODO: optimize
        // model lighting
        VectorCopy(rsurface.modellight_lightdir, lightdir);
-       ambientcolor[0] = rsurface.modellight_ambient[0] * r * 0.5f;
-       ambientcolor[1] = rsurface.modellight_ambient[1] * g * 0.5f;
-       ambientcolor[2] = rsurface.modellight_ambient[2] * b * 0.5f;
-       diffusecolor[0] = rsurface.modellight_diffuse[0] * r * 0.5f;
-       diffusecolor[1] = rsurface.modellight_diffuse[1] * g * 0.5f;
-       diffusecolor[2] = rsurface.modellight_diffuse[2] * b * 0.5f;
+       f = 0.5f * r_refdef.lightmapintensity;
+       ambientcolor[0] = rsurface.modellight_ambient[0] * r * f;
+       ambientcolor[1] = rsurface.modellight_ambient[1] * g * f;
+       ambientcolor[2] = rsurface.modellight_ambient[2] * b * f;
+       diffusecolor[0] = rsurface.modellight_diffuse[0] * r * f;
+       diffusecolor[1] = rsurface.modellight_diffuse[1] * g * f;
+       diffusecolor[2] = rsurface.modellight_diffuse[2] * b * f;
        if (VectorLength2(diffusecolor) > 0)
        {
                // generate color arrays for the surfaces in this list
@@ -5271,12 +5448,20 @@ static void RSurf_DrawBatch_GL11_VertexShade(int texturenumsurfaces, msurface_t
        RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
 }
 
-static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
+void RSurf_SetupDepthAndCulling(void)
 {
+       // submodels are biased to avoid z-fighting with world surfaces that they
+       // may be exactly overlapping (avoids z-fighting artifacts on certain
+       // doors and things in Quake maps)
        GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
-       GL_PolygonOffset(rsurface.texture->currentpolygonfactor, rsurface.texture->currentpolygonoffset);
+       GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
        GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
        GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_view.cullface_back);
+}
+
+static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
+{
+       RSurf_SetupDepthAndCulling();
        if (rsurface.mode != RSURFMODE_SHOWSURFACES)
        {
                rsurface.mode = RSURFMODE_SHOWSURFACES;
@@ -5309,10 +5494,7 @@ static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, msurface_t **te
                // restore entity matrix
                R_Mesh_Matrix(&rsurface.matrix);
        }
-       GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
-       GL_PolygonOffset(rsurface.texture->currentpolygonfactor, rsurface.texture->currentpolygonoffset);
-       GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
-       GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_view.cullface_back);
+       RSurf_SetupDepthAndCulling();
        GL_DepthMask(true);
        // LordHavoc: HalfLife maps have freaky skypolys so don't use
        // skymasking on them, and Quake3 never did sky masking (unlike
@@ -5322,7 +5504,7 @@ static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, msurface_t **te
        // level, so don't use it then either.
        if (r_refdef.worldmodel && r_refdef.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_viewcache.world_novis)
        {
-               GL_Color(r_refdef.fogcolor[0] * r_view.colorscale, r_refdef.fogcolor[1] * r_view.colorscale, r_refdef.fogcolor[2] * r_view.colorscale, 1);
+               GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
                R_Mesh_ColorPointer(NULL, 0, 0);
                R_Mesh_ResetTextureState();
                if (skyrendermasked)
@@ -5354,6 +5536,7 @@ static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, msurface_t **t
        {
                rsurface.mode = RSURFMODE_GLSL;
                R_Mesh_ResetTextureState();
+               GL_Color(1, 1, 1, 1);
        }
 
        R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
@@ -5395,7 +5578,7 @@ static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, msurface_t **t
                GL_Color(1, 1, 1, 1);
                R_Mesh_ColorPointer(NULL, 0, 0);
 
-               R_SetupSurfaceShader(vec3_origin, rsurface.lightmode == 2, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND);
+               R_SetupSurfaceShader(vec3_origin, rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND);
                if (r_glsl_permutation)
                {
                        RSurf_PrepareVerticesForBatch(true, true, texturenumsurfaces, texturesurfacelist);
@@ -5432,20 +5615,16 @@ static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, msurface_t **t
                R_Mesh_TexBind(12, R_GetTexture(r_texture_white)); // changed per surface
        }
 
-       R_SetupSurfaceShader(vec3_origin, rsurface.lightmode == 2, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
+       R_SetupSurfaceShader(vec3_origin, rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
        if (!r_glsl_permutation)
                return;
 
-       if (rsurface.lightmode == 2)
-               RSurf_PrepareVerticesForBatch(true, r_glsl_permutation->loc_Texture_Normal >= 0, texturenumsurfaces, texturesurfacelist);
-       else
-               RSurf_PrepareVerticesForBatch(r_glsl_permutation->loc_Texture_Normal >= 0, r_glsl_permutation->loc_Texture_Normal >= 0, texturenumsurfaces, texturesurfacelist);
+       RSurf_PrepareVerticesForBatch(r_glsl_permutation->loc_Texture_Normal >= 0 || r_glsl_permutation->loc_LightDir >= 0, r_glsl_permutation->loc_Texture_Normal >= 0, texturenumsurfaces, texturesurfacelist);
        R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
        R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
        R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
        R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
        R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
-       GL_Color(rsurface.texture->currentlayers[0].color[0], rsurface.texture->currentlayers[0].color[1], rsurface.texture->currentlayers[0].color[2], rsurface.texture->currentlayers[0].color[3]);
 
        if (r_glsl_permutation->loc_Texture_Refraction >= 0)
        {
@@ -5536,7 +5715,7 @@ static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, msurface_t **t
                        m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
                        m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
                        R_Mesh_TextureState(&m);
-                       if (rsurface.lightmode == 2)
+                       if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
                                RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
                        else if (rsurface.uselightmaptexture)
                                RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
@@ -5638,7 +5817,7 @@ static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, msurface_t **t
                                m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
                                m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
                                R_Mesh_TextureState(&m);
-                               if (rsurface.lightmode == 2)
+                               if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
                                        RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
                                else if (rsurface.uselightmaptexture)
                                        RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
@@ -5666,7 +5845,7 @@ static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, msurface_t **t
                                m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
                                m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
                                R_Mesh_TextureState(&m);
-                               if (rsurface.lightmode == 2)
+                               if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
                                        RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
                                else
                                        RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
@@ -5755,9 +5934,7 @@ static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **textur
                        GL_ColorMask(0,0,0,0);
                        GL_Color(1,1,1,1);
                }
-               GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
-               GL_PolygonOffset(rsurface.texture->currentpolygonfactor, rsurface.texture->currentpolygonoffset);
-               GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_view.cullface_back);
+               RSurf_SetupDepthAndCulling();
                GL_DepthTest(true);
                GL_BlendFunc(GL_ONE, GL_ZERO);
                GL_DepthMask(true);
@@ -5767,7 +5944,6 @@ static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **textur
                RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
                RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
                GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
-               r_refdef.stats.entities_surfaces += texturenumsurfaces;
        }
        else if (r_depthfirst.integer == 3)
                return;
@@ -5780,10 +5956,8 @@ static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **textur
        {
                if (rsurface.mode != RSURFMODE_MULTIPASS)
                        rsurface.mode = RSURFMODE_MULTIPASS;
-               GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
-               GL_PolygonOffset(rsurface.texture->currentpolygonfactor, rsurface.texture->currentpolygonoffset);
+               RSurf_SetupDepthAndCulling();
                GL_DepthTest(true);
-               GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_view.cullface_back);
                GL_BlendFunc(GL_ONE, GL_ZERO);
                GL_DepthMask(writedepth);
                GL_Color(1,1,1,1);
@@ -5792,7 +5966,6 @@ static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **textur
                R_Mesh_ResetTextureState();
                RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
                R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
-               r_refdef.stats.entities_surfaces += texturenumsurfaces;
        }
        else if (gl_lightmaps.integer)
        {
@@ -5806,8 +5979,6 @@ static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **textur
                GL_DepthMask(writedepth);
                GL_Color(1,1,1,1);
                GL_AlphaTest(false);
-               // use lightmode 0 (fullbright or lightmap) or 2 (model lighting)
-               rsurface.lightmode = ((rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT) || rsurface.modeltexcoordlightmap2f != NULL) ? 0 : 2;
                R_Mesh_ColorPointer(NULL, 0, 0);
                memset(&m, 0, sizeof(m));
                m.tex[0] = R_GetTexture(r_texture_white);
@@ -5815,41 +5986,31 @@ static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **textur
                m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
                m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
                R_Mesh_TextureState(&m);
-               RSurf_PrepareVerticesForBatch(rsurface.lightmode == 2, false, texturenumsurfaces, texturesurfacelist);
-               if (rsurface.lightmode == 2)
+               RSurf_PrepareVerticesForBatch(rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, false, texturenumsurfaces, texturesurfacelist);
+               if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
                        RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
                else if (rsurface.uselightmaptexture)
                        RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
                else
                        RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
-               r_refdef.stats.entities_surfaces += texturenumsurfaces;
        }
        else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY)
-       {
                R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
-               r_refdef.stats.entities_surfaces += texturenumsurfaces;
-       }
        else if (rsurface.texture->currentnumlayers)
        {
                // write depth for anything we skipped on the depth-only pass earlier
                if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
                        writedepth = true;
-               GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
-               GL_PolygonOffset(rsurface.texture->currentpolygonfactor, rsurface.texture->currentpolygonoffset);
-               GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
-               GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_view.cullface_back);
+               RSurf_SetupDepthAndCulling();
                GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
                GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
                GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
-               // use lightmode 0 (fullbright or lightmap) or 2 (model lighting)
-               rsurface.lightmode = ((rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT) || rsurface.modeltexcoordlightmap2f != NULL) ? 0 : 2;
                if (r_glsl.integer && gl_support_fragment_shader)
                        R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist);
                else if (gl_combine.integer && r_textureunits.integer >= 2)
                        R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist);
                else
                        R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist);
-               r_refdef.stats.entities_surfaces += texturenumsurfaces;
        }
        CHECKGLERROR
        GL_LockArrays(0, 0);
@@ -6115,35 +6276,38 @@ void R_DrawDebugModel(entity_render_t *ent)
                                }
                                if (r_shownormals.value > 0)
                                {
-                                       GL_Color(r_view.colorscale, 0, 0, r_shownormals.value);
                                        qglBegin(GL_LINES);
                                        for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
                                        {
                                                VectorCopy(rsurface.vertex3f + l * 3, v);
+                                               GL_Color(r_view.colorscale, 0, 0, 1);
                                                qglVertex3f(v[0], v[1], v[2]);
-                                               VectorMA(v, 8, rsurface.svector3f + l * 3, v);
+                                               VectorMA(v, r_shownormals.value, rsurface.svector3f + l * 3, v);
+                                               GL_Color(r_view.colorscale, 1, 1, 1);
                                                qglVertex3f(v[0], v[1], v[2]);
                                        }
                                        qglEnd();
                                        CHECKGLERROR
-                                       GL_Color(0, 0, r_view.colorscale, r_shownormals.value);
                                        qglBegin(GL_LINES);
                                        for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
                                        {
                                                VectorCopy(rsurface.vertex3f + l * 3, v);
+                                               GL_Color(0, r_view.colorscale, 0, 1);
                                                qglVertex3f(v[0], v[1], v[2]);
-                                               VectorMA(v, 8, rsurface.tvector3f + l * 3, v);
+                                               VectorMA(v, r_shownormals.value, rsurface.tvector3f + l * 3, v);
+                                               GL_Color(r_view.colorscale, 1, 1, 1);
                                                qglVertex3f(v[0], v[1], v[2]);
                                        }
                                        qglEnd();
                                        CHECKGLERROR
-                                       GL_Color(0, r_view.colorscale, 0, r_shownormals.value);
                                        qglBegin(GL_LINES);
                                        for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
                                        {
                                                VectorCopy(rsurface.vertex3f + l * 3, v);
+                                               GL_Color(0, 0, r_view.colorscale, 1);
                                                qglVertex3f(v[0], v[1], v[2]);
-                                               VectorMA(v, 8, rsurface.normal3f + l * 3, v);
+                                               VectorMA(v, r_shownormals.value, rsurface.normal3f + l * 3, v);
+                                               GL_Color(r_view.colorscale, 1, 1, 1);
                                                qglVertex3f(v[0], v[1], v[2]);
                                        }
                                        qglEnd();
@@ -6159,8 +6323,7 @@ extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes, qboolean debug)
 {
        int i, j, endj, f, flagsmask;
-       int counttriangles = 0;
-       msurface_t *surface, **surfacechain;
+       msurface_t *surface;
        texture_t *t;
        model_t *model = r_refdef.worldmodel;
        const int maxsurfacelist = 1024;
@@ -6171,17 +6334,19 @@ void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean dep
 
        RSurf_ActiveWorldEntity();
 
-       // update light styles
-       if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.light_styleupdatechains)
+       // update light styles on this submodel
+       if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
        {
-               for (i = 0;i < model->brushq1.light_styles;i++)
+               model_brush_lightstyleinfo_t *style;
+               for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
                {
-                       if (model->brushq1.light_stylevalue[i] != r_refdef.lightstylevalue[model->brushq1.light_style[i]])
+                       if (style->value != r_refdef.lightstylevalue[style->style])
                        {
-                               model->brushq1.light_stylevalue[i] = r_refdef.lightstylevalue[model->brushq1.light_style[i]];
-                               if ((surfacechain = model->brushq1.light_styleupdatechains[i]))
-                                       for (;(surface = *surfacechain);surfacechain++)
-                                               surface->cached_dlight = true;
+                               msurface_t *surfaces = model->data_surfaces;
+                               int *list = style->surfacelist;
+                               style->value = r_refdef.lightstylevalue[style->style];
+                               for (j = 0;j < style->numsurfaces;j++)
+                                       surfaces[list[j]].cached_dlight = true;
                        }
                }
        }
@@ -6220,26 +6385,26 @@ void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean dep
                                        R_BuildLightMap(r_refdef.worldentity, surface);
                                // add face to draw list
                                surfacelist[numsurfacelist++] = surface;
-                               counttriangles += surface->num_triangles;
+                               r_refdef.stats.world_triangles += surface->num_triangles;
                                if (numsurfacelist >= maxsurfacelist)
                                {
+                                       r_refdef.stats.world_surfaces += numsurfacelist;
                                        R_QueueSurfaceList(r_refdef.worldentity, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
                                        numsurfacelist = 0;
                                }
                        }
                }
        }
+       r_refdef.stats.world_surfaces += numsurfacelist;
        if (numsurfacelist)
                R_QueueSurfaceList(r_refdef.worldentity, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
-       r_refdef.stats.entities_triangles += counttriangles;
        RSurf_CleanUp();
 }
 
 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes, qboolean debug)
 {
-       int i, f, flagsmask;
-       int counttriangles = 0;
-       msurface_t *surface, *endsurface, **surfacechain;
+       int i, j, f, flagsmask;
+       msurface_t *surface, *endsurface;
        texture_t *t;
        model_t *model = ent->model;
        const int maxsurfacelist = 1024;
@@ -6259,16 +6424,18 @@ void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean wr
                RSurf_ActiveModelEntity(ent, true, r_glsl.integer && gl_support_fragment_shader && !depthonly);
 
        // update light styles
-       if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.light_styleupdatechains)
+       if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
        {
-               for (i = 0;i < model->brushq1.light_styles;i++)
+               model_brush_lightstyleinfo_t *style;
+               for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
                {
-                       if (model->brushq1.light_stylevalue[i] != r_refdef.lightstylevalue[model->brushq1.light_style[i]])
+                       if (style->value != r_refdef.lightstylevalue[style->style])
                        {
-                               model->brushq1.light_stylevalue[i] = r_refdef.lightstylevalue[model->brushq1.light_style[i]];
-                               if ((surfacechain = model->brushq1.light_styleupdatechains[i]))
-                                       for (;(surface = *surfacechain);surfacechain++)
-                                               surface->cached_dlight = true;
+                               msurface_t *surfaces = model->data_surfaces;
+                               int *list = style->surfacelist;
+                               style->value = r_refdef.lightstylevalue[style->style];
+                               for (j = 0;j < style->numsurfaces;j++)
+                                       surfaces[list[j]].cached_dlight = true;
                        }
                }
        }
@@ -6299,16 +6466,17 @@ void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean wr
                                R_BuildLightMap(ent, surface);
                        // add face to draw list
                        surfacelist[numsurfacelist++] = surface;
-                       counttriangles += surface->num_triangles;
+                       r_refdef.stats.entities_triangles += surface->num_triangles;
                        if (numsurfacelist >= maxsurfacelist)
                        {
+                               r_refdef.stats.entities_surfaces += numsurfacelist;
                                R_QueueSurfaceList(ent, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
                                numsurfacelist = 0;
                        }
                }
        }
+       r_refdef.stats.entities_surfaces += numsurfacelist;
        if (numsurfacelist)
                R_QueueSurfaceList(ent, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
-       r_refdef.stats.entities_triangles += counttriangles;
        RSurf_CleanUp();
 }