]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_rmain.c
fix error with unused ClientTime reference
[xonotic/darkplaces.git] / gl_rmain.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_main.c
21
22 #include "quakedef.h"
23 #include "cl_dyntexture.h"
24 #include "r_shadow.h"
25 #include "polygon.h"
26 #include "image.h"
27 #include "ft2.h"
28 #include "csprogs.h"
29 #include "cl_video.h"
30 #include "dpsoftrast.h"
31
32 #ifdef SUPPORTD3D
33 #include <d3d9.h>
34 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
35 #endif
36
37 mempool_t *r_main_mempool;
38 rtexturepool_t *r_main_texturepool;
39
40 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
41
42 static qboolean r_loadnormalmap;
43 static qboolean r_loadgloss;
44 qboolean r_loadfog;
45 static qboolean r_loaddds;
46 static qboolean r_savedds;
47
48 //
49 // screen size info
50 //
51 r_refdef_t r_refdef;
52
53 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "screen motionblur - value represents intensity, somewhere around 0.5 recommended"};
54 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "screen motionblur based on damage - value represents intensity, somewhere around 0.5 recommended"};
55 cvar_t r_motionblur_averaging = {CVAR_SAVE, "r_motionblur_averaging", "0.1", "sliding average reaction time for velocity (higher = slower adaption to change)"};
56 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
57 cvar_t r_motionblur_minblur = {CVAR_SAVE, "r_motionblur_minblur", "0.5", "factor of blur to apply at all times (always have this amount of blur no matter what the other factors are)"};
58 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.9", "maxmimum amount of blur"};
59 cvar_t r_motionblur_velocityfactor = {CVAR_SAVE, "r_motionblur_velocityfactor", "1", "factoring in of player velocity to the blur equation - the faster the player moves around the map, the more blur they get"};
60 cvar_t r_motionblur_velocityfactor_minspeed = {CVAR_SAVE, "r_motionblur_velocityfactor_minspeed", "400", "lower value of velocity when it starts to factor into blur equation"};
61 cvar_t r_motionblur_velocityfactor_maxspeed = {CVAR_SAVE, "r_motionblur_velocityfactor_maxspeed", "800", "upper value of velocity when it reaches the peak factor into blur equation"};
62 cvar_t r_motionblur_mousefactor = {CVAR_SAVE, "r_motionblur_mousefactor", "2", "factoring in of mouse acceleration to the blur equation - the faster the player turns their mouse, the more blur they get"};
63 cvar_t r_motionblur_mousefactor_minspeed = {CVAR_SAVE, "r_motionblur_mousefactor_minspeed", "0", "lower value of mouse acceleration when it starts to factor into blur equation"};
64 cvar_t r_motionblur_mousefactor_maxspeed = {CVAR_SAVE, "r_motionblur_mousefactor_maxspeed", "50", "upper value of mouse acceleration when it reaches the peak factor into blur equation"};
65
66 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
67 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
68 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
69 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
70 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
71
72 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
73 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
74 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
75 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
76 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
77 cvar_t r_deformvertexes = {0, "r_deformvertexes", "1", "allows use of deformvertexes in shader files (can be turned off to check performance impact)"};
78 cvar_t r_transparent = {0, "r_transparent", "1", "allows use of transparent surfaces (can be turned off to check performance impact)"};
79 cvar_t r_transparent_alphatocoverage = {0, "r_transparent_alphatocoverage", "1", "enables GL_ALPHA_TO_COVERAGE antialiasing technique on alphablend and alphatest surfaces when using vid_samples 2 or higher"};
80 cvar_t r_showoverdraw = {0, "r_showoverdraw", "0", "shows overlapping geometry"};
81 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
82 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
83 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
84 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
85 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
86 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
87 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
88 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
89 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
90 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
91 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
92 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
93 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
94 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
95 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
96 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
97 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
98 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling (in addition to center sample)"};
99 cvar_t r_cullentities_trace_tempentitysamples = {0, "r_cullentities_trace_tempentitysamples", "-1", "number of samples to test for entity culling of temp entities (including all CSQC entities), -1 disables trace culling on these entities to prevent flicker (pvs still applies)"};
100 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
101 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
102 cvar_t r_sortentities = {0, "r_sortentities", "0", "sort entities before drawing (might be faster)"};
103 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
104 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
105
106 cvar_t r_fakelight = {0, "r_fakelight","0", "render 'fake' lighting instead of real lightmaps"};
107 cvar_t r_fakelight_intensity = {0, "r_fakelight_intensity","0.75", "fakelight intensity modifier"};
108 #define FAKELIGHT_ENABLED (r_fakelight.integer >= 2 || (r_fakelight.integer && r_refdef.scene.worldmodel && !r_refdef.scene.worldmodel->lit))
109
110 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
111 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
112 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
113 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this); when set to 2, always cast the shadows in the direction set by r_shadows_throwdirection, otherwise use the model lighting."};
114 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
115 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
116 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
117 cvar_t r_shadows_drawafterrtlighting = {CVAR_SAVE, "r_shadows_drawafterrtlighting", "0", "draw fake shadows AFTER realtime lightning is drawn. May be useful for simulating fast sunlight on large outdoor maps with only one noshadow rtlight. The price is less realistic appearance of dynamic light shadows."};
118 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
119 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
120 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
121 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
122 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"};
123 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "14", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
124 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
125 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
126 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
127 cvar_t r_fog_clear = {0, "r_fog_clear", "1", "clears renderbuffer with fog color before render starts"};
128 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
129 cvar_t r_transparentdepthmasking = {CVAR_SAVE, "r_transparentdepthmasking", "0", "enables depth writes on transparent meshes whose materially is normally opaque, this prevents seeing the inside of a transparent mesh"};
130 cvar_t r_transparent_sortmindist = {CVAR_SAVE, "r_transparent_sortmindist", "0", "lower distance limit for transparent sorting"};
131 cvar_t r_transparent_sortmaxdist = {CVAR_SAVE, "r_transparent_sortmaxdist", "32768", "upper distance limit for transparent sorting"};
132 cvar_t r_transparent_sortarraysize = {CVAR_SAVE, "r_transparent_sortarraysize", "4096", "number of distance-sorting layers"};
133
134 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
135 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
136 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
137 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
138 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
139 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
140 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
141 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
142
143 cvar_t r_texture_dds_load = {CVAR_SAVE, "r_texture_dds_load", "0", "load compressed dds/filename.dds texture instead of filename.tga, if the file exists (requires driver support)"};
144 cvar_t r_texture_dds_save = {CVAR_SAVE, "r_texture_dds_save", "0", "save compressed dds/filename.dds texture when filename.tga is loaded, so that it can be loaded instead next time"};
145
146 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
147 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
148 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
149
150 cvar_t r_viewfbo = {CVAR_SAVE, "r_viewfbo", "0", "enables use of an 8bit (1) or 16bit (2) or 32bit (3) per component float framebuffer render, which may be at a different resolution than the video mode"};
151 cvar_t r_viewscale = {CVAR_SAVE, "r_viewscale", "1", "scaling factor for resolution of the fbo rendering method, must be > 0, can be above 1 for a costly antialiasing behavior, typical values are 0.5 for 1/4th as many pixels rendered, or 1 for normal rendering"};
152 cvar_t r_viewscale_fpsscaling = {CVAR_SAVE, "r_viewscale_fpsscaling", "0", "change resolution based on framerate"};
153 cvar_t r_viewscale_fpsscaling_min = {CVAR_SAVE, "r_viewscale_fpsscaling_min", "0.0625", "worst acceptable quality"};
154 cvar_t r_viewscale_fpsscaling_multiply = {CVAR_SAVE, "r_viewscale_fpsscaling_multiply", "5", "adjust quality up or down by the frametime difference from 1.0/target, multiplied by this factor"};
155 cvar_t r_viewscale_fpsscaling_stepsize = {CVAR_SAVE, "r_viewscale_fpsscaling_stepsize", "0.01", "smallest adjustment to hit the target framerate (this value prevents minute oscillations)"};
156 cvar_t r_viewscale_fpsscaling_stepmax = {CVAR_SAVE, "r_viewscale_fpsscaling_stepmax", "1.00", "largest adjustment to hit the target framerate (this value prevents wild overshooting of the estimate)"};
157 cvar_t r_viewscale_fpsscaling_target = {CVAR_SAVE, "r_viewscale_fpsscaling_target", "70", "desired framerate"};
158
159 cvar_t r_glsl_deluxemapping = {CVAR_SAVE, "r_glsl_deluxemapping", "1", "use per pixel lighting on deluxemap-compiled q3bsp maps (or a value of 2 forces deluxemap shading even without deluxemaps)"};
160 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
161 cvar_t r_glsl_offsetmapping_steps = {CVAR_SAVE, "r_glsl_offsetmapping_steps", "2", "offset mapping steps (note: too high values may be not supported by your GPU)"};
162 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
163 cvar_t r_glsl_offsetmapping_reliefmapping_steps = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping_steps", "10", "relief mapping steps (note: too high values may be not supported by your GPU)"};
164 cvar_t r_glsl_offsetmapping_reliefmapping_refinesteps = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping_refinesteps", "5", "relief mapping refine steps (these are a binary search executed as the last step as given by r_glsl_offsetmapping_reliefmapping_steps)"};
165 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
166 cvar_t r_glsl_offsetmapping_lod = {CVAR_SAVE, "r_glsl_offsetmapping_lod", "0", "apply distance-based level-of-detail correction to number of offsetmappig steps, effectively making it render faster on large open-area maps"};
167 cvar_t r_glsl_offsetmapping_lod_distance = {CVAR_SAVE, "r_glsl_offsetmapping_lod_distance", "32", "first LOD level distance, second level (-50% steps) is 2x of this, third (33%) - 3x etc."};
168 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
169 cvar_t r_glsl_postprocess_uservec1 = {CVAR_SAVE, "r_glsl_postprocess_uservec1", "0 0 0 0", "a 4-component vector to pass as uservec1 to the postprocessing shader (only useful if default.glsl has been customized)"};
170 cvar_t r_glsl_postprocess_uservec2 = {CVAR_SAVE, "r_glsl_postprocess_uservec2", "0 0 0 0", "a 4-component vector to pass as uservec2 to the postprocessing shader (only useful if default.glsl has been customized)"};
171 cvar_t r_glsl_postprocess_uservec3 = {CVAR_SAVE, "r_glsl_postprocess_uservec3", "0 0 0 0", "a 4-component vector to pass as uservec3 to the postprocessing shader (only useful if default.glsl has been customized)"};
172 cvar_t r_glsl_postprocess_uservec4 = {CVAR_SAVE, "r_glsl_postprocess_uservec4", "0 0 0 0", "a 4-component vector to pass as uservec4 to the postprocessing shader (only useful if default.glsl has been customized)"};
173 cvar_t r_glsl_postprocess_uservec1_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec1_enable", "1", "enables postprocessing uservec1 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
174 cvar_t r_glsl_postprocess_uservec2_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec2_enable", "1", "enables postprocessing uservec2 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
175 cvar_t r_glsl_postprocess_uservec3_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec3_enable", "1", "enables postprocessing uservec3 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
176 cvar_t r_glsl_postprocess_uservec4_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec4_enable", "1", "enables postprocessing uservec4 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
177
178 cvar_t r_water = {CVAR_SAVE, "r_water", "0", "whether to use reflections and refraction on water surfaces (note: r_wateralpha must be set below 1)"};
179 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
180 cvar_t r_water_resolutionmultiplier = {CVAR_SAVE, "r_water_resolutionmultiplier", "0.5", "multiplier for screen resolution when rendering refracted/reflected scenes, 1 is full quality, lower values are faster"};
181 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
182 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
183 cvar_t r_water_scissormode = {0, "r_water_scissormode", "3", "scissor (1) or cull (2) or both (3) water renders"};
184 cvar_t r_water_lowquality = {0, "r_water_lowquality", "0", "special option to accelerate water rendering, 1 disables shadows and particles, 2 disables all dynamic lights"};
185
186 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
187 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
188 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
189 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
190
191 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
192 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
193 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
194 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
195 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
196 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exaggerated the glow is"};
197 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
198
199 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
200 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
201 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
202 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivalent to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
203 cvar_t r_hdr_irisadaptation = {CVAR_SAVE, "r_hdr_irisadaptation", "0", "adjust scene brightness according to light intensity at player location"};
204 cvar_t r_hdr_irisadaptation_multiplier = {CVAR_SAVE, "r_hdr_irisadaptation_multiplier", "2", "brightness at which value will be 1.0"};
205 cvar_t r_hdr_irisadaptation_minvalue = {CVAR_SAVE, "r_hdr_irisadaptation_minvalue", "0.5", "minimum value that can result from multiplier / brightness"};
206 cvar_t r_hdr_irisadaptation_maxvalue = {CVAR_SAVE, "r_hdr_irisadaptation_maxvalue", "4", "maximum value that can result from multiplier / brightness"};
207 cvar_t r_hdr_irisadaptation_value = {0, "r_hdr_irisadaptation_value", "1", "current value as scenebrightness multiplier, changes continuously when irisadaptation is active"};
208 cvar_t r_hdr_irisadaptation_fade_up = {CVAR_SAVE, "r_hdr_irisadaptation_fade_up", "0.1", "fade rate at which value adjusts to darkness"};
209 cvar_t r_hdr_irisadaptation_fade_down = {CVAR_SAVE, "r_hdr_irisadaptation_fade_down", "0.5", "fade rate at which value adjusts to brightness"};
210
211 cvar_t r_smoothnormals_areaweighting = {0, "r_smoothnormals_areaweighting", "1", "uses significantly faster (and supposedly higher quality) area-weighted vertex normals and tangent vectors rather than summing normalized triangle normals and tangents"};
212
213 cvar_t developer_texturelogging = {0, "developer_texturelogging", "0", "produces a textures.log file containing names of skins and map textures the engine tried to load"};
214
215 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
216
217 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
218
219 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
220 cvar_t r_glsl_saturation_redcompensate = {CVAR_SAVE, "r_glsl_saturation_redcompensate", "0", "a 'vampire sight' addition to desaturation effect, does compensation for red color, r_glsl_restart is required"};
221
222 cvar_t r_glsl_vertextextureblend_usebothalphas = {CVAR_SAVE, "r_glsl_vertextextureblend_usebothalphas", "0", "use both alpha layers on vertex blended surfaces, each alpha layer sets amount of 'blend leak' on another layer."};
223
224 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "0.5", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
225
226 extern cvar_t v_glslgamma;
227 extern cvar_t v_glslgamma_2d;
228
229 extern qboolean v_flipped_state;
230
231 static struct r_bloomstate_s
232 {
233         qboolean enabled;
234         qboolean hdr;
235
236         int bloomwidth, bloomheight;
237
238         textype_t texturetype;
239         int viewfbo; // used to check if r_viewfbo cvar has changed
240
241         int fbo_framebuffer; // non-zero if r_viewfbo is enabled and working
242         rtexture_t *texture_framebuffercolor; // non-NULL if fbo_screen is non-zero
243         rtexture_t *texture_framebufferdepth; // non-NULL if fbo_screen is non-zero
244
245         int screentexturewidth, screentextureheight;
246         rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
247
248         int bloomtexturewidth, bloomtextureheight;
249         rtexture_t *texture_bloom;
250
251         // arrays for rendering the screen passes
252         float screentexcoord2f[8];
253         float bloomtexcoord2f[8];
254         float offsettexcoord2f[8];
255
256         r_viewport_t viewport;
257 }
258 r_bloomstate;
259
260 r_waterstate_t r_waterstate;
261
262 /// shadow volume bsp struct with automatically growing nodes buffer
263 svbsp_t r_svbsp;
264
265 rtexture_t *r_texture_blanknormalmap;
266 rtexture_t *r_texture_white;
267 rtexture_t *r_texture_grey128;
268 rtexture_t *r_texture_black;
269 rtexture_t *r_texture_notexture;
270 rtexture_t *r_texture_whitecube;
271 rtexture_t *r_texture_normalizationcube;
272 rtexture_t *r_texture_fogattenuation;
273 rtexture_t *r_texture_fogheighttexture;
274 rtexture_t *r_texture_gammaramps;
275 unsigned int r_texture_gammaramps_serial;
276 //rtexture_t *r_texture_fogintensity;
277 rtexture_t *r_texture_reflectcube;
278
279 // TODO: hash lookups?
280 typedef struct cubemapinfo_s
281 {
282         char basename[64];
283         rtexture_t *texture;
284 }
285 cubemapinfo_t;
286
287 int r_texture_numcubemaps;
288 cubemapinfo_t *r_texture_cubemaps[MAX_CUBEMAPS];
289
290 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
291 unsigned int r_numqueries;
292 unsigned int r_maxqueries;
293
294 typedef struct r_qwskincache_s
295 {
296         char name[MAX_QPATH];
297         skinframe_t *skinframe;
298 }
299 r_qwskincache_t;
300
301 static r_qwskincache_t *r_qwskincache;
302 static int r_qwskincache_size;
303
304 /// vertex coordinates for a quad that covers the screen exactly
305 extern const float r_screenvertex3f[12];
306 extern const float r_d3dscreenvertex3f[12];
307 const float r_screenvertex3f[12] =
308 {
309         0, 0, 0,
310         1, 0, 0,
311         1, 1, 0,
312         0, 1, 0
313 };
314 const float r_d3dscreenvertex3f[12] =
315 {
316         0, 1, 0,
317         1, 1, 0,
318         1, 0, 0,
319         0, 0, 0
320 };
321
322 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
323 {
324         int i;
325         for (i = 0;i < verts;i++)
326         {
327                 out[0] = in[0] * r;
328                 out[1] = in[1] * g;
329                 out[2] = in[2] * b;
330                 out[3] = in[3];
331                 in += 4;
332                 out += 4;
333         }
334 }
335
336 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
337 {
338         int i;
339         for (i = 0;i < verts;i++)
340         {
341                 out[0] = r;
342                 out[1] = g;
343                 out[2] = b;
344                 out[3] = a;
345                 out += 4;
346         }
347 }
348
349 // FIXME: move this to client?
350 void FOG_clear(void)
351 {
352         if (gamemode == GAME_NEHAHRA)
353         {
354                 Cvar_Set("gl_fogenable", "0");
355                 Cvar_Set("gl_fogdensity", "0.2");
356                 Cvar_Set("gl_fogred", "0.3");
357                 Cvar_Set("gl_foggreen", "0.3");
358                 Cvar_Set("gl_fogblue", "0.3");
359         }
360         r_refdef.fog_density = 0;
361         r_refdef.fog_red = 0;
362         r_refdef.fog_green = 0;
363         r_refdef.fog_blue = 0;
364         r_refdef.fog_alpha = 1;
365         r_refdef.fog_start = 0;
366         r_refdef.fog_end = 16384;
367         r_refdef.fog_height = 1<<30;
368         r_refdef.fog_fadedepth = 128;
369         memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
370 }
371
372 static void R_BuildBlankTextures(void)
373 {
374         unsigned char data[4];
375         data[2] = 128; // normal X
376         data[1] = 128; // normal Y
377         data[0] = 255; // normal Z
378         data[3] = 255; // height
379         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
380         data[0] = 255;
381         data[1] = 255;
382         data[2] = 255;
383         data[3] = 255;
384         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
385         data[0] = 128;
386         data[1] = 128;
387         data[2] = 128;
388         data[3] = 255;
389         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
390         data[0] = 0;
391         data[1] = 0;
392         data[2] = 0;
393         data[3] = 255;
394         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
395 }
396
397 static void R_BuildNoTexture(void)
398 {
399         int x, y;
400         unsigned char pix[16][16][4];
401         // this makes a light grey/dark grey checkerboard texture
402         for (y = 0;y < 16;y++)
403         {
404                 for (x = 0;x < 16;x++)
405                 {
406                         if ((y < 8) ^ (x < 8))
407                         {
408                                 pix[y][x][0] = 128;
409                                 pix[y][x][1] = 128;
410                                 pix[y][x][2] = 128;
411                                 pix[y][x][3] = 255;
412                         }
413                         else
414                         {
415                                 pix[y][x][0] = 64;
416                                 pix[y][x][1] = 64;
417                                 pix[y][x][2] = 64;
418                                 pix[y][x][3] = 255;
419                         }
420                 }
421         }
422         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
423 }
424
425 static void R_BuildWhiteCube(void)
426 {
427         unsigned char data[6*1*1*4];
428         memset(data, 255, sizeof(data));
429         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
430 }
431
432 static void R_BuildNormalizationCube(void)
433 {
434         int x, y, side;
435         vec3_t v;
436         vec_t s, t, intensity;
437 #define NORMSIZE 64
438         unsigned char *data;
439         data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
440         for (side = 0;side < 6;side++)
441         {
442                 for (y = 0;y < NORMSIZE;y++)
443                 {
444                         for (x = 0;x < NORMSIZE;x++)
445                         {
446                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
447                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
448                                 switch(side)
449                                 {
450                                 default:
451                                 case 0:
452                                         v[0] = 1;
453                                         v[1] = -t;
454                                         v[2] = -s;
455                                         break;
456                                 case 1:
457                                         v[0] = -1;
458                                         v[1] = -t;
459                                         v[2] = s;
460                                         break;
461                                 case 2:
462                                         v[0] = s;
463                                         v[1] = 1;
464                                         v[2] = t;
465                                         break;
466                                 case 3:
467                                         v[0] = s;
468                                         v[1] = -1;
469                                         v[2] = -t;
470                                         break;
471                                 case 4:
472                                         v[0] = s;
473                                         v[1] = -t;
474                                         v[2] = 1;
475                                         break;
476                                 case 5:
477                                         v[0] = -s;
478                                         v[1] = -t;
479                                         v[2] = -1;
480                                         break;
481                                 }
482                                 intensity = 127.0f / sqrt(DotProduct(v, v));
483                                 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
484                                 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
485                                 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
486                                 data[((side*64+y)*64+x)*4+3] = 255;
487                         }
488                 }
489         }
490         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
491         Mem_Free(data);
492 }
493
494 static void R_BuildFogTexture(void)
495 {
496         int x, b;
497 #define FOGWIDTH 256
498         unsigned char data1[FOGWIDTH][4];
499         //unsigned char data2[FOGWIDTH][4];
500         double d, r, alpha;
501
502         r_refdef.fogmasktable_start = r_refdef.fog_start;
503         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
504         r_refdef.fogmasktable_range = r_refdef.fogrange;
505         r_refdef.fogmasktable_density = r_refdef.fog_density;
506
507         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
508         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
509         {
510                 d = (x * r - r_refdef.fogmasktable_start);
511                 if(developer_extra.integer)
512                         Con_DPrintf("%f ", d);
513                 d = max(0, d);
514                 if (r_fog_exp2.integer)
515                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
516                 else
517                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
518                 if(developer_extra.integer)
519                         Con_DPrintf(" : %f ", alpha);
520                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
521                 if(developer_extra.integer)
522                         Con_DPrintf(" = %f\n", alpha);
523                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
524         }
525
526         for (x = 0;x < FOGWIDTH;x++)
527         {
528                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
529                 data1[x][0] = b;
530                 data1[x][1] = b;
531                 data1[x][2] = b;
532                 data1[x][3] = 255;
533                 //data2[x][0] = 255 - b;
534                 //data2[x][1] = 255 - b;
535                 //data2[x][2] = 255 - b;
536                 //data2[x][3] = 255;
537         }
538         if (r_texture_fogattenuation)
539         {
540                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
541                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
542         }
543         else
544         {
545                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
546                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
547         }
548 }
549
550 static void R_BuildFogHeightTexture(void)
551 {
552         unsigned char *inpixels;
553         int size;
554         int x;
555         int y;
556         int j;
557         float c[4];
558         float f;
559         inpixels = NULL;
560         strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
561         if (r_refdef.fogheighttexturename[0])
562                 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
563         if (!inpixels)
564         {
565                 r_refdef.fog_height_tablesize = 0;
566                 if (r_texture_fogheighttexture)
567                         R_FreeTexture(r_texture_fogheighttexture);
568                 r_texture_fogheighttexture = NULL;
569                 if (r_refdef.fog_height_table2d)
570                         Mem_Free(r_refdef.fog_height_table2d);
571                 r_refdef.fog_height_table2d = NULL;
572                 if (r_refdef.fog_height_table1d)
573                         Mem_Free(r_refdef.fog_height_table1d);
574                 r_refdef.fog_height_table1d = NULL;
575                 return;
576         }
577         size = image_width;
578         r_refdef.fog_height_tablesize = size;
579         r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
580         r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
581         memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
582         Mem_Free(inpixels);
583         // LordHavoc: now the magic - what is that table2d for?  it is a cooked
584         // average fog color table accounting for every fog layer between a point
585         // and the camera.  (Note: attenuation is handled separately!)
586         for (y = 0;y < size;y++)
587         {
588                 for (x = 0;x < size;x++)
589                 {
590                         Vector4Clear(c);
591                         f = 0;
592                         if (x < y)
593                         {
594                                 for (j = x;j <= y;j++)
595                                 {
596                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
597                                         f++;
598                                 }
599                         }
600                         else
601                         {
602                                 for (j = x;j >= y;j--)
603                                 {
604                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
605                                         f++;
606                                 }
607                         }
608                         f = 1.0f / f;
609                         r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
610                         r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
611                         r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
612                         r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
613                 }
614         }
615         r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
616 }
617
618 //=======================================================================================================================================================
619
620 static const char *builtinshaderstring =
621 #include "shader_glsl.h"
622 ;
623
624 const char *builtinhlslshaderstring =
625 #include "shader_hlsl.h"
626 ;
627
628 char *glslshaderstring = NULL;
629 char *hlslshaderstring = NULL;
630
631 //=======================================================================================================================================================
632
633 typedef struct shaderpermutationinfo_s
634 {
635         const char *pretext;
636         const char *name;
637 }
638 shaderpermutationinfo_t;
639
640 typedef struct shadermodeinfo_s
641 {
642         const char *vertexfilename;
643         const char *geometryfilename;
644         const char *fragmentfilename;
645         const char *pretext;
646         const char *name;
647 }
648 shadermodeinfo_t;
649
650 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
651 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
652 {
653         {"#define USEDIFFUSE\n", " diffuse"},
654         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
655         {"#define USEVIEWTINT\n", " viewtint"},
656         {"#define USECOLORMAPPING\n", " colormapping"},
657         {"#define USESATURATION\n", " saturation"},
658         {"#define USEFOGINSIDE\n", " foginside"},
659         {"#define USEFOGOUTSIDE\n", " fogoutside"},
660         {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
661         {"#define USEFOGALPHAHACK\n", " fogalphahack"},
662         {"#define USEGAMMARAMPS\n", " gammaramps"},
663         {"#define USECUBEFILTER\n", " cubefilter"},
664         {"#define USEGLOW\n", " glow"},
665         {"#define USEBLOOM\n", " bloom"},
666         {"#define USESPECULAR\n", " specular"},
667         {"#define USEPOSTPROCESSING\n", " postprocessing"},
668         {"#define USEREFLECTION\n", " reflection"},
669         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
670         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
671         {"#define USESHADOWMAP2D\n", " shadowmap2d"},
672         {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
673         {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
674         {"#define USESHADOWSAMPLER\n", " shadowsampler"},
675         {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
676         {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
677         {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
678         {"#define USEALPHAKILL\n", " alphakill"},
679         {"#define USEREFLECTCUBE\n", " reflectcube"},
680         {"#define USENORMALMAPSCROLLBLEND\n", " normalmapscrollblend"},
681         {"#define USEBOUNCEGRID\n", " bouncegrid"},
682         {"#define USEBOUNCEGRIDDIRECTIONAL\n", " bouncegriddirectional"},
683         {"#define USETRIPPY\n", " trippy"},
684 };
685
686 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
687 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
688 {
689         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
690         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
691         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
692         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
693         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
694         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
695         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FAKELIGHT\n", " fakelight"},
696         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
697         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
698         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_LIGHTMAP\n", " lightdirectionmap_forced_lightmap"},
699         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_VERTEXCOLOR\n", " lightdirectionmap_forced_vertexcolor"},
700         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
701         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
702         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
703         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
704         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
705         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
706         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
707 };
708
709 shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
710 {
711         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
712         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
713         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
714         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
715         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
716         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
717         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FAKELIGHT\n", " fakelight"},
718         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
719         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
720         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_LIGHTMAP\n", " lightdirectionmap_forced_lightmap"},
721         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_VERTEXCOLOR\n", " lightdirectionmap_forced_vertexcolor"},
722         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
723         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
724         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
725         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
726         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
727         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
728         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
729 };
730
731 struct r_glsl_permutation_s;
732 typedef struct r_glsl_permutation_s
733 {
734         /// hash lookup data
735         struct r_glsl_permutation_s *hashnext;
736         unsigned int mode;
737         unsigned int permutation;
738
739         /// indicates if we have tried compiling this permutation already
740         qboolean compiled;
741         /// 0 if compilation failed
742         int program;
743         // texture units assigned to each detected uniform
744         int tex_Texture_First;
745         int tex_Texture_Second;
746         int tex_Texture_GammaRamps;
747         int tex_Texture_Normal;
748         int tex_Texture_Color;
749         int tex_Texture_Gloss;
750         int tex_Texture_Glow;
751         int tex_Texture_SecondaryNormal;
752         int tex_Texture_SecondaryColor;
753         int tex_Texture_SecondaryGloss;
754         int tex_Texture_SecondaryGlow;
755         int tex_Texture_Pants;
756         int tex_Texture_Shirt;
757         int tex_Texture_FogHeightTexture;
758         int tex_Texture_FogMask;
759         int tex_Texture_Lightmap;
760         int tex_Texture_Deluxemap;
761         int tex_Texture_Attenuation;
762         int tex_Texture_Cube;
763         int tex_Texture_Refraction;
764         int tex_Texture_Reflection;
765         int tex_Texture_ShadowMap2D;
766         int tex_Texture_CubeProjection;
767         int tex_Texture_ScreenDepth;
768         int tex_Texture_ScreenNormalMap;
769         int tex_Texture_ScreenDiffuse;
770         int tex_Texture_ScreenSpecular;
771         int tex_Texture_ReflectMask;
772         int tex_Texture_ReflectCube;
773         int tex_Texture_BounceGrid;
774         /// locations of detected uniforms in program object, or -1 if not found
775         int loc_Texture_First;
776         int loc_Texture_Second;
777         int loc_Texture_GammaRamps;
778         int loc_Texture_Normal;
779         int loc_Texture_Color;
780         int loc_Texture_Gloss;
781         int loc_Texture_Glow;
782         int loc_Texture_SecondaryNormal;
783         int loc_Texture_SecondaryColor;
784         int loc_Texture_SecondaryGloss;
785         int loc_Texture_SecondaryGlow;
786         int loc_Texture_Pants;
787         int loc_Texture_Shirt;
788         int loc_Texture_FogHeightTexture;
789         int loc_Texture_FogMask;
790         int loc_Texture_Lightmap;
791         int loc_Texture_Deluxemap;
792         int loc_Texture_Attenuation;
793         int loc_Texture_Cube;
794         int loc_Texture_Refraction;
795         int loc_Texture_Reflection;
796         int loc_Texture_ShadowMap2D;
797         int loc_Texture_CubeProjection;
798         int loc_Texture_ScreenDepth;
799         int loc_Texture_ScreenNormalMap;
800         int loc_Texture_ScreenDiffuse;
801         int loc_Texture_ScreenSpecular;
802         int loc_Texture_ReflectMask;
803         int loc_Texture_ReflectCube;
804         int loc_Texture_BounceGrid;
805         int loc_Alpha;
806         int loc_BloomBlur_Parameters;
807         int loc_ClientTime;
808         int loc_Color_Ambient;
809         int loc_Color_Diffuse;
810         int loc_Color_Specular;
811         int loc_Color_Glow;
812         int loc_Color_Pants;
813         int loc_Color_Shirt;
814         int loc_DeferredColor_Ambient;
815         int loc_DeferredColor_Diffuse;
816         int loc_DeferredColor_Specular;
817         int loc_DeferredMod_Diffuse;
818         int loc_DeferredMod_Specular;
819         int loc_DistortScaleRefractReflect;
820         int loc_EyePosition;
821         int loc_FogColor;
822         int loc_FogHeightFade;
823         int loc_FogPlane;
824         int loc_FogPlaneViewDist;
825         int loc_FogRangeRecip;
826         int loc_LightColor;
827         int loc_LightDir;
828         int loc_LightPosition;
829         int loc_OffsetMapping_ScaleSteps;
830         int loc_OffsetMapping_LodDistance;
831         int loc_OffsetMapping_Bias;
832         int loc_PixelSize;
833         int loc_ReflectColor;
834         int loc_ReflectFactor;
835         int loc_ReflectOffset;
836         int loc_RefractColor;
837         int loc_Saturation;
838         int loc_ScreenCenterRefractReflect;
839         int loc_ScreenScaleRefractReflect;
840         int loc_ScreenToDepth;
841         int loc_ShadowMap_Parameters;
842         int loc_ShadowMap_TextureScale;
843         int loc_SpecularPower;
844         int loc_UserVec1;
845         int loc_UserVec2;
846         int loc_UserVec3;
847         int loc_UserVec4;
848         int loc_ViewTintColor;
849         int loc_ViewToLight;
850         int loc_ModelToLight;
851         int loc_TexMatrix;
852         int loc_BackgroundTexMatrix;
853         int loc_ModelViewProjectionMatrix;
854         int loc_ModelViewMatrix;
855         int loc_PixelToScreenTexCoord;
856         int loc_ModelToReflectCube;
857         int loc_ShadowMapMatrix;
858         int loc_BloomColorSubtract;
859         int loc_NormalmapScrollBlend;
860         int loc_BounceGridMatrix;
861         int loc_BounceGridIntensity;
862 }
863 r_glsl_permutation_t;
864
865 #define SHADERPERMUTATION_HASHSIZE 256
866
867
868 // non-degradable "lightweight" shader parameters to keep the permutations simpler
869 // these can NOT degrade! only use for simple stuff
870 enum
871 {
872         SHADERSTATICPARM_SATURATION_REDCOMPENSATE = 0, ///< red compensation filter for saturation
873         SHADERSTATICPARM_EXACTSPECULARMATH = 1, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
874         SHADERSTATICPARM_POSTPROCESS_USERVEC1 = 2, ///< postprocess uservec1 is enabled
875         SHADERSTATICPARM_POSTPROCESS_USERVEC2 = 3, ///< postprocess uservec2 is enabled
876         SHADERSTATICPARM_POSTPROCESS_USERVEC3 = 4, ///< postprocess uservec3 is enabled
877         SHADERSTATICPARM_POSTPROCESS_USERVEC4 = 5,  ///< postprocess uservec4 is enabled
878         SHADERSTATICPARM_VERTEXTEXTUREBLEND_USEBOTHALPHAS = 6, // use both alpha layers while blending materials, allows more advanced microblending
879         SHADERSTATICPARM_OFFSETMAPPING_USELOD = 7,  ///< LOD for offsetmapping
880 };
881 #define SHADERSTATICPARMS_COUNT 8
882
883 static const char *shaderstaticparmstrings_list[SHADERSTATICPARMS_COUNT];
884 static int shaderstaticparms_count = 0;
885
886 static unsigned int r_compileshader_staticparms[(SHADERSTATICPARMS_COUNT + 0x1F) >> 5] = {0};
887 #define R_COMPILESHADER_STATICPARM_ENABLE(p) r_compileshader_staticparms[(p) >> 5] |= (1 << ((p) & 0x1F))
888 qboolean R_CompileShader_CheckStaticParms(void)
889 {
890         static int r_compileshader_staticparms_save[1];
891         memcpy(r_compileshader_staticparms_save, r_compileshader_staticparms, sizeof(r_compileshader_staticparms));
892         memset(r_compileshader_staticparms, 0, sizeof(r_compileshader_staticparms));
893
894         // detect all
895         if (r_glsl_saturation_redcompensate.integer)
896                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_SATURATION_REDCOMPENSATE);
897         if (r_glsl_vertextextureblend_usebothalphas.integer)
898                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_VERTEXTEXTUREBLEND_USEBOTHALPHAS);
899         if (r_shadow_glossexact.integer)
900                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_EXACTSPECULARMATH);
901         if (r_glsl_postprocess.integer)
902         {
903                 if (r_glsl_postprocess_uservec1_enable.integer)
904                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC1);
905                 if (r_glsl_postprocess_uservec2_enable.integer)
906                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC2);
907                 if (r_glsl_postprocess_uservec3_enable.integer)
908                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC3);
909                 if (r_glsl_postprocess_uservec4_enable.integer)
910                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC4);
911         }
912         if (r_glsl_offsetmapping_lod.integer && r_glsl_offsetmapping_lod_distance.integer > 0)
913                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_OFFSETMAPPING_USELOD);
914         return memcmp(r_compileshader_staticparms, r_compileshader_staticparms_save, sizeof(r_compileshader_staticparms)) != 0;
915 }
916
917 #define R_COMPILESHADER_STATICPARM_EMIT(p, n) \
918         if(r_compileshader_staticparms[(p) >> 5] & (1 << ((p) & 0x1F))) \
919                 shaderstaticparmstrings_list[shaderstaticparms_count++] = "#define " n "\n"; \
920         else \
921                 shaderstaticparmstrings_list[shaderstaticparms_count++] = "\n"
922 void R_CompileShader_AddStaticParms(unsigned int mode, unsigned int permutation)
923 {
924         shaderstaticparms_count = 0;
925
926         // emit all
927         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_SATURATION_REDCOMPENSATE, "SATURATION_REDCOMPENSATE");
928         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_EXACTSPECULARMATH, "USEEXACTSPECULARMATH");
929         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC1, "USERVEC1");
930         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC2, "USERVEC2");
931         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC3, "USERVEC3");
932         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC4, "USERVEC4");
933         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_VERTEXTEXTUREBLEND_USEBOTHALPHAS, "USEBOTHALPHAS");
934         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_OFFSETMAPPING_USELOD, "USEOFFSETMAPPING_LOD");
935 }
936
937 /// information about each possible shader permutation
938 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
939 /// currently selected permutation
940 r_glsl_permutation_t *r_glsl_permutation;
941 /// storage for permutations linked in the hash table
942 memexpandablearray_t r_glsl_permutationarray;
943
944 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
945 {
946         //unsigned int hashdepth = 0;
947         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
948         r_glsl_permutation_t *p;
949         for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
950         {
951                 if (p->mode == mode && p->permutation == permutation)
952                 {
953                         //if (hashdepth > 10)
954                         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
955                         return p;
956                 }
957                 //hashdepth++;
958         }
959         p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
960         p->mode = mode;
961         p->permutation = permutation;
962         p->hashnext = r_glsl_permutationhash[mode][hashindex];
963         r_glsl_permutationhash[mode][hashindex] = p;
964         //if (hashdepth > 10)
965         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
966         return p;
967 }
968
969 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
970 {
971         char *shaderstring;
972         if (!filename || !filename[0])
973                 return NULL;
974         if (!strcmp(filename, "glsl/default.glsl"))
975         {
976                 if (!glslshaderstring)
977                 {
978                         glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
979                         if (glslshaderstring)
980                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
981                         else
982                                 glslshaderstring = (char *)builtinshaderstring;
983                 }
984                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
985                 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
986                 return shaderstring;
987         }
988         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
989         if (shaderstring)
990         {
991                 if (printfromdisknotice)
992                         Con_DPrintf("from disk %s... ", filename);
993                 return shaderstring;
994         }
995         return shaderstring;
996 }
997
998 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
999 {
1000         int i;
1001         int sampler;
1002         shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
1003         char *vertexstring, *geometrystring, *fragmentstring;
1004         char permutationname[256];
1005         int vertstrings_count = 0;
1006         int geomstrings_count = 0;
1007         int fragstrings_count = 0;
1008         const char *vertstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
1009         const char *geomstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
1010         const char *fragstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
1011
1012         if (p->compiled)
1013                 return;
1014         p->compiled = true;
1015         p->program = 0;
1016
1017         permutationname[0] = 0;
1018         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
1019         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
1020         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
1021
1022         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
1023
1024         // if we can do #version 130, we should (this improves quality of offset/reliefmapping thanks to textureGrad)
1025         if(vid.support.gl20shaders130)
1026         {
1027                 vertstrings_list[vertstrings_count++] = "#version 130\n";
1028                 geomstrings_list[geomstrings_count++] = "#version 130\n";
1029                 fragstrings_list[fragstrings_count++] = "#version 130\n";
1030                 vertstrings_list[vertstrings_count++] = "#define GLSL130\n";
1031                 geomstrings_list[geomstrings_count++] = "#define GLSL130\n";
1032                 fragstrings_list[fragstrings_count++] = "#define GLSL130\n";
1033         }
1034
1035         // the first pretext is which type of shader to compile as
1036         // (later these will all be bound together as a program object)
1037         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
1038         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
1039         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
1040
1041         // the second pretext is the mode (for example a light source)
1042         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
1043         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
1044         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
1045         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
1046
1047         // now add all the permutation pretexts
1048         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1049         {
1050                 if (permutation & (1<<i))
1051                 {
1052                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
1053                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
1054                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
1055                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
1056                 }
1057                 else
1058                 {
1059                         // keep line numbers correct
1060                         vertstrings_list[vertstrings_count++] = "\n";
1061                         geomstrings_list[geomstrings_count++] = "\n";
1062                         fragstrings_list[fragstrings_count++] = "\n";
1063                 }
1064         }
1065
1066         // add static parms
1067         R_CompileShader_AddStaticParms(mode, permutation);
1068         memcpy((char *)(vertstrings_list + vertstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1069         vertstrings_count += shaderstaticparms_count;
1070         memcpy((char *)(geomstrings_list + geomstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1071         geomstrings_count += shaderstaticparms_count;
1072         memcpy((char *)(fragstrings_list + fragstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1073         fragstrings_count += shaderstaticparms_count;
1074
1075         // now append the shader text itself
1076         vertstrings_list[vertstrings_count++] = vertexstring;
1077         geomstrings_list[geomstrings_count++] = geometrystring;
1078         fragstrings_list[fragstrings_count++] = fragmentstring;
1079
1080         // if any sources were NULL, clear the respective list
1081         if (!vertexstring)
1082                 vertstrings_count = 0;
1083         if (!geometrystring)
1084                 geomstrings_count = 0;
1085         if (!fragmentstring)
1086                 fragstrings_count = 0;
1087
1088         // compile the shader program
1089         if (vertstrings_count + geomstrings_count + fragstrings_count)
1090                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
1091         if (p->program)
1092         {
1093                 CHECKGLERROR
1094                 qglUseProgram(p->program);CHECKGLERROR
1095                 // look up all the uniform variable names we care about, so we don't
1096                 // have to look them up every time we set them
1097
1098                 p->loc_Texture_First              = qglGetUniformLocation(p->program, "Texture_First");
1099                 p->loc_Texture_Second             = qglGetUniformLocation(p->program, "Texture_Second");
1100                 p->loc_Texture_GammaRamps         = qglGetUniformLocation(p->program, "Texture_GammaRamps");
1101                 p->loc_Texture_Normal             = qglGetUniformLocation(p->program, "Texture_Normal");
1102                 p->loc_Texture_Color              = qglGetUniformLocation(p->program, "Texture_Color");
1103                 p->loc_Texture_Gloss              = qglGetUniformLocation(p->program, "Texture_Gloss");
1104                 p->loc_Texture_Glow               = qglGetUniformLocation(p->program, "Texture_Glow");
1105                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocation(p->program, "Texture_SecondaryNormal");
1106                 p->loc_Texture_SecondaryColor     = qglGetUniformLocation(p->program, "Texture_SecondaryColor");
1107                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocation(p->program, "Texture_SecondaryGloss");
1108                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocation(p->program, "Texture_SecondaryGlow");
1109                 p->loc_Texture_Pants              = qglGetUniformLocation(p->program, "Texture_Pants");
1110                 p->loc_Texture_Shirt              = qglGetUniformLocation(p->program, "Texture_Shirt");
1111                 p->loc_Texture_FogHeightTexture   = qglGetUniformLocation(p->program, "Texture_FogHeightTexture");
1112                 p->loc_Texture_FogMask            = qglGetUniformLocation(p->program, "Texture_FogMask");
1113                 p->loc_Texture_Lightmap           = qglGetUniformLocation(p->program, "Texture_Lightmap");
1114                 p->loc_Texture_Deluxemap          = qglGetUniformLocation(p->program, "Texture_Deluxemap");
1115                 p->loc_Texture_Attenuation        = qglGetUniformLocation(p->program, "Texture_Attenuation");
1116                 p->loc_Texture_Cube               = qglGetUniformLocation(p->program, "Texture_Cube");
1117                 p->loc_Texture_Refraction         = qglGetUniformLocation(p->program, "Texture_Refraction");
1118                 p->loc_Texture_Reflection         = qglGetUniformLocation(p->program, "Texture_Reflection");
1119                 p->loc_Texture_ShadowMap2D        = qglGetUniformLocation(p->program, "Texture_ShadowMap2D");
1120                 p->loc_Texture_CubeProjection     = qglGetUniformLocation(p->program, "Texture_CubeProjection");
1121                 p->loc_Texture_ScreenDepth        = qglGetUniformLocation(p->program, "Texture_ScreenDepth");
1122                 p->loc_Texture_ScreenNormalMap    = qglGetUniformLocation(p->program, "Texture_ScreenNormalMap");
1123                 p->loc_Texture_ScreenDiffuse      = qglGetUniformLocation(p->program, "Texture_ScreenDiffuse");
1124                 p->loc_Texture_ScreenSpecular     = qglGetUniformLocation(p->program, "Texture_ScreenSpecular");
1125                 p->loc_Texture_ReflectMask        = qglGetUniformLocation(p->program, "Texture_ReflectMask");
1126                 p->loc_Texture_ReflectCube        = qglGetUniformLocation(p->program, "Texture_ReflectCube");
1127                 p->loc_Texture_BounceGrid         = qglGetUniformLocation(p->program, "Texture_BounceGrid");
1128                 p->loc_Alpha                      = qglGetUniformLocation(p->program, "Alpha");
1129                 p->loc_BloomBlur_Parameters       = qglGetUniformLocation(p->program, "BloomBlur_Parameters");
1130                 p->loc_ClientTime                 = qglGetUniformLocation(p->program, "ClientTime");
1131                 p->loc_Color_Ambient              = qglGetUniformLocation(p->program, "Color_Ambient");
1132                 p->loc_Color_Diffuse              = qglGetUniformLocation(p->program, "Color_Diffuse");
1133                 p->loc_Color_Specular             = qglGetUniformLocation(p->program, "Color_Specular");
1134                 p->loc_Color_Glow                 = qglGetUniformLocation(p->program, "Color_Glow");
1135                 p->loc_Color_Pants                = qglGetUniformLocation(p->program, "Color_Pants");
1136                 p->loc_Color_Shirt                = qglGetUniformLocation(p->program, "Color_Shirt");
1137                 p->loc_DeferredColor_Ambient      = qglGetUniformLocation(p->program, "DeferredColor_Ambient");
1138                 p->loc_DeferredColor_Diffuse      = qglGetUniformLocation(p->program, "DeferredColor_Diffuse");
1139                 p->loc_DeferredColor_Specular     = qglGetUniformLocation(p->program, "DeferredColor_Specular");
1140                 p->loc_DeferredMod_Diffuse        = qglGetUniformLocation(p->program, "DeferredMod_Diffuse");
1141                 p->loc_DeferredMod_Specular       = qglGetUniformLocation(p->program, "DeferredMod_Specular");
1142                 p->loc_DistortScaleRefractReflect = qglGetUniformLocation(p->program, "DistortScaleRefractReflect");
1143                 p->loc_EyePosition                = qglGetUniformLocation(p->program, "EyePosition");
1144                 p->loc_FogColor                   = qglGetUniformLocation(p->program, "FogColor");
1145                 p->loc_FogHeightFade              = qglGetUniformLocation(p->program, "FogHeightFade");
1146                 p->loc_FogPlane                   = qglGetUniformLocation(p->program, "FogPlane");
1147                 p->loc_FogPlaneViewDist           = qglGetUniformLocation(p->program, "FogPlaneViewDist");
1148                 p->loc_FogRangeRecip              = qglGetUniformLocation(p->program, "FogRangeRecip");
1149                 p->loc_LightColor                 = qglGetUniformLocation(p->program, "LightColor");
1150                 p->loc_LightDir                   = qglGetUniformLocation(p->program, "LightDir");
1151                 p->loc_LightPosition              = qglGetUniformLocation(p->program, "LightPosition");
1152                 p->loc_OffsetMapping_ScaleSteps   = qglGetUniformLocation(p->program, "OffsetMapping_ScaleSteps");
1153                 p->loc_OffsetMapping_LodDistance  = qglGetUniformLocation(p->program, "OffsetMapping_LodDistance");
1154                 p->loc_OffsetMapping_Bias         = qglGetUniformLocation(p->program, "OffsetMapping_Bias");
1155                 p->loc_PixelSize                  = qglGetUniformLocation(p->program, "PixelSize");
1156                 p->loc_ReflectColor               = qglGetUniformLocation(p->program, "ReflectColor");
1157                 p->loc_ReflectFactor              = qglGetUniformLocation(p->program, "ReflectFactor");
1158                 p->loc_ReflectOffset              = qglGetUniformLocation(p->program, "ReflectOffset");
1159                 p->loc_RefractColor               = qglGetUniformLocation(p->program, "RefractColor");
1160                 p->loc_Saturation                 = qglGetUniformLocation(p->program, "Saturation");
1161                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocation(p->program, "ScreenCenterRefractReflect");
1162                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocation(p->program, "ScreenScaleRefractReflect");
1163                 p->loc_ScreenToDepth              = qglGetUniformLocation(p->program, "ScreenToDepth");
1164                 p->loc_ShadowMap_Parameters       = qglGetUniformLocation(p->program, "ShadowMap_Parameters");
1165                 p->loc_ShadowMap_TextureScale     = qglGetUniformLocation(p->program, "ShadowMap_TextureScale");
1166                 p->loc_SpecularPower              = qglGetUniformLocation(p->program, "SpecularPower");
1167                 p->loc_UserVec1                   = qglGetUniformLocation(p->program, "UserVec1");
1168                 p->loc_UserVec2                   = qglGetUniformLocation(p->program, "UserVec2");
1169                 p->loc_UserVec3                   = qglGetUniformLocation(p->program, "UserVec3");
1170                 p->loc_UserVec4                   = qglGetUniformLocation(p->program, "UserVec4");
1171                 p->loc_ViewTintColor              = qglGetUniformLocation(p->program, "ViewTintColor");
1172                 p->loc_ViewToLight                = qglGetUniformLocation(p->program, "ViewToLight");
1173                 p->loc_ModelToLight               = qglGetUniformLocation(p->program, "ModelToLight");
1174                 p->loc_TexMatrix                  = qglGetUniformLocation(p->program, "TexMatrix");
1175                 p->loc_BackgroundTexMatrix        = qglGetUniformLocation(p->program, "BackgroundTexMatrix");
1176                 p->loc_ModelViewMatrix            = qglGetUniformLocation(p->program, "ModelViewMatrix");
1177                 p->loc_ModelViewProjectionMatrix  = qglGetUniformLocation(p->program, "ModelViewProjectionMatrix");
1178                 p->loc_PixelToScreenTexCoord      = qglGetUniformLocation(p->program, "PixelToScreenTexCoord");
1179                 p->loc_ModelToReflectCube         = qglGetUniformLocation(p->program, "ModelToReflectCube");
1180                 p->loc_ShadowMapMatrix            = qglGetUniformLocation(p->program, "ShadowMapMatrix");
1181                 p->loc_BloomColorSubtract         = qglGetUniformLocation(p->program, "BloomColorSubtract");
1182                 p->loc_NormalmapScrollBlend       = qglGetUniformLocation(p->program, "NormalmapScrollBlend");
1183                 p->loc_BounceGridMatrix           = qglGetUniformLocation(p->program, "BounceGridMatrix");
1184                 p->loc_BounceGridIntensity        = qglGetUniformLocation(p->program, "BounceGridIntensity");
1185                 // initialize the samplers to refer to the texture units we use
1186                 p->tex_Texture_First = -1;
1187                 p->tex_Texture_Second = -1;
1188                 p->tex_Texture_GammaRamps = -1;
1189                 p->tex_Texture_Normal = -1;
1190                 p->tex_Texture_Color = -1;
1191                 p->tex_Texture_Gloss = -1;
1192                 p->tex_Texture_Glow = -1;
1193                 p->tex_Texture_SecondaryNormal = -1;
1194                 p->tex_Texture_SecondaryColor = -1;
1195                 p->tex_Texture_SecondaryGloss = -1;
1196                 p->tex_Texture_SecondaryGlow = -1;
1197                 p->tex_Texture_Pants = -1;
1198                 p->tex_Texture_Shirt = -1;
1199                 p->tex_Texture_FogHeightTexture = -1;
1200                 p->tex_Texture_FogMask = -1;
1201                 p->tex_Texture_Lightmap = -1;
1202                 p->tex_Texture_Deluxemap = -1;
1203                 p->tex_Texture_Attenuation = -1;
1204                 p->tex_Texture_Cube = -1;
1205                 p->tex_Texture_Refraction = -1;
1206                 p->tex_Texture_Reflection = -1;
1207                 p->tex_Texture_ShadowMap2D = -1;
1208                 p->tex_Texture_CubeProjection = -1;
1209                 p->tex_Texture_ScreenDepth = -1;
1210                 p->tex_Texture_ScreenNormalMap = -1;
1211                 p->tex_Texture_ScreenDiffuse = -1;
1212                 p->tex_Texture_ScreenSpecular = -1;
1213                 p->tex_Texture_ReflectMask = -1;
1214                 p->tex_Texture_ReflectCube = -1;
1215                 p->tex_Texture_BounceGrid = -1;
1216                 sampler = 0;
1217                 if (p->loc_Texture_First           >= 0) {p->tex_Texture_First            = sampler;qglUniform1i(p->loc_Texture_First           , sampler);sampler++;}
1218                 if (p->loc_Texture_Second          >= 0) {p->tex_Texture_Second           = sampler;qglUniform1i(p->loc_Texture_Second          , sampler);sampler++;}
1219                 if (p->loc_Texture_GammaRamps      >= 0) {p->tex_Texture_GammaRamps       = sampler;qglUniform1i(p->loc_Texture_GammaRamps      , sampler);sampler++;}
1220                 if (p->loc_Texture_Normal          >= 0) {p->tex_Texture_Normal           = sampler;qglUniform1i(p->loc_Texture_Normal          , sampler);sampler++;}
1221                 if (p->loc_Texture_Color           >= 0) {p->tex_Texture_Color            = sampler;qglUniform1i(p->loc_Texture_Color           , sampler);sampler++;}
1222                 if (p->loc_Texture_Gloss           >= 0) {p->tex_Texture_Gloss            = sampler;qglUniform1i(p->loc_Texture_Gloss           , sampler);sampler++;}
1223                 if (p->loc_Texture_Glow            >= 0) {p->tex_Texture_Glow             = sampler;qglUniform1i(p->loc_Texture_Glow            , sampler);sampler++;}
1224                 if (p->loc_Texture_SecondaryNormal >= 0) {p->tex_Texture_SecondaryNormal  = sampler;qglUniform1i(p->loc_Texture_SecondaryNormal , sampler);sampler++;}
1225                 if (p->loc_Texture_SecondaryColor  >= 0) {p->tex_Texture_SecondaryColor   = sampler;qglUniform1i(p->loc_Texture_SecondaryColor  , sampler);sampler++;}
1226                 if (p->loc_Texture_SecondaryGloss  >= 0) {p->tex_Texture_SecondaryGloss   = sampler;qglUniform1i(p->loc_Texture_SecondaryGloss  , sampler);sampler++;}
1227                 if (p->loc_Texture_SecondaryGlow   >= 0) {p->tex_Texture_SecondaryGlow    = sampler;qglUniform1i(p->loc_Texture_SecondaryGlow   , sampler);sampler++;}
1228                 if (p->loc_Texture_Pants           >= 0) {p->tex_Texture_Pants            = sampler;qglUniform1i(p->loc_Texture_Pants           , sampler);sampler++;}
1229                 if (p->loc_Texture_Shirt           >= 0) {p->tex_Texture_Shirt            = sampler;qglUniform1i(p->loc_Texture_Shirt           , sampler);sampler++;}
1230                 if (p->loc_Texture_FogHeightTexture>= 0) {p->tex_Texture_FogHeightTexture = sampler;qglUniform1i(p->loc_Texture_FogHeightTexture, sampler);sampler++;}
1231                 if (p->loc_Texture_FogMask         >= 0) {p->tex_Texture_FogMask          = sampler;qglUniform1i(p->loc_Texture_FogMask         , sampler);sampler++;}
1232                 if (p->loc_Texture_Lightmap        >= 0) {p->tex_Texture_Lightmap         = sampler;qglUniform1i(p->loc_Texture_Lightmap        , sampler);sampler++;}
1233                 if (p->loc_Texture_Deluxemap       >= 0) {p->tex_Texture_Deluxemap        = sampler;qglUniform1i(p->loc_Texture_Deluxemap       , sampler);sampler++;}
1234                 if (p->loc_Texture_Attenuation     >= 0) {p->tex_Texture_Attenuation      = sampler;qglUniform1i(p->loc_Texture_Attenuation     , sampler);sampler++;}
1235                 if (p->loc_Texture_Cube            >= 0) {p->tex_Texture_Cube             = sampler;qglUniform1i(p->loc_Texture_Cube            , sampler);sampler++;}
1236                 if (p->loc_Texture_Refraction      >= 0) {p->tex_Texture_Refraction       = sampler;qglUniform1i(p->loc_Texture_Refraction      , sampler);sampler++;}
1237                 if (p->loc_Texture_Reflection      >= 0) {p->tex_Texture_Reflection       = sampler;qglUniform1i(p->loc_Texture_Reflection      , sampler);sampler++;}
1238                 if (p->loc_Texture_ShadowMap2D     >= 0) {p->tex_Texture_ShadowMap2D      = sampler;qglUniform1i(p->loc_Texture_ShadowMap2D     , sampler);sampler++;}
1239                 if (p->loc_Texture_CubeProjection  >= 0) {p->tex_Texture_CubeProjection   = sampler;qglUniform1i(p->loc_Texture_CubeProjection  , sampler);sampler++;}
1240                 if (p->loc_Texture_ScreenDepth     >= 0) {p->tex_Texture_ScreenDepth      = sampler;qglUniform1i(p->loc_Texture_ScreenDepth     , sampler);sampler++;}
1241                 if (p->loc_Texture_ScreenNormalMap >= 0) {p->tex_Texture_ScreenNormalMap  = sampler;qglUniform1i(p->loc_Texture_ScreenNormalMap , sampler);sampler++;}
1242                 if (p->loc_Texture_ScreenDiffuse   >= 0) {p->tex_Texture_ScreenDiffuse    = sampler;qglUniform1i(p->loc_Texture_ScreenDiffuse   , sampler);sampler++;}
1243                 if (p->loc_Texture_ScreenSpecular  >= 0) {p->tex_Texture_ScreenSpecular   = sampler;qglUniform1i(p->loc_Texture_ScreenSpecular  , sampler);sampler++;}
1244                 if (p->loc_Texture_ReflectMask     >= 0) {p->tex_Texture_ReflectMask      = sampler;qglUniform1i(p->loc_Texture_ReflectMask     , sampler);sampler++;}
1245                 if (p->loc_Texture_ReflectCube     >= 0) {p->tex_Texture_ReflectCube      = sampler;qglUniform1i(p->loc_Texture_ReflectCube     , sampler);sampler++;}
1246                 if (p->loc_Texture_BounceGrid      >= 0) {p->tex_Texture_BounceGrid       = sampler;qglUniform1i(p->loc_Texture_BounceGrid      , sampler);sampler++;}
1247                 CHECKGLERROR
1248                 Con_DPrintf("^5GLSL shader %s compiled (%i textures).\n", permutationname, sampler);
1249         }
1250         else
1251                 Con_Printf("^1GLSL shader %s failed!  some features may not work properly.\n", permutationname);
1252
1253         // free the strings
1254         if (vertexstring)
1255                 Mem_Free(vertexstring);
1256         if (geometrystring)
1257                 Mem_Free(geometrystring);
1258         if (fragmentstring)
1259                 Mem_Free(fragmentstring);
1260 }
1261
1262 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
1263 {
1264         r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
1265         if (r_glsl_permutation != perm)
1266         {
1267                 r_glsl_permutation = perm;
1268                 if (!r_glsl_permutation->program)
1269                 {
1270                         if (!r_glsl_permutation->compiled)
1271                                 R_GLSL_CompilePermutation(perm, mode, permutation);
1272                         if (!r_glsl_permutation->program)
1273                         {
1274                                 // remove features until we find a valid permutation
1275                                 int i;
1276                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1277                                 {
1278                                         // reduce i more quickly whenever it would not remove any bits
1279                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
1280                                         if (!(permutation & j))
1281                                                 continue;
1282                                         permutation -= j;
1283                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
1284                                         if (!r_glsl_permutation->compiled)
1285                                                 R_GLSL_CompilePermutation(perm, mode, permutation);
1286                                         if (r_glsl_permutation->program)
1287                                                 break;
1288                                 }
1289                                 if (i >= SHADERPERMUTATION_COUNT)
1290                                 {
1291                                         //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
1292                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
1293                                         qglUseProgram(0);CHECKGLERROR
1294                                         return; // no bit left to clear, entire mode is broken
1295                                 }
1296                         }
1297                 }
1298                 CHECKGLERROR
1299                 qglUseProgram(r_glsl_permutation->program);CHECKGLERROR
1300         }
1301         if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
1302         if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
1303         if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1f(r_glsl_permutation->loc_ClientTime, cl.time);
1304 }
1305
1306 #ifdef SUPPORTD3D
1307
1308 #ifdef SUPPORTD3D
1309 #include <d3d9.h>
1310 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
1311 extern D3DCAPS9 vid_d3d9caps;
1312 #endif
1313
1314 struct r_hlsl_permutation_s;
1315 typedef struct r_hlsl_permutation_s
1316 {
1317         /// hash lookup data
1318         struct r_hlsl_permutation_s *hashnext;
1319         unsigned int mode;
1320         unsigned int permutation;
1321
1322         /// indicates if we have tried compiling this permutation already
1323         qboolean compiled;
1324         /// NULL if compilation failed
1325         IDirect3DVertexShader9 *vertexshader;
1326         IDirect3DPixelShader9 *pixelshader;
1327 }
1328 r_hlsl_permutation_t;
1329
1330 typedef enum D3DVSREGISTER_e
1331 {
1332         D3DVSREGISTER_TexMatrix = 0, // float4x4
1333         D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
1334         D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
1335         D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
1336         D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
1337         D3DVSREGISTER_ModelToLight = 20, // float4x4
1338         D3DVSREGISTER_EyePosition = 24,
1339         D3DVSREGISTER_FogPlane = 25,
1340         D3DVSREGISTER_LightDir = 26,
1341         D3DVSREGISTER_LightPosition = 27,
1342 }
1343 D3DVSREGISTER_t;
1344
1345 typedef enum D3DPSREGISTER_e
1346 {
1347         D3DPSREGISTER_Alpha = 0,
1348         D3DPSREGISTER_BloomBlur_Parameters = 1,
1349         D3DPSREGISTER_ClientTime = 2,
1350         D3DPSREGISTER_Color_Ambient = 3,
1351         D3DPSREGISTER_Color_Diffuse = 4,
1352         D3DPSREGISTER_Color_Specular = 5,
1353         D3DPSREGISTER_Color_Glow = 6,
1354         D3DPSREGISTER_Color_Pants = 7,
1355         D3DPSREGISTER_Color_Shirt = 8,
1356         D3DPSREGISTER_DeferredColor_Ambient = 9,
1357         D3DPSREGISTER_DeferredColor_Diffuse = 10,
1358         D3DPSREGISTER_DeferredColor_Specular = 11,
1359         D3DPSREGISTER_DeferredMod_Diffuse = 12,
1360         D3DPSREGISTER_DeferredMod_Specular = 13,
1361         D3DPSREGISTER_DistortScaleRefractReflect = 14,
1362         D3DPSREGISTER_EyePosition = 15, // unused
1363         D3DPSREGISTER_FogColor = 16,
1364         D3DPSREGISTER_FogHeightFade = 17,
1365         D3DPSREGISTER_FogPlane = 18,
1366         D3DPSREGISTER_FogPlaneViewDist = 19,
1367         D3DPSREGISTER_FogRangeRecip = 20,
1368         D3DPSREGISTER_LightColor = 21,
1369         D3DPSREGISTER_LightDir = 22, // unused
1370         D3DPSREGISTER_LightPosition = 23,
1371         D3DPSREGISTER_OffsetMapping_ScaleSteps = 24,
1372         D3DPSREGISTER_PixelSize = 25,
1373         D3DPSREGISTER_ReflectColor = 26,
1374         D3DPSREGISTER_ReflectFactor = 27,
1375         D3DPSREGISTER_ReflectOffset = 28,
1376         D3DPSREGISTER_RefractColor = 29,
1377         D3DPSREGISTER_Saturation = 30,
1378         D3DPSREGISTER_ScreenCenterRefractReflect = 31,
1379         D3DPSREGISTER_ScreenScaleRefractReflect = 32,
1380         D3DPSREGISTER_ScreenToDepth = 33,
1381         D3DPSREGISTER_ShadowMap_Parameters = 34,
1382         D3DPSREGISTER_ShadowMap_TextureScale = 35,
1383         D3DPSREGISTER_SpecularPower = 36,
1384         D3DPSREGISTER_UserVec1 = 37,
1385         D3DPSREGISTER_UserVec2 = 38,
1386         D3DPSREGISTER_UserVec3 = 39,
1387         D3DPSREGISTER_UserVec4 = 40,
1388         D3DPSREGISTER_ViewTintColor = 41,
1389         D3DPSREGISTER_PixelToScreenTexCoord = 42,
1390         D3DPSREGISTER_BloomColorSubtract = 43,
1391         D3DPSREGISTER_ViewToLight = 44, // float4x4
1392         D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
1393         D3DPSREGISTER_NormalmapScrollBlend = 52,
1394         D3DPSREGISTER_OffsetMapping_LodDistance = 53,
1395         D3DPSREGISTER_OffsetMapping_Bias = 54,
1396         // next at 54
1397 }
1398 D3DPSREGISTER_t;
1399
1400 /// information about each possible shader permutation
1401 r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
1402 /// currently selected permutation
1403 r_hlsl_permutation_t *r_hlsl_permutation;
1404 /// storage for permutations linked in the hash table
1405 memexpandablearray_t r_hlsl_permutationarray;
1406
1407 static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
1408 {
1409         //unsigned int hashdepth = 0;
1410         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
1411         r_hlsl_permutation_t *p;
1412         for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
1413         {
1414                 if (p->mode == mode && p->permutation == permutation)
1415                 {
1416                         //if (hashdepth > 10)
1417                         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
1418                         return p;
1419                 }
1420                 //hashdepth++;
1421         }
1422         p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
1423         p->mode = mode;
1424         p->permutation = permutation;
1425         p->hashnext = r_hlsl_permutationhash[mode][hashindex];
1426         r_hlsl_permutationhash[mode][hashindex] = p;
1427         //if (hashdepth > 10)
1428         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
1429         return p;
1430 }
1431
1432 static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
1433 {
1434         char *shaderstring;
1435         if (!filename || !filename[0])
1436                 return NULL;
1437         if (!strcmp(filename, "hlsl/default.hlsl"))
1438         {
1439                 if (!hlslshaderstring)
1440                 {
1441                         hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
1442                         if (hlslshaderstring)
1443                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
1444                         else
1445                                 hlslshaderstring = (char *)builtinhlslshaderstring;
1446                 }
1447                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
1448                 memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
1449                 return shaderstring;
1450         }
1451         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
1452         if (shaderstring)
1453         {
1454                 if (printfromdisknotice)
1455                         Con_DPrintf("from disk %s... ", filename);
1456                 return shaderstring;
1457         }
1458         return shaderstring;
1459 }
1460
1461 #include <d3dx9.h>
1462 //#include <d3dx9shader.h>
1463 //#include <d3dx9mesh.h>
1464
1465 static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
1466 {
1467         DWORD *vsbin = NULL;
1468         DWORD *psbin = NULL;
1469         fs_offset_t vsbinsize;
1470         fs_offset_t psbinsize;
1471 //      IDirect3DVertexShader9 *vs = NULL;
1472 //      IDirect3DPixelShader9 *ps = NULL;
1473         ID3DXBuffer *vslog = NULL;
1474         ID3DXBuffer *vsbuffer = NULL;
1475         ID3DXConstantTable *vsconstanttable = NULL;
1476         ID3DXBuffer *pslog = NULL;
1477         ID3DXBuffer *psbuffer = NULL;
1478         ID3DXConstantTable *psconstanttable = NULL;
1479         int vsresult = 0;
1480         int psresult = 0;
1481         char temp[MAX_INPUTLINE];
1482         const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
1483         qboolean debugshader = gl_paranoid.integer != 0;
1484         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
1485         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
1486         if (!debugshader)
1487         {
1488                 vsbin = (DWORD *)FS_LoadFile(va("%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
1489                 psbin = (DWORD *)FS_LoadFile(va("%s.psbin", cachename), r_main_mempool, true, &psbinsize);
1490         }
1491         if ((!vsbin && vertstring) || (!psbin && fragstring))
1492         {
1493                 const char* dllnames_d3dx9 [] =
1494                 {
1495                         "d3dx9_43.dll",
1496                         "d3dx9_42.dll",
1497                         "d3dx9_41.dll",
1498                         "d3dx9_40.dll",
1499                         "d3dx9_39.dll",
1500                         "d3dx9_38.dll",
1501                         "d3dx9_37.dll",
1502                         "d3dx9_36.dll",
1503                         "d3dx9_35.dll",
1504                         "d3dx9_34.dll",
1505                         "d3dx9_33.dll",
1506                         "d3dx9_32.dll",
1507                         "d3dx9_31.dll",
1508                         "d3dx9_30.dll",
1509                         "d3dx9_29.dll",
1510                         "d3dx9_28.dll",
1511                         "d3dx9_27.dll",
1512                         "d3dx9_26.dll",
1513                         "d3dx9_25.dll",
1514                         "d3dx9_24.dll",
1515                         NULL
1516                 };
1517                 dllhandle_t d3dx9_dll = NULL;
1518                 HRESULT (WINAPI *qD3DXCompileShaderFromFileA)(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
1519                 HRESULT (WINAPI *qD3DXPreprocessShader)(LPCSTR pSrcData, UINT SrcDataSize, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPD3DXBUFFER* ppShaderText, LPD3DXBUFFER* ppErrorMsgs);
1520                 HRESULT (WINAPI *qD3DXCompileShader)(LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
1521                 dllfunction_t d3dx9_dllfuncs[] =
1522                 {
1523                         {"D3DXCompileShaderFromFileA",  (void **) &qD3DXCompileShaderFromFileA},
1524                         {"D3DXPreprocessShader",                (void **) &qD3DXPreprocessShader},
1525                         {"D3DXCompileShader",                   (void **) &qD3DXCompileShader},
1526                         {NULL, NULL}
1527                 };
1528                 if (Sys_LoadLibrary(dllnames_d3dx9, &d3dx9_dll, d3dx9_dllfuncs))
1529                 {
1530                         DWORD shaderflags = 0;
1531                         if (debugshader)
1532                                 shaderflags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION;
1533                         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
1534                         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
1535                         if (vertstring && vertstring[0])
1536                         {
1537                                 if (debugshader)
1538                                 {
1539 //                                      vsresult = qD3DXPreprocessShader(vertstring, strlen(vertstring), NULL, NULL, &vsbuffer, &vslog);
1540 //                                      FS_WriteFile(va("%s_vs.fx", cachename), vsbuffer->GetBufferPointer(), vsbuffer->GetBufferSize());
1541                                         FS_WriteFile(va("%s_vs.fx", cachename), vertstring, strlen(vertstring));
1542                                         vsresult = qD3DXCompileShaderFromFileA(va("%s/%s_vs.fx", fs_gamedir, cachename), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
1543                                 }
1544                                 else
1545                                         vsresult = qD3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
1546                                 if (vsbuffer)
1547                                 {
1548                                         vsbinsize = vsbuffer->GetBufferSize();
1549                                         vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
1550                                         memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
1551                                         vsbuffer->Release();
1552                                 }
1553                                 if (vslog)
1554                                 {
1555                                         strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
1556                                         Con_DPrintf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
1557                                         vslog->Release();
1558                                 }
1559                         }
1560                         if (fragstring && fragstring[0])
1561                         {
1562                                 if (debugshader)
1563                                 {
1564 //                                      psresult = qD3DXPreprocessShader(fragstring, strlen(fragstring), NULL, NULL, &psbuffer, &pslog);
1565 //                                      FS_WriteFile(va("%s_ps.fx", cachename), psbuffer->GetBufferPointer(), psbuffer->GetBufferSize());
1566                                         FS_WriteFile(va("%s_ps.fx", cachename), fragstring, strlen(fragstring));
1567                                         psresult = qD3DXCompileShaderFromFileA(va("%s/%s_ps.fx", fs_gamedir, cachename), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
1568                                 }
1569                                 else
1570                                         psresult = qD3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
1571                                 if (psbuffer)
1572                                 {
1573                                         psbinsize = psbuffer->GetBufferSize();
1574                                         psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
1575                                         memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
1576                                         psbuffer->Release();
1577                                 }
1578                                 if (pslog)
1579                                 {
1580                                         strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
1581                                         Con_DPrintf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
1582                                         pslog->Release();
1583                                 }
1584                         }
1585                         Sys_UnloadLibrary(&d3dx9_dll);
1586                 }
1587                 else
1588                         Con_DPrintf("Unable to compile shader - D3DXCompileShader function not found\n");
1589         }
1590         if (vsbin && psbin)
1591         {
1592                 vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
1593                 if (FAILED(vsresult))
1594                         Con_DPrintf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
1595                 psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
1596                 if (FAILED(psresult))
1597                         Con_DPrintf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
1598         }
1599         // free the shader data
1600         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
1601         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
1602 }
1603
1604 static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
1605 {
1606         int i;
1607         shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
1608         int vertstring_length = 0;
1609         int geomstring_length = 0;
1610         int fragstring_length = 0;
1611         char *t;
1612         char *vertexstring, *geometrystring, *fragmentstring;
1613         char *vertstring, *geomstring, *fragstring;
1614         char permutationname[256];
1615         char cachename[256];
1616         int vertstrings_count = 0;
1617         int geomstrings_count = 0;
1618         int fragstrings_count = 0;
1619         const char *vertstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
1620         const char *geomstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
1621         const char *fragstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
1622
1623         if (p->compiled)
1624                 return;
1625         p->compiled = true;
1626         p->vertexshader = NULL;
1627         p->pixelshader = NULL;
1628
1629         permutationname[0] = 0;
1630         cachename[0] = 0;
1631         vertexstring   = R_HLSL_GetText(modeinfo->vertexfilename, true);
1632         geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
1633         fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
1634
1635         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
1636         strlcat(cachename, "hlsl/", sizeof(cachename));
1637
1638         // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
1639         vertstrings_count = 0;
1640         geomstrings_count = 0;
1641         fragstrings_count = 0;
1642         vertstrings_list[vertstrings_count++] = "#define HLSL\n";
1643         geomstrings_list[geomstrings_count++] = "#define HLSL\n";
1644         fragstrings_list[fragstrings_count++] = "#define HLSL\n";
1645
1646         // the first pretext is which type of shader to compile as
1647         // (later these will all be bound together as a program object)
1648         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
1649         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
1650         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
1651
1652         // the second pretext is the mode (for example a light source)
1653         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
1654         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
1655         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
1656         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
1657         strlcat(cachename, modeinfo->name, sizeof(cachename));
1658
1659         // now add all the permutation pretexts
1660         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1661         {
1662                 if (permutation & (1<<i))
1663                 {
1664                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
1665                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
1666                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
1667                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
1668                         strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
1669                 }
1670                 else
1671                 {
1672                         // keep line numbers correct
1673                         vertstrings_list[vertstrings_count++] = "\n";
1674                         geomstrings_list[geomstrings_count++] = "\n";
1675                         fragstrings_list[fragstrings_count++] = "\n";
1676                 }
1677         }
1678
1679         // add static parms
1680         R_CompileShader_AddStaticParms(mode, permutation);
1681         memcpy(vertstrings_list + vertstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1682         vertstrings_count += shaderstaticparms_count;
1683         memcpy(geomstrings_list + geomstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1684         geomstrings_count += shaderstaticparms_count;
1685         memcpy(fragstrings_list + fragstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1686         fragstrings_count += shaderstaticparms_count;
1687
1688         // replace spaces in the cachename with _ characters
1689         for (i = 0;cachename[i];i++)
1690                 if (cachename[i] == ' ')
1691                         cachename[i] = '_';
1692
1693         // now append the shader text itself
1694         vertstrings_list[vertstrings_count++] = vertexstring;
1695         geomstrings_list[geomstrings_count++] = geometrystring;
1696         fragstrings_list[fragstrings_count++] = fragmentstring;
1697
1698         // if any sources were NULL, clear the respective list
1699         if (!vertexstring)
1700                 vertstrings_count = 0;
1701         if (!geometrystring)
1702                 geomstrings_count = 0;
1703         if (!fragmentstring)
1704                 fragstrings_count = 0;
1705
1706         vertstring_length = 0;
1707         for (i = 0;i < vertstrings_count;i++)
1708                 vertstring_length += strlen(vertstrings_list[i]);
1709         vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
1710         for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
1711                 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
1712
1713         geomstring_length = 0;
1714         for (i = 0;i < geomstrings_count;i++)
1715                 geomstring_length += strlen(geomstrings_list[i]);
1716         geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
1717         for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
1718                 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
1719
1720         fragstring_length = 0;
1721         for (i = 0;i < fragstrings_count;i++)
1722                 fragstring_length += strlen(fragstrings_list[i]);
1723         fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
1724         for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
1725                 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
1726
1727         // try to load the cached shader, or generate one
1728         R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
1729
1730         if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
1731                 Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
1732         else
1733                 Con_Printf("^1HLSL shader %s failed!  some features may not work properly.\n", permutationname);
1734
1735         // free the strings
1736         if (vertstring)
1737                 Mem_Free(vertstring);
1738         if (geomstring)
1739                 Mem_Free(geomstring);
1740         if (fragstring)
1741                 Mem_Free(fragstring);
1742         if (vertexstring)
1743                 Mem_Free(vertexstring);
1744         if (geometrystring)
1745                 Mem_Free(geometrystring);
1746         if (fragmentstring)
1747                 Mem_Free(fragmentstring);
1748 }
1749
1750 static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
1751 static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
1752 static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1753 static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1754 static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1755 static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1756
1757 static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
1758 static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
1759 static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1760 static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1761 static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1762 static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1763
1764 void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
1765 {
1766         r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
1767         if (r_hlsl_permutation != perm)
1768         {
1769                 r_hlsl_permutation = perm;
1770                 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
1771                 {
1772                         if (!r_hlsl_permutation->compiled)
1773                                 R_HLSL_CompilePermutation(perm, mode, permutation);
1774                         if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
1775                         {
1776                                 // remove features until we find a valid permutation
1777                                 int i;
1778                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1779                                 {
1780                                         // reduce i more quickly whenever it would not remove any bits
1781                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
1782                                         if (!(permutation & j))
1783                                                 continue;
1784                                         permutation -= j;
1785                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
1786                                         if (!r_hlsl_permutation->compiled)
1787                                                 R_HLSL_CompilePermutation(perm, mode, permutation);
1788                                         if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
1789                                                 break;
1790                                 }
1791                                 if (i >= SHADERPERMUTATION_COUNT)
1792                                 {
1793                                         //Con_Printf("Could not find a working HLSL shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
1794                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
1795                                         return; // no bit left to clear, entire mode is broken
1796                                 }
1797                         }
1798                 }
1799                 IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
1800                 IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
1801         }
1802         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
1803         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
1804         hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
1805 }
1806 #endif
1807
1808 void R_SetupShader_SetPermutationSoft(unsigned int mode, unsigned int permutation)
1809 {
1810         DPSOFTRAST_SetShader(mode, permutation, r_shadow_glossexact.integer);
1811         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1, 1, false, gl_modelviewprojection16f);
1812         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewMatrixM1, 1, false, gl_modelview16f);
1813         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ClientTime, cl.time);
1814 }
1815
1816 void R_GLSL_Restart_f(void)
1817 {
1818         unsigned int i, limit;
1819         if (glslshaderstring && glslshaderstring != builtinshaderstring)
1820                 Mem_Free(glslshaderstring);
1821         glslshaderstring = NULL;
1822         if (hlslshaderstring && hlslshaderstring != builtinhlslshaderstring)
1823                 Mem_Free(hlslshaderstring);
1824         hlslshaderstring = NULL;
1825         switch(vid.renderpath)
1826         {
1827         case RENDERPATH_D3D9:
1828 #ifdef SUPPORTD3D
1829                 {
1830                         r_hlsl_permutation_t *p;
1831                         r_hlsl_permutation = NULL;
1832                         limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
1833                         for (i = 0;i < limit;i++)
1834                         {
1835                                 if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
1836                                 {
1837                                         if (p->vertexshader)
1838                                                 IDirect3DVertexShader9_Release(p->vertexshader);
1839                                         if (p->pixelshader)
1840                                                 IDirect3DPixelShader9_Release(p->pixelshader);
1841                                         Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
1842                                 }
1843                         }
1844                         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
1845                 }
1846 #endif
1847                 break;
1848         case RENDERPATH_D3D10:
1849                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1850                 break;
1851         case RENDERPATH_D3D11:
1852                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1853                 break;
1854         case RENDERPATH_GL20:
1855         case RENDERPATH_GLES2:
1856                 {
1857                         r_glsl_permutation_t *p;
1858                         r_glsl_permutation = NULL;
1859                         limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
1860                         for (i = 0;i < limit;i++)
1861                         {
1862                                 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
1863                                 {
1864                                         GL_Backend_FreeProgram(p->program);
1865                                         Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
1866                                 }
1867                         }
1868                         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
1869                 }
1870                 break;
1871         case RENDERPATH_GL11:
1872         case RENDERPATH_GL13:
1873         case RENDERPATH_GLES1:
1874                 break;
1875         case RENDERPATH_SOFT:
1876                 break;
1877         }
1878 }
1879
1880 void R_GLSL_DumpShader_f(void)
1881 {
1882         int i;
1883         qfile_t *file;
1884
1885         file = FS_OpenRealFile("glsl/default.glsl", "w", false);
1886         if (file)
1887         {
1888                 FS_Print(file, "/* The engine may define the following macros:\n");
1889                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
1890                 for (i = 0;i < SHADERMODE_COUNT;i++)
1891                         FS_Print(file, glslshadermodeinfo[i].pretext);
1892                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1893                         FS_Print(file, shaderpermutationinfo[i].pretext);
1894                 FS_Print(file, "*/\n");
1895                 FS_Print(file, builtinshaderstring);
1896                 FS_Close(file);
1897                 Con_Printf("glsl/default.glsl written\n");
1898         }
1899         else
1900                 Con_Printf("failed to write to glsl/default.glsl\n");
1901
1902         file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
1903         if (file)
1904         {
1905                 FS_Print(file, "/* The engine may define the following macros:\n");
1906                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
1907                 for (i = 0;i < SHADERMODE_COUNT;i++)
1908                         FS_Print(file, hlslshadermodeinfo[i].pretext);
1909                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1910                         FS_Print(file, shaderpermutationinfo[i].pretext);
1911                 FS_Print(file, "*/\n");
1912                 FS_Print(file, builtinhlslshaderstring);
1913                 FS_Close(file);
1914                 Con_Printf("hlsl/default.hlsl written\n");
1915         }
1916         else
1917                 Con_Printf("failed to write to hlsl/default.hlsl\n");
1918 }
1919
1920 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale, qboolean usegamma, qboolean notrippy)
1921 {
1922         unsigned int permutation = 0;
1923         if (r_trippy.integer && !notrippy)
1924                 permutation |= SHADERPERMUTATION_TRIPPY;
1925         permutation |= SHADERPERMUTATION_VIEWTINT;
1926         if (first)
1927                 permutation |= SHADERPERMUTATION_DIFFUSE;
1928         if (second)
1929                 permutation |= SHADERPERMUTATION_SPECULAR;
1930         if (texturemode == GL_MODULATE)
1931                 permutation |= SHADERPERMUTATION_COLORMAPPING;
1932         else if (texturemode == GL_ADD)
1933                 permutation |= SHADERPERMUTATION_GLOW;
1934         else if (texturemode == GL_DECAL)
1935                 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
1936         if (usegamma && v_glslgamma.integer && v_glslgamma_2d.integer && !vid.sRGB2D && r_texture_gammaramps && !vid_gammatables_trivial)
1937                 permutation |= SHADERPERMUTATION_GAMMARAMPS;
1938         if (!second)
1939                 texturemode = GL_MODULATE;
1940         if (vid.allowalphatocoverage)
1941                 GL_AlphaToCoverage(false);
1942         switch (vid.renderpath)
1943         {
1944         case RENDERPATH_D3D9:
1945 #ifdef SUPPORTD3D
1946                 R_SetupShader_SetPermutationHLSL(SHADERMODE_GENERIC, permutation);
1947                 R_Mesh_TexBind(GL20TU_FIRST , first );
1948                 R_Mesh_TexBind(GL20TU_SECOND, second);
1949                 if (permutation & SHADERPERMUTATION_GAMMARAMPS)
1950                         R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps, r_texture_gammaramps);
1951 #endif
1952                 break;
1953         case RENDERPATH_D3D10:
1954                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1955                 break;
1956         case RENDERPATH_D3D11:
1957                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1958                 break;
1959         case RENDERPATH_GL20:
1960         case RENDERPATH_GLES2:
1961                 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, permutation);
1962                 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First , first );
1963                 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second, second);
1964                 if (r_glsl_permutation->tex_Texture_GammaRamps >= 0)
1965                         R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps, r_texture_gammaramps);
1966                 break;
1967         case RENDERPATH_GL13:
1968         case RENDERPATH_GLES1:
1969                 R_Mesh_TexBind(0, first );
1970                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
1971                 R_Mesh_TexBind(1, second);
1972                 if (second)
1973                         R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
1974                 break;
1975         case RENDERPATH_GL11:
1976                 R_Mesh_TexBind(0, first );
1977                 break;
1978         case RENDERPATH_SOFT:
1979                 R_SetupShader_SetPermutationSoft(SHADERMODE_GENERIC, permutation);
1980                 R_Mesh_TexBind(GL20TU_FIRST , first );
1981                 R_Mesh_TexBind(GL20TU_SECOND, second);
1982                 break;
1983         }
1984 }
1985
1986 void R_SetupShader_DepthOrShadow(qboolean notrippy)
1987 {
1988         unsigned int permutation = 0;
1989         if (r_trippy.integer && !notrippy)
1990                 permutation |= SHADERPERMUTATION_TRIPPY;
1991         if (vid.allowalphatocoverage)
1992                 GL_AlphaToCoverage(false);
1993         switch (vid.renderpath)
1994         {
1995         case RENDERPATH_D3D9:
1996 #ifdef SUPPORTD3D
1997                 R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, permutation);
1998 #endif
1999                 break;
2000         case RENDERPATH_D3D10:
2001                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2002                 break;
2003         case RENDERPATH_D3D11:
2004                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2005                 break;
2006         case RENDERPATH_GL20:
2007         case RENDERPATH_GLES2:
2008                 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, permutation);
2009                 break;
2010         case RENDERPATH_GL13:
2011         case RENDERPATH_GLES1:
2012                 R_Mesh_TexBind(0, 0);
2013                 R_Mesh_TexBind(1, 0);
2014                 break;
2015         case RENDERPATH_GL11:
2016                 R_Mesh_TexBind(0, 0);
2017                 break;
2018         case RENDERPATH_SOFT:
2019                 R_SetupShader_SetPermutationSoft(SHADERMODE_DEPTH_OR_SHADOW, permutation);
2020                 break;
2021         }
2022 }
2023
2024 void R_SetupShader_ShowDepth(qboolean notrippy)
2025 {
2026         int permutation = 0;
2027         if (r_trippy.integer && !notrippy)
2028                 permutation |= SHADERPERMUTATION_TRIPPY;
2029         if (vid.allowalphatocoverage)
2030                 GL_AlphaToCoverage(false);
2031         switch (vid.renderpath)
2032         {
2033         case RENDERPATH_D3D9:
2034 #ifdef SUPPORTHLSL
2035                 R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, permutation);
2036 #endif
2037                 break;
2038         case RENDERPATH_D3D10:
2039                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2040                 break;
2041         case RENDERPATH_D3D11:
2042                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2043                 break;
2044         case RENDERPATH_GL20:
2045         case RENDERPATH_GLES2:
2046                 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, permutation);
2047                 break;
2048         case RENDERPATH_GL13:
2049         case RENDERPATH_GLES1:
2050                 break;
2051         case RENDERPATH_GL11:
2052                 break;
2053         case RENDERPATH_SOFT:
2054                 R_SetupShader_SetPermutationSoft(SHADERMODE_SHOWDEPTH, permutation);
2055                 break;
2056         }
2057 }
2058
2059 extern qboolean r_shadow_usingdeferredprepass;
2060 extern cvar_t r_shadow_deferred_8bitrange;
2061 extern rtexture_t *r_shadow_attenuationgradienttexture;
2062 extern rtexture_t *r_shadow_attenuation2dtexture;
2063 extern rtexture_t *r_shadow_attenuation3dtexture;
2064 extern qboolean r_shadow_usingshadowmap2d;
2065 extern qboolean r_shadow_usingshadowmaportho;
2066 extern float r_shadow_shadowmap_texturescale[2];
2067 extern float r_shadow_shadowmap_parameters[4];
2068 extern qboolean r_shadow_shadowmapvsdct;
2069 extern qboolean r_shadow_shadowmapsampler;
2070 extern int r_shadow_shadowmappcf;
2071 extern rtexture_t *r_shadow_shadowmap2dtexture;
2072 extern rtexture_t *r_shadow_shadowmap2dcolortexture;
2073 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
2074 extern matrix4x4_t r_shadow_shadowmapmatrix;
2075 extern int r_shadow_shadowmaplod; // changes for each light based on distance
2076 extern int r_shadow_prepass_width;
2077 extern int r_shadow_prepass_height;
2078 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
2079 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
2080 extern rtexture_t *r_shadow_prepassgeometrydepthcolortexture;
2081 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
2082 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
2083
2084 #define BLENDFUNC_ALLOWS_COLORMOD      1
2085 #define BLENDFUNC_ALLOWS_FOG           2
2086 #define BLENDFUNC_ALLOWS_FOG_HACK0     4
2087 #define BLENDFUNC_ALLOWS_FOG_HACKALPHA 8
2088 #define BLENDFUNC_ALLOWS_ANYFOG        (BLENDFUNC_ALLOWS_FOG | BLENDFUNC_ALLOWS_FOG_HACK0 | BLENDFUNC_ALLOWS_FOG_HACKALPHA)
2089 static int R_BlendFuncFlags(int src, int dst)
2090 {
2091         int r = 0;
2092
2093         // a blendfunc allows colormod if:
2094         // a) it can never keep the destination pixel invariant, or
2095         // b) it can keep the destination pixel invariant, and still can do so if colormodded
2096         // this is to prevent unintended side effects from colormod
2097
2098         // a blendfunc allows fog if:
2099         // blend(fog(src), fog(dst)) == fog(blend(src, dst))
2100         // this is to prevent unintended side effects from fog
2101
2102         // these checks are the output of fogeval.pl
2103
2104         r |= BLENDFUNC_ALLOWS_COLORMOD;
2105         if(src == GL_DST_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2106         if(src == GL_DST_ALPHA && dst == GL_ONE_MINUS_DST_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2107         if(src == GL_DST_COLOR && dst == GL_ONE_MINUS_SRC_ALPHA) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2108         if(src == GL_DST_COLOR && dst == GL_ONE_MINUS_SRC_COLOR) r |= BLENDFUNC_ALLOWS_FOG;
2109         if(src == GL_DST_COLOR && dst == GL_SRC_ALPHA) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2110         if(src == GL_DST_COLOR && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2111         if(src == GL_DST_COLOR && dst == GL_ZERO) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2112         if(src == GL_ONE && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2113         if(src == GL_ONE && dst == GL_ONE_MINUS_SRC_ALPHA) r |= BLENDFUNC_ALLOWS_FOG_HACKALPHA;
2114         if(src == GL_ONE && dst == GL_ZERO) r |= BLENDFUNC_ALLOWS_FOG;
2115         if(src == GL_ONE_MINUS_DST_ALPHA && dst == GL_DST_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2116         if(src == GL_ONE_MINUS_DST_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2117         if(src == GL_ONE_MINUS_DST_COLOR && dst == GL_SRC_COLOR) r |= BLENDFUNC_ALLOWS_FOG;
2118         if(src == GL_ONE_MINUS_SRC_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2119         if(src == GL_ONE_MINUS_SRC_ALPHA && dst == GL_SRC_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2120         if(src == GL_ONE_MINUS_SRC_ALPHA && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2121         if(src == GL_ONE_MINUS_SRC_COLOR && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2122         if(src == GL_SRC_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2123         if(src == GL_SRC_ALPHA && dst == GL_ONE_MINUS_SRC_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2124         if(src == GL_ZERO && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG;
2125         if(src == GL_ZERO && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2126
2127         return r;
2128 }
2129
2130 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane, qboolean notrippy)
2131 {
2132         // select a permutation of the lighting shader appropriate to this
2133         // combination of texture, entity, light source, and fogging, only use the
2134         // minimum features necessary to avoid wasting rendering time in the
2135         // fragment shader on features that are not being used
2136         unsigned int permutation = 0;
2137         unsigned int mode = 0;
2138         int blendfuncflags;
2139         static float dummy_colormod[3] = {1, 1, 1};
2140         float *colormod = rsurface.colormod;
2141         float m16f[16];
2142         matrix4x4_t tempmatrix;
2143         r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
2144         if (r_trippy.integer && !notrippy)
2145                 permutation |= SHADERPERMUTATION_TRIPPY;
2146         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2147                 permutation |= SHADERPERMUTATION_ALPHAKILL;
2148         if (rsurface.texture->r_water_waterscroll[0] && rsurface.texture->r_water_waterscroll[1])
2149                 permutation |= SHADERPERMUTATION_NORMALMAPSCROLLBLEND; // todo: make generic
2150         if (rsurfacepass == RSURFPASS_BACKGROUND)
2151         {
2152                 // distorted background
2153                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
2154                 {
2155                         mode = SHADERMODE_WATER;
2156                         if((r_wateralpha.value < 1) && (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA))
2157                         {
2158                                 // this is the right thing to do for wateralpha
2159                                 GL_BlendFunc(GL_ONE, GL_ZERO);
2160                                 blendfuncflags = R_BlendFuncFlags(GL_ONE, GL_ZERO);
2161                         }
2162                         else
2163                         {
2164                                 // this is the right thing to do for entity alpha
2165                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2166                                 blendfuncflags = R_BlendFuncFlags(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2167                         }
2168                 }
2169                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
2170                 {
2171                         mode = SHADERMODE_REFRACTION;
2172                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2173                         blendfuncflags = R_BlendFuncFlags(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2174                 }
2175                 else
2176                 {
2177                         mode = SHADERMODE_GENERIC;
2178                         permutation |= SHADERPERMUTATION_DIFFUSE;
2179                         GL_BlendFunc(GL_ONE, GL_ZERO);
2180                         blendfuncflags = R_BlendFuncFlags(GL_ONE, GL_ZERO);
2181                 }
2182                 if (vid.allowalphatocoverage)
2183                         GL_AlphaToCoverage(false);
2184         }
2185         else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
2186         {
2187                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2188                 {
2189                         switch(rsurface.texture->offsetmapping)
2190                         {
2191                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2192                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2193                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2194                         case OFFSETMAPPING_OFF: break;
2195                         }
2196                 }
2197                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2198                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2199                 // normalmap (deferred prepass), may use alpha test on diffuse
2200                 mode = SHADERMODE_DEFERREDGEOMETRY;
2201                 GL_BlendFunc(GL_ONE, GL_ZERO);
2202                 blendfuncflags = R_BlendFuncFlags(GL_ONE, GL_ZERO);
2203                 if (vid.allowalphatocoverage)
2204                         GL_AlphaToCoverage(false);
2205         }
2206         else if (rsurfacepass == RSURFPASS_RTLIGHT)
2207         {
2208                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2209                 {
2210                         switch(rsurface.texture->offsetmapping)
2211                         {
2212                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2213                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2214                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2215                         case OFFSETMAPPING_OFF: break;
2216                         }
2217                 }
2218                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2219                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2220                 // light source
2221                 mode = SHADERMODE_LIGHTSOURCE;
2222                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2223                         permutation |= SHADERPERMUTATION_CUBEFILTER;
2224                 if (diffusescale > 0)
2225                         permutation |= SHADERPERMUTATION_DIFFUSE;
2226                 if (specularscale > 0)
2227                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2228                 if (r_refdef.fogenabled)
2229                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2230                 if (rsurface.texture->colormapping)
2231                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2232                 if (r_shadow_usingshadowmap2d)
2233                 {
2234                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2235                         if(r_shadow_shadowmapvsdct)
2236                                 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
2237
2238                         if (r_shadow_shadowmapsampler)
2239                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2240                         if (r_shadow_shadowmappcf > 1)
2241                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2242                         else if (r_shadow_shadowmappcf)
2243                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2244                 }
2245                 if (rsurface.texture->reflectmasktexture)
2246                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2247                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2248                 blendfuncflags = R_BlendFuncFlags(GL_SRC_ALPHA, GL_ONE);
2249                 if (vid.allowalphatocoverage)
2250                         GL_AlphaToCoverage(false);
2251         }
2252         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
2253         {
2254                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2255                 {
2256                         switch(rsurface.texture->offsetmapping)
2257                         {
2258                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2259                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2260                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2261                         case OFFSETMAPPING_OFF: break;
2262                         }
2263                 }
2264                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2265                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2266                 // unshaded geometry (fullbright or ambient model lighting)
2267                 mode = SHADERMODE_FLATCOLOR;
2268                 ambientscale = diffusescale = specularscale = 0;
2269                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2270                         permutation |= SHADERPERMUTATION_GLOW;
2271                 if (r_refdef.fogenabled)
2272                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2273                 if (rsurface.texture->colormapping)
2274                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2275                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2276                 {
2277                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2278                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2279
2280                         if (r_shadow_shadowmapsampler)
2281                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2282                         if (r_shadow_shadowmappcf > 1)
2283                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2284                         else if (r_shadow_shadowmappcf)
2285                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2286                 }
2287                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2288                         permutation |= SHADERPERMUTATION_REFLECTION;
2289                 if (rsurface.texture->reflectmasktexture)
2290                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2291                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2292                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2293                 // when using alphatocoverage, we don't need alphakill
2294                 if (vid.allowalphatocoverage)
2295                 {
2296                         if (r_transparent_alphatocoverage.integer)
2297                         {
2298                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2299                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2300                         }
2301                         else
2302                                 GL_AlphaToCoverage(false);
2303                 }
2304         }
2305         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
2306         {
2307                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2308                 {
2309                         switch(rsurface.texture->offsetmapping)
2310                         {
2311                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2312                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2313                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2314                         case OFFSETMAPPING_OFF: break;
2315                         }
2316                 }
2317                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2318                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2319                 // directional model lighting
2320                 mode = SHADERMODE_LIGHTDIRECTION;
2321                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2322                         permutation |= SHADERPERMUTATION_GLOW;
2323                 permutation |= SHADERPERMUTATION_DIFFUSE;
2324                 if (specularscale > 0)
2325                         permutation |= SHADERPERMUTATION_SPECULAR;
2326                 if (r_refdef.fogenabled)
2327                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2328                 if (rsurface.texture->colormapping)
2329                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2330                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2331                 {
2332                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2333                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2334
2335                         if (r_shadow_shadowmapsampler)
2336                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2337                         if (r_shadow_shadowmappcf > 1)
2338                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2339                         else if (r_shadow_shadowmappcf)
2340                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2341                 }
2342                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2343                         permutation |= SHADERPERMUTATION_REFLECTION;
2344                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
2345                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
2346                 if (rsurface.texture->reflectmasktexture)
2347                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2348                 if (r_shadow_bouncegridtexture && cl.csqc_vidvars.drawworld)
2349                 {
2350                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
2351                         if (r_shadow_bouncegriddirectional)
2352                                 permutation |= SHADERPERMUTATION_BOUNCEGRIDDIRECTIONAL;
2353                 }
2354                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2355                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2356                 // when using alphatocoverage, we don't need alphakill
2357                 if (vid.allowalphatocoverage)
2358                 {
2359                         if (r_transparent_alphatocoverage.integer)
2360                         {
2361                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2362                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2363                         }
2364                         else
2365                                 GL_AlphaToCoverage(false);
2366                 }
2367         }
2368         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
2369         {
2370                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2371                 {
2372                         switch(rsurface.texture->offsetmapping)
2373                         {
2374                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2375                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2376                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2377                         case OFFSETMAPPING_OFF: break;
2378                         }
2379                 }
2380                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2381                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2382                 // ambient model lighting
2383                 mode = SHADERMODE_LIGHTDIRECTION;
2384                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2385                         permutation |= SHADERPERMUTATION_GLOW;
2386                 if (r_refdef.fogenabled)
2387                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2388                 if (rsurface.texture->colormapping)
2389                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2390                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2391                 {
2392                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2393                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2394
2395                         if (r_shadow_shadowmapsampler)
2396                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2397                         if (r_shadow_shadowmappcf > 1)
2398                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2399                         else if (r_shadow_shadowmappcf)
2400                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2401                 }
2402                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2403                         permutation |= SHADERPERMUTATION_REFLECTION;
2404                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
2405                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
2406                 if (rsurface.texture->reflectmasktexture)
2407                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2408                 if (r_shadow_bouncegridtexture && cl.csqc_vidvars.drawworld)
2409                 {
2410                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
2411                         if (r_shadow_bouncegriddirectional)
2412                                 permutation |= SHADERPERMUTATION_BOUNCEGRIDDIRECTIONAL;
2413                 }
2414                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2415                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2416                 // when using alphatocoverage, we don't need alphakill
2417                 if (vid.allowalphatocoverage)
2418                 {
2419                         if (r_transparent_alphatocoverage.integer)
2420                         {
2421                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2422                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2423                         }
2424                         else
2425                                 GL_AlphaToCoverage(false);
2426                 }
2427         }
2428         else
2429         {
2430                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2431                 {
2432                         switch(rsurface.texture->offsetmapping)
2433                         {
2434                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2435                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2436                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2437                         case OFFSETMAPPING_OFF: break;
2438                         }
2439                 }
2440                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2441                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2442                 // lightmapped wall
2443                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2444                         permutation |= SHADERPERMUTATION_GLOW;
2445                 if (r_refdef.fogenabled)
2446                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2447                 if (rsurface.texture->colormapping)
2448                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2449                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2450                 {
2451                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2452                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2453
2454                         if (r_shadow_shadowmapsampler)
2455                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2456                         if (r_shadow_shadowmappcf > 1)
2457                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2458                         else if (r_shadow_shadowmappcf)
2459                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2460                 }
2461                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2462                         permutation |= SHADERPERMUTATION_REFLECTION;
2463                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
2464                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
2465                 if (rsurface.texture->reflectmasktexture)
2466                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2467                 if (FAKELIGHT_ENABLED)
2468                 {
2469                         // fake lightmapping (q1bsp, q3bsp, fullbright map)
2470                         mode = SHADERMODE_FAKELIGHT;
2471                         permutation |= SHADERPERMUTATION_DIFFUSE;
2472                         if (specularscale > 0)
2473                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2474                 }
2475                 else if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
2476                 {
2477                         // deluxemapping (light direction texture)
2478                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
2479                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
2480                         else
2481                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
2482                         permutation |= SHADERPERMUTATION_DIFFUSE;
2483                         if (specularscale > 0)
2484                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2485                 }
2486                 else if (r_glsl_deluxemapping.integer >= 2)
2487                 {
2488                         // fake deluxemapping (uniform light direction in tangentspace)
2489                         if (rsurface.uselightmaptexture)
2490                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_FORCED_LIGHTMAP;
2491                         else
2492                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_FORCED_VERTEXCOLOR;
2493                         permutation |= SHADERPERMUTATION_DIFFUSE;
2494                         if (specularscale > 0)
2495                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2496                 }
2497                 else if (rsurface.uselightmaptexture)
2498                 {
2499                         // ordinary lightmapping (q1bsp, q3bsp)
2500                         mode = SHADERMODE_LIGHTMAP;
2501                 }
2502                 else
2503                 {
2504                         // ordinary vertex coloring (q3bsp)
2505                         mode = SHADERMODE_VERTEXCOLOR;
2506                 }
2507                 if (r_shadow_bouncegridtexture && cl.csqc_vidvars.drawworld)
2508                 {
2509                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
2510                         if (r_shadow_bouncegriddirectional)
2511                                 permutation |= SHADERPERMUTATION_BOUNCEGRIDDIRECTIONAL;
2512                 }
2513                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2514                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2515                 // when using alphatocoverage, we don't need alphakill
2516                 if (vid.allowalphatocoverage)
2517                 {
2518                         if (r_transparent_alphatocoverage.integer)
2519                         {
2520                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2521                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2522                         }
2523                         else
2524                                 GL_AlphaToCoverage(false);
2525                 }
2526         }
2527         if(!(blendfuncflags & BLENDFUNC_ALLOWS_COLORMOD))
2528                 colormod = dummy_colormod;
2529         if(!(blendfuncflags & BLENDFUNC_ALLOWS_ANYFOG))
2530                 permutation &= ~(SHADERPERMUTATION_FOGHEIGHTTEXTURE | SHADERPERMUTATION_FOGOUTSIDE | SHADERPERMUTATION_FOGINSIDE);
2531         if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACKALPHA)
2532                 permutation |= SHADERPERMUTATION_FOGALPHAHACK;
2533         switch(vid.renderpath)
2534         {
2535         case RENDERPATH_D3D9:
2536 #ifdef SUPPORTD3D
2537                 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2538                 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
2539                 R_SetupShader_SetPermutationHLSL(mode, permutation);
2540                 Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
2541                 if (mode == SHADERMODE_LIGHTSOURCE)
2542                 {
2543                         Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
2544                         hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2545                 }
2546                 else
2547                 {
2548                         if (mode == SHADERMODE_LIGHTDIRECTION)
2549                         {
2550                                 hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2551                         }
2552                 }
2553                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
2554                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
2555                 Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
2556                 hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2557                 hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2558
2559                 if (mode == SHADERMODE_LIGHTSOURCE)
2560                 {
2561                         hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2562                         hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
2563                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
2564                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2565                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
2566
2567                         // additive passes are only darkened by fog, not tinted
2568                         hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
2569                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2570                 }
2571                 else
2572                 {
2573                         if (mode == SHADERMODE_FLATCOLOR)
2574                         {
2575                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0], colormod[1], colormod[2]);
2576                         }
2577                         else if (mode == SHADERMODE_LIGHTDIRECTION)
2578                         {
2579                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
2580                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
2581                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2582                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
2583                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
2584                                 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
2585                                 hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2586                         }
2587                         else
2588                         {
2589                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
2590                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
2591                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2592                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
2593                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
2594                         }
2595                         // additive passes are only darkened by fog, not tinted
2596                         if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACK0)
2597                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
2598                         else
2599                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
2600                         hlslPSSetParameter4f(D3DPSREGISTER_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
2601                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
2602                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
2603                         hlslPSSetParameter4f(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2604                         hlslPSSetParameter4f(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2605                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
2606                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
2607                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (rsurface.texture->specularpower - 1.0f) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
2608                         if (mode == SHADERMODE_WATER)
2609                                 hlslPSSetParameter2f(D3DPSREGISTER_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
2610                 }
2611                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
2612                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
2613                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
2614                 hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
2615                 hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2616                 if (rsurface.texture->pantstexture)
2617                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
2618                 else
2619                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
2620                 if (rsurface.texture->shirttexture)
2621                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
2622                 else
2623                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
2624                 hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2625                 hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
2626                 hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
2627                 hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
2628                 hlslPSSetParameter4f(D3DPSREGISTER_OffsetMapping_ScaleSteps,
2629                                 r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale,
2630                                 max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2631                                 1.0 / max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2632                                 max(1, r_glsl_offsetmapping_reliefmapping_refinesteps.integer)
2633                         );
2634                 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_LodDistance, r_glsl_offsetmapping_lod_distance.integer);
2635                 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Bias, rsurface.texture->offsetbias);
2636                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
2637                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
2638
2639                 R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
2640                 R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
2641                 R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
2642                 R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
2643                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
2644                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
2645                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
2646                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
2647                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
2648                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
2649                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
2650                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
2651                 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
2652                 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
2653                 R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
2654                 R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
2655                 if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
2656                 if (rsurfacepass == RSURFPASS_BACKGROUND)
2657                 {
2658                         R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
2659                         if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
2660                         R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2661                 }
2662                 else
2663                 {
2664                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2665                 }
2666 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
2667 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
2668                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
2669                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
2670                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
2671                 {
2672                         R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dcolortexture);
2673                         if (rsurface.rtlight)
2674                         {
2675                                 if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
2676                                 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
2677                         }
2678                 }
2679 #endif
2680                 break;
2681         case RENDERPATH_D3D10:
2682                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2683                 break;
2684         case RENDERPATH_D3D11:
2685                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2686                 break;
2687         case RENDERPATH_GL20:
2688         case RENDERPATH_GLES2:
2689                 if (!vid.useinterleavedarrays)
2690                 {
2691                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2692                         R_Mesh_VertexPointer(     3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
2693                         R_Mesh_ColorPointer(      4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
2694                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
2695                         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
2696                         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
2697                         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
2698                         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
2699                 }
2700                 else
2701                 {
2702                         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2703                         R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
2704                 }
2705                 R_SetupShader_SetPermutationGLSL(mode, permutation);
2706                 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
2707                 if (mode == SHADERMODE_LIGHTSOURCE)
2708                 {
2709                         if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
2710                         if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3f(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2711                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
2712                         if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
2713                         if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2714                         if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
2715         
2716                         // additive passes are only darkened by fog, not tinted
2717                         if (r_glsl_permutation->loc_FogColor >= 0)
2718                                 qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
2719                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2720                 }
2721                 else
2722                 {
2723                         if (mode == SHADERMODE_FLATCOLOR)
2724                         {
2725                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
2726                         }
2727                         else if (mode == SHADERMODE_LIGHTDIRECTION)
2728                         {
2729                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
2730                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
2731                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2732                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
2733                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
2734                                 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
2735                                 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3f(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2736                         }
2737                         else
2738                         {
2739                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
2740                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
2741                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2742                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
2743                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
2744                         }
2745                         // additive passes are only darkened by fog, not tinted
2746                         if (r_glsl_permutation->loc_FogColor >= 0)
2747                         {
2748                                 if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACK0)
2749                                         qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
2750                                 else
2751                                         qglUniform3f(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
2752                         }
2753                         if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
2754                         if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
2755                         if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
2756                         if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4f(r_glsl_permutation->loc_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2757                         if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4f(r_glsl_permutation->loc_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2758                         if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
2759                         if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
2760                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2761                         if (r_glsl_permutation->loc_NormalmapScrollBlend >= 0) qglUniform2f(r_glsl_permutation->loc_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
2762                 }
2763                 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
2764                 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
2765                 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
2766                 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2f(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
2767                 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4f(r_glsl_permutation->loc_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
2768
2769                 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
2770                 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1f(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
2771                 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3f(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2772                 if (r_glsl_permutation->loc_Color_Pants >= 0)
2773                 {
2774                         if (rsurface.texture->pantstexture)
2775                                 qglUniform3f(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
2776                         else
2777                                 qglUniform3f(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
2778                 }
2779                 if (r_glsl_permutation->loc_Color_Shirt >= 0)
2780                 {
2781                         if (rsurface.texture->shirttexture)
2782                                 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
2783                         else
2784                                 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
2785                 }
2786                 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4f(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2787                 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1f(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
2788                 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1f(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
2789                 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1f(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
2790                 if (r_glsl_permutation->loc_OffsetMapping_ScaleSteps >= 0) qglUniform4f(r_glsl_permutation->loc_OffsetMapping_ScaleSteps,
2791                                 r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale,
2792                                 max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2793                                 1.0 / max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2794                                 max(1, r_glsl_offsetmapping_reliefmapping_refinesteps.integer)
2795                         );
2796                 if (r_glsl_permutation->loc_OffsetMapping_LodDistance >= 0) qglUniform1f(r_glsl_permutation->loc_OffsetMapping_LodDistance, r_glsl_offsetmapping_lod_distance.integer);
2797                 if (r_glsl_permutation->loc_OffsetMapping_Bias >= 0) qglUniform1f(r_glsl_permutation->loc_OffsetMapping_Bias, rsurface.texture->offsetbias);
2798                 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2f(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
2799                 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2f(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
2800                 if (r_glsl_permutation->loc_BounceGridMatrix >= 0) {Matrix4x4_Concat(&tempmatrix, &r_shadow_bouncegridmatrix, &rsurface.matrix);Matrix4x4_ToArrayFloatGL(&tempmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BounceGridMatrix, 1, false, m16f);}
2801                 if (r_glsl_permutation->loc_BounceGridIntensity >= 0) qglUniform1f(r_glsl_permutation->loc_BounceGridIntensity, r_shadow_bouncegridintensity*r_refdef.view.colorscale);
2802
2803                 if (r_glsl_permutation->tex_Texture_First           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First            , r_texture_white                                     );
2804                 if (r_glsl_permutation->tex_Texture_Second          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second           , r_texture_white                                     );
2805                 if (r_glsl_permutation->tex_Texture_GammaRamps      >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps       , r_texture_gammaramps                                );
2806                 if (r_glsl_permutation->tex_Texture_Normal          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Normal           , rsurface.texture->nmaptexture                       );
2807                 if (r_glsl_permutation->tex_Texture_Color           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Color            , rsurface.texture->basetexture                       );
2808                 if (r_glsl_permutation->tex_Texture_Gloss           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Gloss            , rsurface.texture->glosstexture                      );
2809                 if (r_glsl_permutation->tex_Texture_Glow            >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Glow             , rsurface.texture->glowtexture                       );
2810                 if (r_glsl_permutation->tex_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryNormal  , rsurface.texture->backgroundnmaptexture             );
2811                 if (r_glsl_permutation->tex_Texture_SecondaryColor  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryColor   , rsurface.texture->backgroundbasetexture             );
2812                 if (r_glsl_permutation->tex_Texture_SecondaryGloss  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGloss   , rsurface.texture->backgroundglosstexture            );
2813                 if (r_glsl_permutation->tex_Texture_SecondaryGlow   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGlow    , rsurface.texture->backgroundglowtexture             );
2814                 if (r_glsl_permutation->tex_Texture_Pants           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Pants            , rsurface.texture->pantstexture                      );
2815                 if (r_glsl_permutation->tex_Texture_Shirt           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Shirt            , rsurface.texture->shirttexture                      );
2816                 if (r_glsl_permutation->tex_Texture_ReflectMask     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectMask      , rsurface.texture->reflectmasktexture                );
2817                 if (r_glsl_permutation->tex_Texture_ReflectCube     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectCube      , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
2818                 if (r_glsl_permutation->tex_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogHeightTexture , r_texture_fogheighttexture                          );
2819                 if (r_glsl_permutation->tex_Texture_FogMask         >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogMask          , r_texture_fogattenuation                            );
2820                 if (r_glsl_permutation->tex_Texture_Lightmap        >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Lightmap         , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
2821                 if (r_glsl_permutation->tex_Texture_Deluxemap       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Deluxemap        , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
2822                 if (r_glsl_permutation->tex_Texture_Attenuation     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation      , r_shadow_attenuationgradienttexture                 );
2823                 if (rsurfacepass == RSURFPASS_BACKGROUND)
2824                 {
2825                         if (r_glsl_permutation->tex_Texture_Refraction  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Refraction        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
2826                         if (r_glsl_permutation->tex_Texture_First       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
2827                         if (r_glsl_permutation->tex_Texture_Reflection  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2828                 }
2829                 else
2830                 {
2831                         if (r_glsl_permutation->tex_Texture_Reflection >= 0 && waterplane) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2832                 }
2833                 if (r_glsl_permutation->tex_Texture_ScreenDepth     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth       , r_shadow_prepassgeometrydepthtexture                );
2834                 if (r_glsl_permutation->tex_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap   , r_shadow_prepassgeometrynormalmaptexture            );
2835                 if (r_glsl_permutation->tex_Texture_ScreenDiffuse   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDiffuse     , r_shadow_prepasslightingdiffusetexture              );
2836                 if (r_glsl_permutation->tex_Texture_ScreenSpecular  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenSpecular    , r_shadow_prepasslightingspeculartexture             );
2837                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
2838                 {
2839                         if (r_glsl_permutation->tex_Texture_ShadowMap2D     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D, r_shadow_shadowmap2dtexture                         );
2840                         if (rsurface.rtlight)
2841                         {
2842                                 if (r_glsl_permutation->tex_Texture_Cube            >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube              , rsurface.rtlight->currentcubemap                    );
2843                                 if (r_glsl_permutation->tex_Texture_CubeProjection  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection    , r_shadow_shadowmapvsdcttexture                      );
2844                         }
2845                 }
2846                 if (r_glsl_permutation->tex_Texture_BounceGrid  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_BounceGrid, r_shadow_bouncegridtexture);
2847                 CHECKGLERROR
2848                 break;
2849         case RENDERPATH_GL11:
2850         case RENDERPATH_GL13:
2851         case RENDERPATH_GLES1:
2852                 break;
2853         case RENDERPATH_SOFT:
2854                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2855                 R_Mesh_PrepareVertices_Mesh_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchsvector3f, rsurface.batchtvector3f, rsurface.batchnormal3f, rsurface.batchlightmapcolor4f, rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordlightmap2f);
2856                 R_SetupShader_SetPermutationSoft(mode, permutation);
2857                 {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToReflectCubeM1, 1, false, m16f);}
2858                 if (mode == SHADERMODE_LIGHTSOURCE)
2859                 {
2860                         {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToLightM1, 1, false, m16f);}
2861                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2862                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
2863                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
2864                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2865                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
2866         
2867                         // additive passes are only darkened by fog, not tinted
2868                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
2869                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2870                 }
2871                 else
2872                 {
2873                         if (mode == SHADERMODE_FLATCOLOR)
2874                         {
2875                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0], colormod[1], colormod[2]);
2876                         }
2877                         else if (mode == SHADERMODE_LIGHTDIRECTION)
2878                         {
2879                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
2880                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
2881                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2882                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
2883                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
2884                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
2885                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2886                         }
2887                         else
2888                         {
2889                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
2890                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
2891                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2892                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
2893                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
2894                         }
2895                         // additive passes are only darkened by fog, not tinted
2896                         if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACK0)
2897                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
2898                         else
2899                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
2900                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
2901                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
2902                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
2903                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2904                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2905                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
2906                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectOffset, rsurface.texture->reflectmin);
2907                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2908                         DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
2909                 }
2910                 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_TexMatrixM1, 1, false, m16f);}
2911                 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_BackgroundTexMatrixM1, 1, false, m16f);}
2912                 {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ShadowMapMatrixM1, 1, false, m16f);}
2913                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
2914                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
2915
2916                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
2917                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
2918                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2919                 if (DPSOFTRAST_UNIFORM_Color_Pants >= 0)
2920                 {
2921                         if (rsurface.texture->pantstexture)
2922                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
2923                         else
2924                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, 0, 0, 0);
2925                 }
2926                 if (DPSOFTRAST_UNIFORM_Color_Shirt >= 0)
2927                 {
2928                         if (rsurface.texture->shirttexture)
2929                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
2930                         else
2931                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, 0, 0, 0);
2932                 }
2933                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2934                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogPlaneViewDist, rsurface.fogplaneviewdist);
2935                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogRangeRecip, rsurface.fograngerecip);
2936                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogHeightFade, rsurface.fogheightfade);
2937                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_OffsetMapping_ScaleSteps,
2938                                 r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale,
2939                                 max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2940                                 1.0 / max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2941                                 max(1, r_glsl_offsetmapping_reliefmapping_refinesteps.integer)
2942                         );
2943                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_OffsetMapping_LodDistance, r_glsl_offsetmapping_lod_distance.integer);
2944                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_OffsetMapping_Bias, rsurface.texture->offsetbias);
2945                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
2946                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
2947
2948                 R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
2949                 R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
2950                 R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
2951                 R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
2952                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
2953                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
2954                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
2955                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
2956                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
2957                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
2958                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
2959                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
2960                 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
2961                 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
2962                 R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
2963                 R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
2964                 if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
2965                 if (rsurfacepass == RSURFPASS_BACKGROUND)
2966                 {
2967                         R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
2968                         if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
2969                         R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2970                 }
2971                 else
2972                 {
2973                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2974                 }
2975 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
2976 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
2977                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
2978                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
2979                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
2980                 {
2981                         R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dcolortexture);
2982                         if (rsurface.rtlight)
2983                         {
2984                                 if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
2985                                 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
2986                         }
2987                 }
2988                 break;
2989         }
2990 }
2991
2992 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
2993 {
2994         // select a permutation of the lighting shader appropriate to this
2995         // combination of texture, entity, light source, and fogging, only use the
2996         // minimum features necessary to avoid wasting rendering time in the
2997         // fragment shader on features that are not being used
2998         unsigned int permutation = 0;
2999         unsigned int mode = 0;
3000         const float *lightcolorbase = rtlight->currentcolor;
3001         float ambientscale = rtlight->ambientscale;
3002         float diffusescale = rtlight->diffusescale;
3003         float specularscale = rtlight->specularscale;
3004         // this is the location of the light in view space
3005         vec3_t viewlightorigin;
3006         // this transforms from view space (camera) to light space (cubemap)
3007         matrix4x4_t viewtolight;
3008         matrix4x4_t lighttoview;
3009         float viewtolight16f[16];
3010         float range = 1.0f / r_shadow_deferred_8bitrange.value;
3011         // light source
3012         mode = SHADERMODE_DEFERREDLIGHTSOURCE;
3013         if (rtlight->currentcubemap != r_texture_whitecube)
3014                 permutation |= SHADERPERMUTATION_CUBEFILTER;
3015         if (diffusescale > 0)
3016                 permutation |= SHADERPERMUTATION_DIFFUSE;
3017         if (specularscale > 0 && r_shadow_gloss.integer > 0)
3018                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
3019         if (r_shadow_usingshadowmap2d)
3020         {
3021                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
3022                 if (r_shadow_shadowmapvsdct)
3023                         permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
3024
3025                 if (r_shadow_shadowmapsampler)
3026                         permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
3027                 if (r_shadow_shadowmappcf > 1)
3028                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
3029                 else if (r_shadow_shadowmappcf)
3030                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
3031         }
3032         if (vid.allowalphatocoverage)
3033                 GL_AlphaToCoverage(false);
3034         Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
3035         Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
3036         Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
3037         Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
3038         switch(vid.renderpath)
3039         {
3040         case RENDERPATH_D3D9:
3041 #ifdef SUPPORTD3D
3042                 R_SetupShader_SetPermutationHLSL(mode, permutation);
3043                 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
3044                 hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
3045                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
3046                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
3047                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
3048                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
3049                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
3050                 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
3051                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
3052                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
3053
3054                 R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
3055                 R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthcolortexture           );
3056                 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
3057                 R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
3058                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dcolortexture                    );
3059                 R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
3060 #endif
3061                 break;
3062         case RENDERPATH_D3D10:
3063                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3064                 break;
3065         case RENDERPATH_D3D11:
3066                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3067                 break;
3068         case RENDERPATH_GL20:
3069         case RENDERPATH_GLES2:
3070                 R_SetupShader_SetPermutationGLSL(mode, permutation);
3071                 if (r_glsl_permutation->loc_LightPosition             >= 0) qglUniform3f(       r_glsl_permutation->loc_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
3072                 if (r_glsl_permutation->loc_ViewToLight               >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ViewToLight              , 1, false, viewtolight16f);
3073                 if (r_glsl_permutation->loc_DeferredColor_Ambient     >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
3074                 if (r_glsl_permutation->loc_DeferredColor_Diffuse     >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
3075                 if (r_glsl_permutation->loc_DeferredColor_Specular    >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Specular   , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
3076                 if (r_glsl_permutation->loc_ShadowMap_TextureScale    >= 0) qglUniform2f(       r_glsl_permutation->loc_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
3077                 if (r_glsl_permutation->loc_ShadowMap_Parameters      >= 0) qglUniform4f(       r_glsl_permutation->loc_ShadowMap_Parameters     , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
3078                 if (r_glsl_permutation->loc_SpecularPower             >= 0) qglUniform1f(       r_glsl_permutation->loc_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
3079                 if (r_glsl_permutation->loc_ScreenToDepth             >= 0) qglUniform2f(       r_glsl_permutation->loc_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
3080                 if (r_glsl_permutation->loc_PixelToScreenTexCoord     >= 0) qglUniform2f(       r_glsl_permutation->loc_PixelToScreenTexCoord    , 1.0f/vid.width, 1.0f/vid.height);
3081
3082                 if (r_glsl_permutation->tex_Texture_Attenuation       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation        , r_shadow_attenuationgradienttexture                 );
3083                 if (r_glsl_permutation->tex_Texture_ScreenDepth       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth        , r_shadow_prepassgeometrydepthtexture                );
3084                 if (r_glsl_permutation->tex_Texture_ScreenNormalMap   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap    , r_shadow_prepassgeometrynormalmaptexture            );
3085                 if (r_glsl_permutation->tex_Texture_Cube              >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube               , rsurface.rtlight->currentcubemap                    );
3086                 if (r_glsl_permutation->tex_Texture_ShadowMap2D       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D        , r_shadow_shadowmap2dtexture                         );
3087                 if (r_glsl_permutation->tex_Texture_CubeProjection    >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection     , r_shadow_shadowmapvsdcttexture                      );
3088                 break;
3089         case RENDERPATH_GL11:
3090         case RENDERPATH_GL13:
3091         case RENDERPATH_GLES1:
3092                 break;
3093         case RENDERPATH_SOFT:
3094                 R_SetupShader_SetPermutationGLSL(mode, permutation);
3095                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
3096                 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ViewToLightM1            , 1, false, viewtolight16f);
3097                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
3098                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
3099                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Specular   , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
3100                 DPSOFTRAST_Uniform2f(       DPSOFTRAST_UNIFORM_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
3101                 DPSOFTRAST_Uniform4f(       DPSOFTRAST_UNIFORM_ShadowMap_Parameters     , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
3102                 DPSOFTRAST_Uniform1f(       DPSOFTRAST_UNIFORM_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
3103                 DPSOFTRAST_Uniform2f(       DPSOFTRAST_UNIFORM_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
3104                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
3105
3106                 R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
3107                 R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthtexture                );
3108                 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
3109                 R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
3110                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dtexture                         );
3111                 R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
3112                 break;
3113         }
3114 }
3115
3116 #define SKINFRAME_HASH 1024
3117
3118 typedef struct
3119 {
3120         int loadsequence; // incremented each level change
3121         memexpandablearray_t array;
3122         skinframe_t *hash[SKINFRAME_HASH];
3123 }
3124 r_skinframe_t;
3125 r_skinframe_t r_skinframe;
3126
3127 void R_SkinFrame_PrepareForPurge(void)
3128 {
3129         r_skinframe.loadsequence++;
3130         // wrap it without hitting zero
3131         if (r_skinframe.loadsequence >= 200)
3132                 r_skinframe.loadsequence = 1;
3133 }
3134
3135 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
3136 {
3137         if (!skinframe)
3138                 return;
3139         // mark the skinframe as used for the purging code
3140         skinframe->loadsequence = r_skinframe.loadsequence;
3141 }
3142
3143 void R_SkinFrame_Purge(void)
3144 {
3145         int i;
3146         skinframe_t *s;
3147         for (i = 0;i < SKINFRAME_HASH;i++)
3148         {
3149                 for (s = r_skinframe.hash[i];s;s = s->next)
3150                 {
3151                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
3152                         {
3153                                 if (s->merged == s->base)
3154                                         s->merged = NULL;
3155                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
3156                                 R_PurgeTexture(s->stain );s->stain  = NULL;
3157                                 R_PurgeTexture(s->merged);s->merged = NULL;
3158                                 R_PurgeTexture(s->base  );s->base   = NULL;
3159                                 R_PurgeTexture(s->pants );s->pants  = NULL;
3160                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
3161                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
3162                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
3163                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
3164                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
3165                                 R_PurgeTexture(s->reflect);s->reflect = NULL;
3166                                 s->loadsequence = 0;
3167                         }
3168                 }
3169         }
3170 }
3171
3172 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
3173         skinframe_t *item;
3174         char basename[MAX_QPATH];
3175
3176         Image_StripImageExtension(name, basename, sizeof(basename));
3177
3178         if( last == NULL ) {
3179                 int hashindex;
3180                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
3181                 item = r_skinframe.hash[hashindex];
3182         } else {
3183                 item = last->next;
3184         }
3185
3186         // linearly search through the hash bucket
3187         for( ; item ; item = item->next ) {
3188                 if( !strcmp( item->basename, basename ) ) {
3189                         return item;
3190                 }
3191         }
3192         return NULL;
3193 }
3194
3195 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
3196 {
3197         skinframe_t *item;
3198         int hashindex;
3199         char basename[MAX_QPATH];
3200
3201         Image_StripImageExtension(name, basename, sizeof(basename));
3202
3203         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
3204         for (item = r_skinframe.hash[hashindex];item;item = item->next)
3205                 if (!strcmp(item->basename, basename) && (comparecrc < 0 || (item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)))
3206                         break;
3207
3208         if (!item) {
3209                 rtexture_t *dyntexture;
3210                 // check whether its a dynamic texture
3211                 dyntexture = CL_GetDynTexture( basename );
3212                 if (!add && !dyntexture)
3213                         return NULL;
3214                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
3215                 memset(item, 0, sizeof(*item));
3216                 strlcpy(item->basename, basename, sizeof(item->basename));
3217                 item->base = dyntexture; // either NULL or dyntexture handle
3218                 item->textureflags = textureflags & ~TEXF_FORCE_RELOAD;
3219                 item->comparewidth = comparewidth;
3220                 item->compareheight = compareheight;
3221                 item->comparecrc = comparecrc;
3222                 item->next = r_skinframe.hash[hashindex];
3223                 r_skinframe.hash[hashindex] = item;
3224         }
3225         else if (textureflags & TEXF_FORCE_RELOAD)
3226         {
3227                 rtexture_t *dyntexture;
3228                 // check whether its a dynamic texture
3229                 dyntexture = CL_GetDynTexture( basename );
3230                 if (!add && !dyntexture)
3231                         return NULL;
3232                 if (item->merged == item->base)
3233                         item->merged = NULL;
3234                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
3235                 R_PurgeTexture(item->stain );item->stain  = NULL;
3236                 R_PurgeTexture(item->merged);item->merged = NULL;
3237                 R_PurgeTexture(item->base  );item->base   = NULL;
3238                 R_PurgeTexture(item->pants );item->pants  = NULL;
3239                 R_PurgeTexture(item->shirt );item->shirt  = NULL;
3240                 R_PurgeTexture(item->nmap  );item->nmap   = NULL;
3241                 R_PurgeTexture(item->gloss );item->gloss  = NULL;
3242                 R_PurgeTexture(item->glow  );item->glow   = NULL;
3243                 R_PurgeTexture(item->fog   );item->fog    = NULL;
3244         R_PurgeTexture(item->reflect);item->reflect = NULL;
3245                 item->loadsequence = 0;
3246         }
3247         else if( item->base == NULL )
3248         {
3249                 rtexture_t *dyntexture;
3250                 // check whether its a dynamic texture
3251                 // 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]
3252                 dyntexture = CL_GetDynTexture( basename );
3253                 item->base = dyntexture; // either NULL or dyntexture handle
3254         }
3255
3256         R_SkinFrame_MarkUsed(item);
3257         return item;
3258 }
3259
3260 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
3261         { \
3262                 unsigned long long avgcolor[5], wsum; \
3263                 int pix, comp, w; \
3264                 avgcolor[0] = 0; \
3265                 avgcolor[1] = 0; \
3266                 avgcolor[2] = 0; \
3267                 avgcolor[3] = 0; \
3268                 avgcolor[4] = 0; \
3269                 wsum = 0; \
3270                 for(pix = 0; pix < cnt; ++pix) \
3271                 { \
3272                         w = 0; \
3273                         for(comp = 0; comp < 3; ++comp) \
3274                                 w += getpixel; \
3275                         if(w) /* ignore perfectly black pixels because that is better for model skins */ \
3276                         { \
3277                                 ++wsum; \
3278                                 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
3279                                 w = getpixel; \
3280                                 for(comp = 0; comp < 3; ++comp) \
3281                                         avgcolor[comp] += getpixel * w; \
3282                                 avgcolor[3] += w; \
3283                         } \
3284                         /* comp = 3; -- not needed, comp is always 3 when we get here */ \
3285                         avgcolor[4] += getpixel; \
3286                 } \
3287                 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
3288                         avgcolor[3] = 1; \
3289                 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
3290                 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
3291                 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
3292                 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
3293         }
3294
3295 extern cvar_t gl_picmip;
3296 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
3297 {
3298         int j;
3299         unsigned char *pixels;
3300         unsigned char *bumppixels;
3301         unsigned char *basepixels = NULL;
3302         int basepixels_width = 0;
3303         int basepixels_height = 0;
3304         skinframe_t *skinframe;
3305         rtexture_t *ddsbase = NULL;
3306         qboolean ddshasalpha = false;
3307         float ddsavgcolor[4];
3308         char basename[MAX_QPATH];
3309         int miplevel = R_PicmipForFlags(textureflags);
3310         int savemiplevel = miplevel;
3311         int mymiplevel;
3312
3313         if (cls.state == ca_dedicated)
3314                 return NULL;
3315
3316         // return an existing skinframe if already loaded
3317         // if loading of the first image fails, don't make a new skinframe as it
3318         // would cause all future lookups of this to be missing
3319         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
3320         if (skinframe && skinframe->base)
3321                 return skinframe;
3322
3323         Image_StripImageExtension(name, basename, sizeof(basename));
3324
3325         // check for DDS texture file first
3326         if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
3327         {
3328                 basepixels = loadimagepixelsbgra(name, complain, true, false, &miplevel);
3329                 if (basepixels == NULL)
3330                         return NULL;
3331         }
3332
3333         // FIXME handle miplevel
3334
3335         if (developer_loading.integer)
3336                 Con_Printf("loading skin \"%s\"\n", name);
3337
3338         // we've got some pixels to store, so really allocate this new texture now
3339         if (!skinframe)
3340                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
3341         textureflags &= ~TEXF_FORCE_RELOAD;
3342         skinframe->stain = NULL;
3343         skinframe->merged = NULL;
3344         skinframe->base = NULL;
3345         skinframe->pants = NULL;
3346         skinframe->shirt = NULL;
3347         skinframe->nmap = NULL;
3348         skinframe->gloss = NULL;
3349         skinframe->glow = NULL;
3350         skinframe->fog = NULL;
3351         skinframe->reflect = NULL;
3352         skinframe->hasalpha = false;
3353
3354         if (ddsbase)
3355         {
3356                 skinframe->base = ddsbase;
3357                 skinframe->hasalpha = ddshasalpha;
3358                 VectorCopy(ddsavgcolor, skinframe->avgcolor);
3359                 if (r_loadfog && skinframe->hasalpha)
3360                         skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
3361                 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
3362         }
3363         else
3364         {
3365                 basepixels_width = image_width;
3366                 basepixels_height = image_height;
3367                 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, vid.sRGB3D ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
3368                 if (textureflags & TEXF_ALPHA)
3369                 {
3370                         for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
3371                         {
3372                                 if (basepixels[j] < 255)
3373                                 {
3374                                         skinframe->hasalpha = true;
3375                                         break;
3376                                 }
3377                         }
3378                         if (r_loadfog && skinframe->hasalpha)
3379                         {
3380                                 // has transparent pixels
3381                                 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
3382                                 for (j = 0;j < image_width * image_height * 4;j += 4)
3383                                 {
3384                                         pixels[j+0] = 255;
3385                                         pixels[j+1] = 255;
3386                                         pixels[j+2] = 255;
3387                                         pixels[j+3] = basepixels[j+3];
3388                                 }
3389                                 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
3390                                 Mem_Free(pixels);
3391                         }
3392                 }
3393                 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
3394 #ifndef USE_GLES2
3395                 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
3396                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
3397                         R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), r_texture_dds_save.integer < 2, skinframe->hasalpha);
3398                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
3399                         R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), r_texture_dds_save.integer < 2, true);
3400 #endif
3401         }
3402
3403         if (r_loaddds)
3404         {
3405                 mymiplevel = savemiplevel;
3406                 if (r_loadnormalmap)
3407                         skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), NULL, NULL, mymiplevel);
3408                 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
3409                 if (r_loadgloss)
3410                         skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
3411                 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
3412                 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
3413                 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
3414         }
3415
3416         // _norm is the name used by tenebrae and has been adopted as standard
3417         if (r_loadnormalmap && skinframe->nmap == NULL)
3418         {
3419                 mymiplevel = savemiplevel;
3420                 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
3421                 {
3422                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3423                         Mem_Free(pixels);
3424                         pixels = NULL;
3425                 }
3426                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
3427                 {
3428                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
3429                         Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
3430                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3431                         Mem_Free(pixels);
3432                         Mem_Free(bumppixels);
3433                 }
3434                 else if (r_shadow_bumpscale_basetexture.value > 0)
3435                 {
3436                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
3437                         Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
3438                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3439                         Mem_Free(pixels);
3440                 }
3441 #ifndef USE_GLES2
3442                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
3443                         R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), r_texture_dds_save.integer < 2, true);
3444 #endif
3445         }
3446
3447         // _luma is supported only for tenebrae compatibility
3448         // _glow is the preferred name
3449         mymiplevel = savemiplevel;
3450         if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow",  skinframe->basename), false, false, false, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, false, &mymiplevel))))
3451         {
3452                 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, vid.sRGB3D ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, textureflags & (gl_texturecompression_glow.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3453 #ifndef USE_GLES2
3454                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
3455                         R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), r_texture_dds_save.integer < 2, true);
3456 #endif
3457                 Mem_Free(pixels);pixels = NULL;
3458         }
3459
3460         mymiplevel = savemiplevel;
3461         if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, false, &mymiplevel)))
3462         {
3463                 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, vid.sRGB3D ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (gl_texturecompression_gloss.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3464 #ifndef USE_GLES2
3465                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
3466                         R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), r_texture_dds_save.integer < 2, true);
3467 #endif
3468                 Mem_Free(pixels);
3469                 pixels = NULL;
3470         }
3471
3472         mymiplevel = savemiplevel;
3473         if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, false, &mymiplevel)))
3474         {
3475                 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, vid.sRGB3D ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3476 #ifndef USE_GLES2
3477                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
3478                         R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), r_texture_dds_save.integer < 2, false);
3479 #endif
3480                 Mem_Free(pixels);
3481                 pixels = NULL;
3482         }
3483
3484         mymiplevel = savemiplevel;
3485         if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, false, &mymiplevel)))
3486         {
3487                 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, vid.sRGB3D ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3488 #ifndef USE_GLES2
3489                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
3490                         R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), r_texture_dds_save.integer < 2, false);
3491 #endif
3492                 Mem_Free(pixels);
3493                 pixels = NULL;
3494         }
3495
3496         mymiplevel = savemiplevel;
3497         if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, false, &mymiplevel)))
3498         {
3499                 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, vid.sRGB3D ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, textureflags & (gl_texturecompression_reflectmask.integer && gl_texturecompression.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
3500 #ifndef USE_GLES2
3501                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
3502                         R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), r_texture_dds_save.integer < 2, true);
3503 #endif
3504                 Mem_Free(pixels);
3505                 pixels = NULL;
3506         }
3507
3508         if (basepixels)
3509                 Mem_Free(basepixels);
3510
3511         return skinframe;
3512 }
3513
3514 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
3515 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height, qboolean sRGB)
3516 {
3517         int i;
3518         unsigned char *temp1, *temp2;
3519         skinframe_t *skinframe;
3520
3521         if (cls.state == ca_dedicated)
3522                 return NULL;
3523
3524         // if already loaded just return it, otherwise make a new skinframe
3525         skinframe = R_SkinFrame_Find(name, textureflags, width, height, (textureflags & TEXF_FORCE_RELOAD) ? -1 : skindata ? CRC_Block(skindata, width*height*4) : 0, true);
3526         if (skinframe && skinframe->base)
3527                 return skinframe;
3528         textureflags &= ~TEXF_FORCE_RELOAD;
3529
3530         skinframe->stain = NULL;
3531         skinframe->merged = NULL;
3532         skinframe->base = NULL;
3533         skinframe->pants = NULL;
3534         skinframe->shirt = NULL;
3535         skinframe->nmap = NULL;
3536         skinframe->gloss = NULL;
3537         skinframe->glow = NULL;
3538         skinframe->fog = NULL;
3539         skinframe->reflect = NULL;
3540         skinframe->hasalpha = false;
3541
3542         // if no data was provided, then clearly the caller wanted to get a blank skinframe
3543         if (!skindata)
3544                 return NULL;
3545
3546         if (developer_loading.integer)
3547                 Con_Printf("loading 32bit skin \"%s\"\n", name);
3548
3549         if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
3550         {
3551                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
3552                 temp2 = temp1 + width * height * 4;
3553                 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
3554                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
3555                 Mem_Free(temp1);
3556         }
3557         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, sRGB ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, textureflags, -1, NULL);
3558         if (textureflags & TEXF_ALPHA)
3559         {
3560                 for (i = 3;i < width * height * 4;i += 4)
3561                 {
3562                         if (skindata[i] < 255)
3563                         {
3564                                 skinframe->hasalpha = true;
3565                                 break;
3566                         }
3567                 }
3568                 if (r_loadfog && skinframe->hasalpha)
3569                 {
3570                         unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
3571                         memcpy(fogpixels, skindata, width * height * 4);
3572                         for (i = 0;i < width * height * 4;i += 4)
3573                                 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
3574                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
3575                         Mem_Free(fogpixels);
3576                 }
3577         }
3578
3579         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
3580         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
3581
3582         return skinframe;
3583 }
3584
3585 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
3586 {
3587         int i;
3588         int featuresmask;
3589         skinframe_t *skinframe;
3590
3591         if (cls.state == ca_dedicated)
3592                 return NULL;
3593
3594         // if already loaded just return it, otherwise make a new skinframe
3595         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
3596         if (skinframe && skinframe->base)
3597                 return skinframe;
3598         textureflags &= ~TEXF_FORCE_RELOAD;
3599
3600         skinframe->stain = NULL;
3601         skinframe->merged = NULL;
3602         skinframe->base = NULL;
3603         skinframe->pants = NULL;
3604         skinframe->shirt = NULL;
3605         skinframe->nmap = NULL;
3606         skinframe->gloss = NULL;
3607         skinframe->glow = NULL;
3608         skinframe->fog = NULL;
3609         skinframe->reflect = NULL;
3610         skinframe->hasalpha = false;
3611
3612         // if no data was provided, then clearly the caller wanted to get a blank skinframe
3613         if (!skindata)
3614                 return NULL;
3615
3616         if (developer_loading.integer)
3617                 Con_Printf("loading quake skin \"%s\"\n", name);
3618
3619         // we actually don't upload anything until the first use, because mdl skins frequently go unused, and are almost never used in both modes (colormapped and non-colormapped)
3620         skinframe->qpixels = (unsigned char *)Mem_Alloc(r_main_mempool, width*height); // FIXME LEAK
3621         memcpy(skinframe->qpixels, skindata, width*height);
3622         skinframe->qwidth = width;
3623         skinframe->qheight = height;
3624
3625         featuresmask = 0;
3626         for (i = 0;i < width * height;i++)
3627                 featuresmask |= palette_featureflags[skindata[i]];
3628
3629         skinframe->hasalpha = false;
3630         skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
3631         skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
3632         skinframe->qgeneratemerged = true;
3633         skinframe->qgeneratebase = skinframe->qhascolormapping;
3634         skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
3635
3636         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
3637         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
3638
3639         return skinframe;
3640 }
3641
3642 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
3643 {
3644         int width;
3645         int height;
3646         unsigned char *skindata;
3647
3648         if (!skinframe->qpixels)
3649                 return;
3650
3651         if (!skinframe->qhascolormapping)
3652                 colormapped = false;
3653
3654         if (colormapped)
3655         {
3656                 if (!skinframe->qgeneratebase)
3657                         return;
3658         }
3659         else
3660         {
3661                 if (!skinframe->qgeneratemerged)
3662                         return;
3663         }
3664
3665         width = skinframe->qwidth;
3666         height = skinframe->qheight;
3667         skindata = skinframe->qpixels;
3668
3669         if (skinframe->qgeneratenmap)
3670         {
3671                 unsigned char *temp1, *temp2;
3672                 skinframe->qgeneratenmap = false;
3673                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
3674                 temp2 = temp1 + width * height * 4;
3675                 // use either a custom palette or the quake palette
3676                 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
3677                 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
3678                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (skinframe->textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
3679                 Mem_Free(temp1);
3680         }
3681
3682         if (skinframe->qgenerateglow)
3683         {
3684                 skinframe->qgenerateglow = false;
3685                 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, vid.sRGB3D ? TEXTYPE_SRGB_PALETTE : TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
3686         }
3687
3688         if (colormapped)
3689         {
3690                 skinframe->qgeneratebase = false;
3691                 skinframe->base  = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, vid.sRGB3D ? TEXTYPE_SRGB_PALETTE : TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
3692                 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, vid.sRGB3D ? TEXTYPE_SRGB_PALETTE : TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
3693                 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, vid.sRGB3D ? TEXTYPE_SRGB_PALETTE : TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
3694         }
3695         else
3696         {
3697                 skinframe->qgeneratemerged = false;
3698                 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, vid.sRGB3D ? TEXTYPE_SRGB_PALETTE : TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
3699         }
3700
3701         if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
3702         {
3703                 Mem_Free(skinframe->qpixels);
3704                 skinframe->qpixels = NULL;
3705         }
3706 }
3707
3708 skinframe_t *R_SkinFrame_LoadInternal8bit(const char *name, int textureflags, const unsigned char *skindata, int width, int height, const unsigned int *palette, const unsigned int *alphapalette)
3709 {
3710         int i;
3711         skinframe_t *skinframe;
3712
3713         if (cls.state == ca_dedicated)
3714                 return NULL;
3715
3716         // if already loaded just return it, otherwise make a new skinframe
3717         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
3718         if (skinframe && skinframe->base)
3719                 return skinframe;
3720         textureflags &= ~TEXF_FORCE_RELOAD;
3721
3722         skinframe->stain = NULL;
3723         skinframe->merged = NULL;
3724         skinframe->base = NULL;
3725         skinframe->pants = NULL;
3726         skinframe->shirt = NULL;
3727         skinframe->nmap = NULL;
3728         skinframe->gloss = NULL;
3729         skinframe->glow = NULL;
3730         skinframe->fog = NULL;
3731         skinframe->reflect = NULL;
3732         skinframe->hasalpha = false;
3733
3734         // if no data was provided, then clearly the caller wanted to get a blank skinframe
3735         if (!skindata)
3736                 return NULL;
3737
3738         if (developer_loading.integer)
3739                 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
3740
3741         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
3742         if (textureflags & TEXF_ALPHA)
3743         {
3744                 for (i = 0;i < width * height;i++)
3745                 {
3746                         if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
3747                         {
3748                                 skinframe->hasalpha = true;
3749                                 break;
3750                         }
3751                 }
3752                 if (r_loadfog && skinframe->hasalpha)
3753                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
3754         }
3755
3756         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
3757         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
3758
3759         return skinframe;
3760 }
3761
3762 skinframe_t *R_SkinFrame_LoadMissing(void)
3763 {
3764         skinframe_t *skinframe;
3765
3766         if (cls.state == ca_dedicated)
3767                 return NULL;
3768
3769         skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
3770         skinframe->stain = NULL;
3771         skinframe->merged = NULL;
3772         skinframe->base = NULL;
3773         skinframe->pants = NULL;
3774         skinframe->shirt = NULL;
3775         skinframe->nmap = NULL;
3776         skinframe->gloss = NULL;
3777         skinframe->glow = NULL;
3778         skinframe->fog = NULL;
3779         skinframe->reflect = NULL;
3780         skinframe->hasalpha = false;
3781
3782         skinframe->avgcolor[0] = rand() / RAND_MAX;
3783         skinframe->avgcolor[1] = rand() / RAND_MAX;
3784         skinframe->avgcolor[2] = rand() / RAND_MAX;
3785         skinframe->avgcolor[3] = 1;
3786
3787         return skinframe;
3788 }
3789
3790 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
3791 typedef struct suffixinfo_s
3792 {
3793         const char *suffix;
3794         qboolean flipx, flipy, flipdiagonal;
3795 }
3796 suffixinfo_t;
3797 static suffixinfo_t suffix[3][6] =
3798 {
3799         {
3800                 {"px",   false, false, false},
3801                 {"nx",   false, false, false},
3802                 {"py",   false, false, false},
3803                 {"ny",   false, false, false},
3804                 {"pz",   false, false, false},
3805                 {"nz",   false, false, false}
3806         },
3807         {
3808                 {"posx", false, false, false},
3809                 {"negx", false, false, false},
3810                 {"posy", false, false, false},
3811                 {"negy", false, false, false},
3812                 {"posz", false, false, false},
3813                 {"negz", false, false, false}
3814         },
3815         {
3816                 {"rt",    true, false,  true},
3817                 {"lf",   false,  true,  true},
3818                 {"ft",    true,  true, false},
3819                 {"bk",   false, false, false},
3820                 {"up",    true, false,  true},
3821                 {"dn",    true, false,  true}
3822         }
3823 };
3824
3825 static int componentorder[4] = {0, 1, 2, 3};
3826
3827 rtexture_t *R_LoadCubemap(const char *basename)
3828 {
3829         int i, j, cubemapsize;
3830         unsigned char *cubemappixels, *image_buffer;
3831         rtexture_t *cubemaptexture;
3832         char name[256];
3833         // must start 0 so the first loadimagepixels has no requested width/height
3834         cubemapsize = 0;
3835         cubemappixels = NULL;
3836         cubemaptexture = NULL;
3837         // keep trying different suffix groups (posx, px, rt) until one loads
3838         for (j = 0;j < 3 && !cubemappixels;j++)
3839         {
3840                 // load the 6 images in the suffix group
3841                 for (i = 0;i < 6;i++)
3842                 {
3843                         // generate an image name based on the base and and suffix
3844                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
3845                         // load it
3846                         if ((image_buffer = loadimagepixelsbgra(name, false, false, false, NULL)))
3847                         {
3848                                 // an image loaded, make sure width and height are equal
3849                                 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
3850                                 {
3851                                         // if this is the first image to load successfully, allocate the cubemap memory
3852                                         if (!cubemappixels && image_width >= 1)
3853                                         {
3854                                                 cubemapsize = image_width;
3855                                                 // note this clears to black, so unavailable sides are black
3856                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
3857                                         }
3858                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
3859                                         if (cubemappixels)
3860                                                 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_buffer, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
3861                                 }
3862                                 else
3863                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
3864                                 // free the image
3865                                 Mem_Free(image_buffer);
3866                         }
3867                 }
3868         }
3869         // if a cubemap loaded, upload it
3870         if (cubemappixels)
3871         {
3872                 if (developer_loading.integer)
3873                         Con_Printf("loading cubemap \"%s\"\n", basename);
3874
3875                 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, vid.sRGB3D ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer && gl_texturecompression.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
3876                 Mem_Free(cubemappixels);
3877         }
3878         else
3879         {
3880                 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
3881                 if (developer_loading.integer)
3882                 {
3883                         Con_Printf("(tried tried images ");
3884                         for (j = 0;j < 3;j++)
3885                                 for (i = 0;i < 6;i++)
3886                                         Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
3887                         Con_Print(" and was unable to find any of them).\n");
3888                 }
3889         }
3890         return cubemaptexture;
3891 }
3892
3893 rtexture_t *R_GetCubemap(const char *basename)
3894 {
3895         int i;
3896         for (i = 0;i < r_texture_numcubemaps;i++)
3897                 if (r_texture_cubemaps[i] != NULL)
3898                         if (!strcasecmp(r_texture_cubemaps[i]->basename, basename))
3899                                 return r_texture_cubemaps[i]->texture ? r_texture_cubemaps[i]->texture : r_texture_whitecube;
3900         if (i >= MAX_CUBEMAPS || !r_main_mempool)
3901                 return r_texture_whitecube;
3902         r_texture_numcubemaps++;
3903         r_texture_cubemaps[i] = (cubemapinfo_t *)Mem_Alloc(r_main_mempool, sizeof(cubemapinfo_t));
3904         strlcpy(r_texture_cubemaps[i]->basename, basename, sizeof(r_texture_cubemaps[i]->basename));
3905         r_texture_cubemaps[i]->texture = R_LoadCubemap(r_texture_cubemaps[i]->basename);
3906         return r_texture_cubemaps[i]->texture;
3907 }
3908
3909 void R_FreeCubemap(const char *basename)
3910 {
3911         int i;
3912
3913         for (i = 0;i < r_texture_numcubemaps;i++)
3914         {
3915                 if (r_texture_cubemaps[i] != NULL)
3916                 {
3917                         if (r_texture_cubemaps[i]->texture)
3918                         {
3919                                 if (developer_loading.integer)
3920                                         Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i]->basename);
3921                                 R_FreeTexture(r_texture_cubemaps[i]->texture);
3922                                 Mem_Free(r_texture_cubemaps[i]);
3923                                 r_texture_cubemaps[i] = NULL;
3924                         }
3925                 }
3926         }
3927 }
3928
3929 void R_FreeCubemaps(void)
3930 {
3931         int i;
3932         for (i = 0;i < r_texture_numcubemaps;i++)
3933         {
3934                 if (developer_loading.integer)
3935                         Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i]->basename);
3936                 if (r_texture_cubemaps[i] != NULL)
3937                 {
3938                         if (r_texture_cubemaps[i]->texture)
3939                                 R_FreeTexture(r_texture_cubemaps[i]->texture);
3940                         Mem_Free(r_texture_cubemaps[i]);
3941                 }
3942         }
3943         r_texture_numcubemaps = 0;
3944 }
3945
3946 void R_Main_FreeViewCache(void)
3947 {
3948         if (r_refdef.viewcache.entityvisible)
3949                 Mem_Free(r_refdef.viewcache.entityvisible);
3950         if (r_refdef.viewcache.world_pvsbits)
3951                 Mem_Free(r_refdef.viewcache.world_pvsbits);
3952         if (r_refdef.viewcache.world_leafvisible)
3953                 Mem_Free(r_refdef.viewcache.world_leafvisible);
3954         if (r_refdef.viewcache.world_surfacevisible)
3955                 Mem_Free(r_refdef.viewcache.world_surfacevisible);
3956         memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
3957 }
3958
3959 void R_Main_ResizeViewCache(void)
3960 {
3961         int numentities = r_refdef.scene.numentities;
3962         int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
3963         int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
3964         int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
3965         int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
3966         if (r_refdef.viewcache.maxentities < numentities)
3967         {
3968                 r_refdef.viewcache.maxentities = numentities;
3969                 if (r_refdef.viewcache.entityvisible)
3970                         Mem_Free(r_refdef.viewcache.entityvisible);
3971                 r_refdef.viewcache.entityvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
3972         }
3973         if (r_refdef.viewcache.world_numclusters != numclusters)
3974         {
3975                 r_refdef.viewcache.world_numclusters = numclusters;
3976                 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
3977                 if (r_refdef.viewcache.world_pvsbits)
3978                         Mem_Free(r_refdef.viewcache.world_pvsbits);
3979                 r_refdef.viewcache.world_pvsbits = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
3980         }
3981         if (r_refdef.viewcache.world_numleafs != numleafs)
3982         {
3983                 r_refdef.viewcache.world_numleafs = numleafs;
3984                 if (r_refdef.viewcache.world_leafvisible)
3985                         Mem_Free(r_refdef.viewcache.world_leafvisible);
3986                 r_refdef.viewcache.world_leafvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
3987         }
3988         if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
3989         {
3990                 r_refdef.viewcache.world_numsurfaces = numsurfaces;
3991                 if (r_refdef.viewcache.world_surfacevisible)
3992                         Mem_Free(r_refdef.viewcache.world_surfacevisible);
3993                 r_refdef.viewcache.world_surfacevisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
3994         }
3995 }
3996
3997 extern rtexture_t *loadingscreentexture;
3998 void gl_main_start(void)
3999 {
4000         loadingscreentexture = NULL;
4001         r_texture_blanknormalmap = NULL;
4002         r_texture_white = NULL;
4003         r_texture_grey128 = NULL;
4004         r_texture_black = NULL;
4005         r_texture_whitecube = NULL;
4006         r_texture_normalizationcube = NULL;
4007         r_texture_fogattenuation = NULL;
4008         r_texture_fogheighttexture = NULL;
4009         r_texture_gammaramps = NULL;
4010         r_texture_numcubemaps = 0;
4011
4012         r_loaddds = r_texture_dds_load.integer != 0;
4013         r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
4014
4015         switch(vid.renderpath)
4016         {
4017         case RENDERPATH_GL20:
4018         case RENDERPATH_D3D9:
4019         case RENDERPATH_D3D10:
4020         case RENDERPATH_D3D11:
4021         case RENDERPATH_SOFT:
4022         case RENDERPATH_GLES2:
4023                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
4024                 Cvar_SetValueQuick(&gl_combine, 1);
4025                 Cvar_SetValueQuick(&r_glsl, 1);
4026                 r_loadnormalmap = true;
4027                 r_loadgloss = true;
4028                 r_loadfog = false;
4029                 break;
4030         case RENDERPATH_GL13:
4031         case RENDERPATH_GLES1:
4032                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
4033                 Cvar_SetValueQuick(&gl_combine, 1);
4034                 Cvar_SetValueQuick(&r_glsl, 0);
4035                 r_loadnormalmap = false;
4036                 r_loadgloss = false;
4037                 r_loadfog = true;
4038                 break;
4039         case RENDERPATH_GL11:
4040                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
4041                 Cvar_SetValueQuick(&gl_combine, 0);
4042                 Cvar_SetValueQuick(&r_glsl, 0);
4043                 r_loadnormalmap = false;
4044                 r_loadgloss = false;
4045                 r_loadfog = true;
4046                 break;
4047         }
4048
4049         R_AnimCache_Free();
4050         R_FrameData_Reset();
4051
4052         r_numqueries = 0;
4053         r_maxqueries = 0;
4054         memset(r_queries, 0, sizeof(r_queries));
4055
4056         r_qwskincache = NULL;
4057         r_qwskincache_size = 0;
4058
4059         // due to caching of texture_t references, the collision cache must be reset
4060         Collision_Cache_Reset(true);
4061
4062         // set up r_skinframe loading system for textures
4063         memset(&r_skinframe, 0, sizeof(r_skinframe));
4064         r_skinframe.loadsequence = 1;
4065         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
4066
4067         r_main_texturepool = R_AllocTexturePool();
4068         R_BuildBlankTextures();
4069         R_BuildNoTexture();
4070         if (vid.support.arb_texture_cube_map)
4071         {
4072                 R_BuildWhiteCube();
4073                 R_BuildNormalizationCube();
4074         }
4075         r_texture_fogattenuation = NULL;
4076         r_texture_fogheighttexture = NULL;
4077         r_texture_gammaramps = NULL;
4078         //r_texture_fogintensity = NULL;
4079         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
4080         memset(&r_waterstate, 0, sizeof(r_waterstate));
4081         r_glsl_permutation = NULL;
4082         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4083         Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
4084         glslshaderstring = NULL;
4085 #ifdef SUPPORTD3D
4086         r_hlsl_permutation = NULL;
4087         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
4088         Mem_ExpandableArray_NewArray(&r_hlsl_permutationarray, r_main_mempool, sizeof(r_hlsl_permutation_t), 256);
4089 #endif
4090         hlslshaderstring = NULL;
4091         memset(&r_svbsp, 0, sizeof (r_svbsp));
4092
4093         memset(r_texture_cubemaps, 0, sizeof(r_texture_cubemaps));
4094         r_texture_numcubemaps = 0;
4095
4096         r_refdef.fogmasktable_density = 0;
4097 }
4098
4099 void gl_main_shutdown(void)
4100 {
4101         R_AnimCache_Free();
4102         R_FrameData_Reset();
4103
4104         R_Main_FreeViewCache();
4105
4106         switch(vid.renderpath)
4107         {
4108         case RENDERPATH_GL11:
4109         case RENDERPATH_GL13:
4110         case RENDERPATH_GL20:
4111         case RENDERPATH_GLES1:
4112         case RENDERPATH_GLES2:
4113 #ifdef GL_SAMPLES_PASSED_ARB
4114                 if (r_maxqueries)
4115                         qglDeleteQueriesARB(r_maxqueries, r_queries);
4116 #endif
4117                 break;
4118         case RENDERPATH_D3D9:
4119                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4120                 break;
4121         case RENDERPATH_D3D10:
4122                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4123                 break;
4124         case RENDERPATH_D3D11:
4125                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4126                 break;
4127         case RENDERPATH_SOFT:
4128                 break;
4129         }
4130
4131         r_numqueries = 0;
4132         r_maxqueries = 0;
4133         memset(r_queries, 0, sizeof(r_queries));
4134
4135         r_qwskincache = NULL;
4136         r_qwskincache_size = 0;
4137
4138         // clear out the r_skinframe state
4139         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
4140         memset(&r_skinframe, 0, sizeof(r_skinframe));
4141
4142         if (r_svbsp.nodes)
4143                 Mem_Free(r_svbsp.nodes);
4144         memset(&r_svbsp, 0, sizeof (r_svbsp));
4145         R_FreeTexturePool(&r_main_texturepool);
4146         loadingscreentexture = NULL;
4147         r_texture_blanknormalmap = NULL;
4148         r_texture_white = NULL;
4149         r_texture_grey128 = NULL;
4150         r_texture_black = NULL;
4151         r_texture_whitecube = NULL;
4152         r_texture_normalizationcube = NULL;
4153         r_texture_fogattenuation = NULL;
4154         r_texture_fogheighttexture = NULL;
4155         r_texture_gammaramps = NULL;
4156         r_texture_numcubemaps = 0;
4157         //r_texture_fogintensity = NULL;
4158         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
4159         memset(&r_waterstate, 0, sizeof(r_waterstate));
4160         R_GLSL_Restart_f();
4161
4162         r_glsl_permutation = NULL;
4163         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4164         Mem_ExpandableArray_FreeArray(&r_glsl_permutationarray);
4165         glslshaderstring = NULL;
4166 #ifdef SUPPORTD3D
4167         r_hlsl_permutation = NULL;
4168         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
4169         Mem_ExpandableArray_FreeArray(&r_hlsl_permutationarray);
4170 #endif
4171         hlslshaderstring = NULL;
4172 }
4173
4174 extern void CL_ParseEntityLump(char *entitystring);
4175 void gl_main_newmap(void)
4176 {
4177         // FIXME: move this code to client
4178         char *entities, entname[MAX_QPATH];
4179         if (r_qwskincache)
4180                 Mem_Free(r_qwskincache);
4181         r_qwskincache = NULL;
4182         r_qwskincache_size = 0;
4183         if (cl.worldmodel)
4184         {
4185                 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
4186                 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
4187                 {
4188                         CL_ParseEntityLump(entities);
4189                         Mem_Free(entities);
4190                         return;
4191                 }
4192                 if (cl.worldmodel->brush.entities)
4193                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
4194         }
4195         R_Main_FreeViewCache();
4196
4197         R_FrameData_Reset();
4198 }
4199
4200 void GL_Main_Init(void)
4201 {
4202         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
4203
4204         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
4205         Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
4206         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
4207         if (gamemode == GAME_NEHAHRA)
4208         {
4209                 Cvar_RegisterVariable (&gl_fogenable);
4210                 Cvar_RegisterVariable (&gl_fogdensity);
4211                 Cvar_RegisterVariable (&gl_fogred);
4212                 Cvar_RegisterVariable (&gl_foggreen);
4213                 Cvar_RegisterVariable (&gl_fogblue);
4214                 Cvar_RegisterVariable (&gl_fogstart);
4215                 Cvar_RegisterVariable (&gl_fogend);
4216                 Cvar_RegisterVariable (&gl_skyclip);
4217         }
4218         Cvar_RegisterVariable(&r_motionblur);
4219         Cvar_RegisterVariable(&r_damageblur);
4220         Cvar_RegisterVariable(&r_motionblur_averaging);
4221         Cvar_RegisterVariable(&r_motionblur_randomize);
4222         Cvar_RegisterVariable(&r_motionblur_minblur);
4223         Cvar_RegisterVariable(&r_motionblur_maxblur);
4224         Cvar_RegisterVariable(&r_motionblur_velocityfactor);
4225         Cvar_RegisterVariable(&r_motionblur_velocityfactor_minspeed);
4226         Cvar_RegisterVariable(&r_motionblur_velocityfactor_maxspeed);
4227         Cvar_RegisterVariable(&r_motionblur_mousefactor);
4228         Cvar_RegisterVariable(&r_motionblur_mousefactor_minspeed);
4229         Cvar_RegisterVariable(&r_motionblur_mousefactor_maxspeed);
4230         Cvar_RegisterVariable(&r_equalize_entities_fullbright);
4231         Cvar_RegisterVariable(&r_equalize_entities_minambient);
4232         Cvar_RegisterVariable(&r_equalize_entities_by);
4233         Cvar_RegisterVariable(&r_equalize_entities_to);
4234         Cvar_RegisterVariable(&r_depthfirst);
4235         Cvar_RegisterVariable(&r_useinfinitefarclip);
4236         Cvar_RegisterVariable(&r_farclip_base);
4237         Cvar_RegisterVariable(&r_farclip_world);
4238         Cvar_RegisterVariable(&r_nearclip);
4239         Cvar_RegisterVariable(&r_deformvertexes);
4240         Cvar_RegisterVariable(&r_transparent);
4241         Cvar_RegisterVariable(&r_transparent_alphatocoverage);
4242         Cvar_RegisterVariable(&r_showoverdraw);
4243         Cvar_RegisterVariable(&r_showbboxes);
4244         Cvar_RegisterVariable(&r_showsurfaces);
4245         Cvar_RegisterVariable(&r_showtris);
4246         Cvar_RegisterVariable(&r_shownormals);
4247         Cvar_RegisterVariable(&r_showlighting);
4248         Cvar_RegisterVariable(&r_showshadowvolumes);
4249         Cvar_RegisterVariable(&r_showcollisionbrushes);
4250         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
4251         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
4252         Cvar_RegisterVariable(&r_showdisabledepthtest);
4253         Cvar_RegisterVariable(&r_drawportals);
4254         Cvar_RegisterVariable(&r_drawentities);
4255         Cvar_RegisterVariable(&r_draw2d);
4256         Cvar_RegisterVariable(&r_drawworld);
4257         Cvar_RegisterVariable(&r_cullentities_trace);
4258         Cvar_RegisterVariable(&r_cullentities_trace_samples);
4259         Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
4260         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
4261         Cvar_RegisterVariable(&r_cullentities_trace_delay);
4262         Cvar_RegisterVariable(&r_sortentities);
4263         Cvar_RegisterVariable(&r_drawviewmodel);
4264         Cvar_RegisterVariable(&r_drawexteriormodel);
4265         Cvar_RegisterVariable(&r_speeds);
4266         Cvar_RegisterVariable(&r_fullbrights);
4267         Cvar_RegisterVariable(&r_wateralpha);
4268         Cvar_RegisterVariable(&r_dynamic);
4269         Cvar_RegisterVariable(&r_fakelight);
4270         Cvar_RegisterVariable(&r_fakelight_intensity);
4271         Cvar_RegisterVariable(&r_fullbright);
4272         Cvar_RegisterVariable(&r_shadows);
4273         Cvar_RegisterVariable(&r_shadows_darken);
4274         Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
4275         Cvar_RegisterVariable(&r_shadows_castfrombmodels);
4276         Cvar_RegisterVariable(&r_shadows_throwdistance);
4277         Cvar_RegisterVariable(&r_shadows_throwdirection);
4278         Cvar_RegisterVariable(&r_shadows_focus);
4279         Cvar_RegisterVariable(&r_shadows_shadowmapscale);
4280         Cvar_RegisterVariable(&r_q1bsp_skymasking);
4281         Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
4282         Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
4283         Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
4284         Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
4285         Cvar_RegisterVariable(&r_fog_exp2);
4286         Cvar_RegisterVariable(&r_fog_clear);
4287         Cvar_RegisterVariable(&r_drawfog);
4288         Cvar_RegisterVariable(&r_transparentdepthmasking);
4289         Cvar_RegisterVariable(&r_transparent_sortmindist);
4290         Cvar_RegisterVariable(&r_transparent_sortmaxdist);
4291         Cvar_RegisterVariable(&r_transparent_sortarraysize);
4292         Cvar_RegisterVariable(&r_texture_dds_load);
4293         Cvar_RegisterVariable(&r_texture_dds_save);
4294         Cvar_RegisterVariable(&r_textureunits);
4295         Cvar_RegisterVariable(&gl_combine);
4296         Cvar_RegisterVariable(&r_viewfbo);
4297         Cvar_RegisterVariable(&r_viewscale);
4298         Cvar_RegisterVariable(&r_viewscale_fpsscaling);
4299         Cvar_RegisterVariable(&r_viewscale_fpsscaling_min);
4300         Cvar_RegisterVariable(&r_viewscale_fpsscaling_multiply);
4301         Cvar_RegisterVariable(&r_viewscale_fpsscaling_stepsize);
4302         Cvar_RegisterVariable(&r_viewscale_fpsscaling_stepmax);
4303         Cvar_RegisterVariable(&r_viewscale_fpsscaling_target);
4304         Cvar_RegisterVariable(&r_glsl);
4305         Cvar_RegisterVariable(&r_glsl_deluxemapping);
4306         Cvar_RegisterVariable(&r_glsl_offsetmapping);
4307         Cvar_RegisterVariable(&r_glsl_offsetmapping_steps);
4308         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
4309         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping_steps);
4310         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping_refinesteps);
4311         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
4312         Cvar_RegisterVariable(&r_glsl_offsetmapping_lod);
4313         Cvar_RegisterVariable(&r_glsl_offsetmapping_lod_distance);
4314         Cvar_RegisterVariable(&r_glsl_postprocess);
4315         Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
4316         Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
4317         Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
4318         Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
4319         Cvar_RegisterVariable(&r_glsl_postprocess_uservec1_enable);
4320         Cvar_RegisterVariable(&r_glsl_postprocess_uservec2_enable);
4321         Cvar_RegisterVariable(&r_glsl_postprocess_uservec3_enable);
4322         Cvar_RegisterVariable(&r_glsl_postprocess_uservec4_enable);
4323
4324         Cvar_RegisterVariable(&r_water);
4325         Cvar_RegisterVariable(&r_water_resolutionmultiplier);
4326         Cvar_RegisterVariable(&r_water_clippingplanebias);
4327         Cvar_RegisterVariable(&r_water_refractdistort);
4328         Cvar_RegisterVariable(&r_water_reflectdistort);
4329         Cvar_RegisterVariable(&r_water_scissormode);
4330         Cvar_RegisterVariable(&r_water_lowquality);
4331
4332         Cvar_RegisterVariable(&r_lerpsprites);
4333         Cvar_RegisterVariable(&r_lerpmodels);
4334         Cvar_RegisterVariable(&r_lerplightstyles);
4335         Cvar_RegisterVariable(&r_waterscroll);
4336         Cvar_RegisterVariable(&r_bloom);
4337         Cvar_RegisterVariable(&r_bloom_colorscale);
4338         Cvar_RegisterVariable(&r_bloom_brighten);
4339         Cvar_RegisterVariable(&r_bloom_blur);
4340         Cvar_RegisterVariable(&r_bloom_resolution);
4341         Cvar_RegisterVariable(&r_bloom_colorexponent);
4342         Cvar_RegisterVariable(&r_bloom_colorsubtract);
4343         Cvar_RegisterVariable(&r_hdr);
4344         Cvar_RegisterVariable(&r_hdr_scenebrightness);
4345         Cvar_RegisterVariable(&r_hdr_glowintensity);
4346         Cvar_RegisterVariable(&r_hdr_range);
4347         Cvar_RegisterVariable(&r_hdr_irisadaptation);
4348         Cvar_RegisterVariable(&r_hdr_irisadaptation_multiplier);
4349         Cvar_RegisterVariable(&r_hdr_irisadaptation_minvalue);
4350         Cvar_RegisterVariable(&r_hdr_irisadaptation_maxvalue);
4351         Cvar_RegisterVariable(&r_hdr_irisadaptation_value);
4352         Cvar_RegisterVariable(&r_hdr_irisadaptation_fade_up);
4353         Cvar_RegisterVariable(&r_hdr_irisadaptation_fade_down);
4354         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
4355         Cvar_RegisterVariable(&developer_texturelogging);
4356         Cvar_RegisterVariable(&gl_lightmaps);
4357         Cvar_RegisterVariable(&r_test);
4358         Cvar_RegisterVariable(&r_glsl_saturation);
4359         Cvar_RegisterVariable(&r_glsl_saturation_redcompensate);
4360         Cvar_RegisterVariable(&r_glsl_vertextextureblend_usebothalphas);
4361         Cvar_RegisterVariable(&r_framedatasize);
4362         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
4363                 Cvar_SetValue("r_fullbrights", 0);
4364         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
4365 }
4366
4367 extern void R_Textures_Init(void);
4368 extern void GL_Draw_Init(void);
4369 extern void GL_Main_Init(void);
4370 extern void R_Shadow_Init(void);
4371 extern void R_Sky_Init(void);
4372 extern void GL_Surf_Init(void);
4373 extern void R_Particles_Init(void);
4374 extern void R_Explosion_Init(void);
4375 extern void gl_backend_init(void);
4376 extern void Sbar_Init(void);
4377 extern void R_LightningBeams_Init(void);
4378 extern void Mod_RenderInit(void);
4379 extern void Font_Init(void);
4380
4381 void Render_Init(void)
4382 {
4383         gl_backend_init();
4384         R_Textures_Init();
4385         GL_Main_Init();
4386         Font_Init();
4387         GL_Draw_Init();
4388         R_Shadow_Init();
4389         R_Sky_Init();
4390         GL_Surf_Init();
4391         Sbar_Init();
4392         R_Particles_Init();
4393         R_Explosion_Init();
4394         R_LightningBeams_Init();
4395         Mod_RenderInit();
4396 }
4397
4398 /*
4399 ===============
4400 GL_Init
4401 ===============
4402 */
4403 #ifndef USE_GLES2
4404 extern char *ENGINE_EXTENSIONS;
4405 void GL_Init (void)
4406 {
4407         gl_renderer = (const char *)qglGetString(GL_RENDERER);
4408         gl_vendor = (const char *)qglGetString(GL_VENDOR);
4409         gl_version = (const char *)qglGetString(GL_VERSION);
4410         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
4411
4412         if (!gl_extensions)
4413                 gl_extensions = "";
4414         if (!gl_platformextensions)
4415                 gl_platformextensions = "";
4416
4417         Con_Printf("GL_VENDOR: %s\n", gl_vendor);
4418         Con_Printf("GL_RENDERER: %s\n", gl_renderer);
4419         Con_Printf("GL_VERSION: %s\n", gl_version);
4420         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
4421         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
4422
4423         VID_CheckExtensions();
4424
4425         // LordHavoc: report supported extensions
4426         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
4427
4428         // clear to black (loading plaque will be seen over this)
4429         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
4430 }
4431 #endif
4432
4433 int R_CullBox(const vec3_t mins, const vec3_t maxs)
4434 {
4435         int i;
4436         mplane_t *p;
4437         if (r_trippy.integer)
4438                 return false;
4439         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
4440         {
4441                 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
4442                 if (i == 4)
4443                         continue;
4444                 p = r_refdef.view.frustum + i;
4445                 switch(p->signbits)
4446                 {
4447                 default:
4448                 case 0:
4449                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
4450                                 return true;
4451                         break;
4452                 case 1:
4453                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
4454                                 return true;
4455                         break;
4456                 case 2:
4457                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
4458                                 return true;
4459                         break;
4460                 case 3:
4461                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
4462                                 return true;
4463                         break;
4464                 case 4:
4465                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
4466                                 return true;
4467                         break;
4468                 case 5:
4469                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
4470                                 return true;
4471                         break;
4472                 case 6:
4473                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
4474                                 return true;
4475                         break;
4476                 case 7:
4477                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
4478                                 return true;
4479                         break;
4480                 }
4481         }
4482         return false;
4483 }
4484
4485 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
4486 {
4487         int i;
4488         const mplane_t *p;
4489         if (r_trippy.integer)
4490                 return false;
4491         for (i = 0;i < numplanes;i++)
4492         {
4493                 p = planes + i;
4494                 switch(p->signbits)
4495                 {
4496                 default:
4497                 case 0:
4498                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
4499                                 return true;
4500                         break;
4501                 case 1:
4502                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
4503                                 return true;
4504                         break;
4505                 case 2:
4506                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
4507                                 return true;
4508                         break;
4509                 case 3:
4510                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
4511                                 return true;
4512                         break;
4513                 case 4:
4514                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
4515                                 return true;
4516                         break;
4517                 case 5:
4518                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
4519                                 return true;
4520                         break;
4521                 case 6:
4522                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
4523                                 return true;
4524                         break;
4525                 case 7:
4526                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
4527                                 return true;
4528                         break;
4529                 }
4530         }
4531         return false;
4532 }
4533
4534 //==================================================================================
4535
4536 // LordHavoc: this stores temporary data used within the same frame
4537
4538 typedef struct r_framedata_mem_s
4539 {
4540         struct r_framedata_mem_s *purge; // older mem block to free on next frame
4541         size_t size; // how much usable space
4542         size_t current; // how much space in use
4543         size_t mark; // last "mark" location, temporary memory can be freed by returning to this
4544         size_t wantedsize; // how much space was allocated
4545         unsigned char *data; // start of real data (16byte aligned)
4546 }
4547 r_framedata_mem_t;
4548
4549 static r_framedata_mem_t *r_framedata_mem;
4550
4551 void R_FrameData_Reset(void)
4552 {
4553         while (r_framedata_mem)
4554         {
4555                 r_framedata_mem_t *next = r_framedata_mem->purge;
4556                 Mem_Free(r_framedata_mem);
4557                 r_framedata_mem = next;
4558         }
4559 }
4560
4561 void R_FrameData_Resize(void)
4562 {
4563         size_t wantedsize;
4564         wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
4565         wantedsize = bound(65536, wantedsize, 1000*1024*1024);
4566         if (!r_framedata_mem || r_framedata_mem->wantedsize != wantedsize)
4567         {
4568                 r_framedata_mem_t *newmem = (r_framedata_mem_t *)Mem_Alloc(r_main_mempool, wantedsize);
4569                 newmem->wantedsize = wantedsize;
4570                 newmem->data = (unsigned char *)(((size_t)(newmem+1) + 15) & ~15);
4571                 newmem->size = (unsigned char *)newmem + wantedsize - newmem->data;
4572                 newmem->current = 0;
4573                 newmem->mark = 0;
4574                 newmem->purge = r_framedata_mem;
4575                 r_framedata_mem = newmem;
4576         }
4577 }
4578
4579 void R_FrameData_NewFrame(void)
4580 {
4581         R_FrameData_Resize();
4582         if (!r_framedata_mem)
4583                 return;
4584         // if we ran out of space on the last frame, free the old memory now
4585         while (r_framedata_mem->purge)
4586         {
4587                 // repeatedly remove the second item in the list, leaving only head
4588                 r_framedata_mem_t *next = r_framedata_mem->purge->purge;
4589                 Mem_Free(r_framedata_mem->purge);
4590                 r_framedata_mem->purge = next;
4591         }
4592         // reset the current mem pointer
4593         r_framedata_mem->current = 0;
4594         r_framedata_mem->mark = 0;
4595 }
4596
4597 void *R_FrameData_Alloc(size_t size)
4598 {
4599         void *data;
4600
4601         // align to 16 byte boundary - the data pointer is already aligned, so we
4602         // only need to ensure the size of every allocation is also aligned
4603         size = (size + 15) & ~15;
4604
4605         while (!r_framedata_mem || r_framedata_mem->current + size > r_framedata_mem->size)
4606         {
4607                 // emergency - we ran out of space, allocate more memory
4608                 Cvar_SetValueQuick(&r_framedatasize, bound(0.25f, r_framedatasize.value * 2.0f, 128.0f));
4609                 R_FrameData_Resize();
4610         }
4611
4612         data = r_framedata_mem->data + r_framedata_mem->current;
4613         r_framedata_mem->current += size;
4614
4615         // count the usage for stats
4616         r_refdef.stats.framedatacurrent = max(r_refdef.stats.framedatacurrent, (int)r_framedata_mem->current);
4617         r_refdef.stats.framedatasize = max(r_refdef.stats.framedatasize, (int)r_framedata_mem->size);
4618
4619         return (void *)data;
4620 }
4621
4622 void *R_FrameData_Store(size_t size, void *data)
4623 {
4624         void *d = R_FrameData_Alloc(size);
4625         if (d && data)
4626                 memcpy(d, data, size);
4627         return d;
4628 }
4629
4630 void R_FrameData_SetMark(void)
4631 {
4632         if (!r_framedata_mem)
4633                 return;
4634         r_framedata_mem->mark = r_framedata_mem->current;
4635 }
4636
4637 void R_FrameData_ReturnToMark(void)
4638 {
4639         if (!r_framedata_mem)
4640                 return;
4641         r_framedata_mem->current = r_framedata_mem->mark;
4642 }
4643
4644 //==================================================================================
4645
4646 // LordHavoc: animcache originally written by Echon, rewritten since then
4647
4648 /**
4649  * Animation cache prevents re-generating mesh data for an animated model
4650  * multiple times in one frame for lighting, shadowing, reflections, etc.
4651  */
4652
4653 void R_AnimCache_Free(void)
4654 {
4655 }
4656
4657 void R_AnimCache_ClearCache(void)
4658 {
4659         int i;
4660         entity_render_t *ent;
4661
4662         for (i = 0;i < r_refdef.scene.numentities;i++)
4663         {
4664                 ent = r_refdef.scene.entities[i];
4665                 ent->animcache_vertex3f = NULL;
4666                 ent->animcache_normal3f = NULL;
4667                 ent->animcache_svector3f = NULL;
4668                 ent->animcache_tvector3f = NULL;
4669                 ent->animcache_vertexmesh = NULL;
4670                 ent->animcache_vertex3fbuffer = NULL;
4671                 ent->animcache_vertexmeshbuffer = NULL;
4672         }
4673 }
4674
4675 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
4676 {
4677         int i;
4678
4679         // check if we need the meshbuffers
4680         if (!vid.useinterleavedarrays)
4681                 return;
4682
4683         if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
4684                 ent->animcache_vertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
4685         // TODO: upload vertex3f buffer?
4686         if (ent->animcache_vertexmesh)
4687         {
4688                 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
4689                 for (i = 0;i < numvertices;i++)
4690                         memcpy(ent->animcache_vertexmesh[i].vertex3f, ent->animcache_vertex3f + 3*i, sizeof(float[3]));
4691                 if (ent->animcache_svector3f)
4692                         for (i = 0;i < numvertices;i++)
4693                                 memcpy(ent->animcache_vertexmesh[i].svector3f, ent->animcache_svector3f + 3*i, sizeof(float[3]));
4694                 if (ent->animcache_tvector3f)
4695                         for (i = 0;i < numvertices;i++)
4696                                 memcpy(ent->animcache_vertexmesh[i].tvector3f, ent->animcache_tvector3f + 3*i, sizeof(float[3]));
4697                 if (ent->animcache_normal3f)
4698                         for (i = 0;i < numvertices;i++)
4699                                 memcpy(ent->animcache_vertexmesh[i].normal3f, ent->animcache_normal3f + 3*i, sizeof(float[3]));
4700                 // TODO: upload vertexmeshbuffer?
4701         }
4702 }
4703
4704 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
4705 {
4706         dp_model_t *model = ent->model;
4707         int numvertices;
4708         // see if it's already cached this frame
4709         if (ent->animcache_vertex3f)
4710         {
4711                 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
4712                 if (wantnormals || wanttangents)
4713                 {
4714                         if (ent->animcache_normal3f)
4715                                 wantnormals = false;
4716                         if (ent->animcache_svector3f)
4717                                 wanttangents = false;
4718                         if (wantnormals || wanttangents)
4719                         {
4720                                 numvertices = model->surfmesh.num_vertices;
4721                                 if (wantnormals)
4722                                         ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
4723                                 if (wanttangents)
4724                                 {
4725                                         ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
4726                                         ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
4727                                 }
4728                                 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
4729                                 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
4730                         }
4731                 }
4732         }
4733         else
4734         {
4735                 // see if this ent is worth caching
4736                 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices)
4737                         return false;
4738                 // get some memory for this entity and generate mesh data
4739                 numvertices = model->surfmesh.num_vertices;
4740                 ent->animcache_vertex3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
4741                 if (wantnormals)
4742                         ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
4743                 if (wanttangents)
4744                 {
4745                         ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
4746                         ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
4747                 }
4748                 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
4749                 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
4750         }
4751         return true;
4752 }
4753
4754 void R_AnimCache_CacheVisibleEntities(void)
4755 {
4756         int i;
4757         qboolean wantnormals = true;
4758         qboolean wanttangents = !r_showsurfaces.integer;
4759
4760         switch(vid.renderpath)
4761         {
4762         case RENDERPATH_GL20:
4763         case RENDERPATH_D3D9:
4764         case RENDERPATH_D3D10:
4765         case RENDERPATH_D3D11:
4766         case RENDERPATH_GLES2:
4767                 break;
4768         case RENDERPATH_GL11:
4769         case RENDERPATH_GL13:
4770         case RENDERPATH_GLES1:
4771                 wanttangents = false;
4772                 break;
4773         case RENDERPATH_SOFT:
4774                 break;
4775         }
4776
4777         if (r_shownormals.integer)
4778                 wanttangents = wantnormals = true;
4779
4780         // TODO: thread this
4781         // NOTE: R_PrepareRTLights() also caches entities
4782
4783         for (i = 0;i < r_refdef.scene.numentities;i++)
4784                 if (r_refdef.viewcache.entityvisible[i])
4785                         R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
4786 }
4787
4788 //==================================================================================
4789
4790 extern cvar_t r_overheadsprites_pushback;
4791
4792 static void R_View_UpdateEntityLighting (void)
4793 {
4794         int i;
4795         entity_render_t *ent;
4796         vec3_t tempdiffusenormal, avg;
4797         vec_t f, fa, fd, fdd;
4798         qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
4799
4800         for (i = 0;i < r_refdef.scene.numentities;i++)
4801         {
4802                 ent = r_refdef.scene.entities[i];
4803
4804                 // skip unseen models and models that updated by CSQC
4805                 if ((!r_refdef.viewcache.entityvisible[i] && skipunseen) || ent->flags & RENDER_CUSTOMIZEDMODELLIGHT)
4806                         continue;
4807
4808                 // skip bsp models
4809                 if (ent->model && ent->model->brush.num_leafs)
4810                 {
4811                         // TODO: use modellight for r_ambient settings on world?
4812                         VectorSet(ent->modellight_ambient, 0, 0, 0);
4813                         VectorSet(ent->modellight_diffuse, 0, 0, 0);
4814                         VectorSet(ent->modellight_lightdir, 0, 0, 1);
4815                         continue;
4816                 }
4817
4818                 // fetch the lighting from the worldmodel data
4819                 VectorClear(ent->modellight_ambient);
4820                 VectorClear(ent->modellight_diffuse);
4821                 VectorClear(tempdiffusenormal);
4822                 if (ent->flags & RENDER_LIGHT)
4823                 {
4824                         vec3_t org;
4825                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4826
4827                         // complete lightning for lit sprites
4828                         // todo: make a EF_ field so small ents could be lit purely by modellight and skipping real rtlight pass (like EF_NORTLIGHT)?
4829                         if (ent->model->type == mod_sprite && !(ent->model->data_textures[0].basematerialflags & MATERIALFLAG_FULLBRIGHT))
4830                         {
4831                                 if (ent->model->sprite.sprnum_type == SPR_OVERHEAD) // apply offset for overhead sprites
4832                                         org[2] = org[2] + r_overheadsprites_pushback.value;
4833                                 R_LightPoint(ent->modellight_ambient, org, LP_LIGHTMAP | LP_RTWORLD | LP_DYNLIGHT);
4834                         }
4835                         else
4836                                 R_CompleteLightPoint(ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal, org, LP_LIGHTMAP);
4837
4838                         if(ent->flags & RENDER_EQUALIZE)
4839                         {
4840                                 // first fix up ambient lighting...
4841                                 if(r_equalize_entities_minambient.value > 0)
4842                                 {
4843                                         fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
4844                                         if(fd > 0)
4845                                         {
4846                                                 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
4847                                                 if(fa < r_equalize_entities_minambient.value * fd)
4848                                                 {
4849                                                         // solve:
4850                                                         //   fa'/fd' = minambient
4851                                                         //   fa'+0.25*fd' = fa+0.25*fd
4852                                                         //   ...
4853                                                         //   fa' = fd' * minambient
4854                                                         //   fd'*(0.25+minambient) = fa+0.25*fd
4855                                                         //   ...
4856                                                         //   fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
4857                                                         //   fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
4858                                                         //   ...
4859                                                         fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
4860                                                         f = fdd / fd; // f>0 because all this is additive; f<1 because fdd<fd because this follows from fa < r_equalize_entities_minambient.value * fd
4861                                                         VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
4862                                                         VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
4863                                                 }
4864                                         }
4865                                 }
4866
4867                                 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
4868                                 {
4869                                         fa = 0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2];
4870                                         fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
4871                                         f = fa + 0.25 * fd;
4872                                         if(f > 0)
4873                                         {
4874                                                 // adjust brightness and saturation to target
4875                                                 avg[0] = avg[1] = avg[2] = fa / f;
4876                                                 VectorLerp(ent->modellight_ambient, r_equalize_entities_by.value, avg, ent->modellight_ambient);
4877                                                 avg[0] = avg[1] = avg[2] = fd / f;
4878                                                 VectorLerp(ent->modellight_diffuse, r_equalize_entities_by.value, avg, ent->modellight_diffuse);
4879                                         }
4880                                 }
4881                         }
4882                 }
4883                 else // highly rare
4884                         VectorSet(ent->modellight_ambient, 1, 1, 1);
4885
4886                 // move the light direction into modelspace coordinates for lighting code
4887                 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
4888                 if(VectorLength2(ent->modellight_lightdir) == 0)
4889                         VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
4890                 VectorNormalize(ent->modellight_lightdir);
4891         }
4892 }
4893
4894 #define MAX_LINEOFSIGHTTRACES 64
4895
4896 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
4897 {
4898         int i;
4899         vec3_t boxmins, boxmaxs;
4900         vec3_t start;
4901         vec3_t end;
4902         dp_model_t *model = r_refdef.scene.worldmodel;
4903
4904         if (!model || !model->brush.TraceLineOfSight)
4905                 return true;
4906
4907         // expand the box a little
4908         boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
4909         boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
4910         boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
4911         boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
4912         boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
4913         boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
4914
4915         // return true if eye is inside enlarged box
4916         if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
4917                 return true;
4918
4919         // try center
4920         VectorCopy(eye, start);
4921         VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
4922         if (model->brush.TraceLineOfSight(model, start, end))
4923                 return true;
4924
4925         // try various random positions
4926         for (i = 0;i < numsamples;i++)
4927         {
4928                 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
4929                 if (model->brush.TraceLineOfSight(model, start, end))
4930                         return true;
4931         }
4932
4933         return false;
4934 }
4935
4936
4937 static void R_View_UpdateEntityVisible (void)
4938 {
4939         int i;
4940         int renderimask;
4941         int samples;
4942         entity_render_t *ent;
4943
4944         renderimask = r_refdef.envmap                                    ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
4945                 : r_waterstate.renderingrefraction                       ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
4946                 : (chase_active.integer || r_waterstate.renderingscene)  ? RENDER_VIEWMODEL
4947                 :                                                          RENDER_EXTERIORMODEL;
4948         if (!r_drawviewmodel.integer)
4949                 renderimask |= RENDER_VIEWMODEL;
4950         if (!r_drawexteriormodel.integer)
4951                 renderimask |= RENDER_EXTERIORMODEL;
4952         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
4953         {
4954                 // worldmodel can check visibility
4955                 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
4956                 for (i = 0;i < r_refdef.scene.numentities;i++)
4957                 {
4958                         ent = r_refdef.scene.entities[i];
4959                         if (!(ent->flags & renderimask))
4960                         if (!R_CullBox(ent->mins, ent->maxs) || (ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
4961                         if ((ent->flags & (RENDER_NODEPTHTEST | RENDER_WORLDOBJECT | RENDER_VIEWMODEL)) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs))
4962                                 r_refdef.viewcache.entityvisible[i] = true;
4963                 }
4964         }
4965         else
4966         {
4967                 // no worldmodel or it can't check visibility
4968                 for (i = 0;i < r_refdef.scene.numentities;i++)
4969                 {
4970                         ent = r_refdef.scene.entities[i];
4971                         r_refdef.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));
4972                 }
4973         }
4974         if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane && !r_trippy.integer)
4975                 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
4976         {
4977                 for (i = 0;i < r_refdef.scene.numentities;i++)
4978                 {
4979                         if (!r_refdef.viewcache.entityvisible[i])
4980                                 continue;
4981                         ent = r_refdef.scene.entities[i];
4982                         if(!(ent->flags & (RENDER_VIEWMODEL | RENDER_WORLDOBJECT | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
4983                         {
4984                                 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
4985                                 if (samples < 0)
4986                                         continue; // temp entities do pvs only
4987                                 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
4988                                         ent->last_trace_visibility = realtime;
4989                                 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
4990                                         r_refdef.viewcache.entityvisible[i] = 0;
4991                         }
4992                 }
4993         }
4994 }
4995
4996 /// only used if skyrendermasked, and normally returns false
4997 int R_DrawBrushModelsSky (void)
4998 {
4999         int i, sky;
5000         entity_render_t *ent;
5001
5002         sky = false;
5003         for (i = 0;i < r_refdef.scene.numentities;i++)
5004         {
5005                 if (!r_refdef.viewcache.entityvisible[i])
5006                         continue;
5007                 ent = r_refdef.scene.entities[i];
5008                 if (!ent->model || !ent->model->DrawSky)
5009                         continue;
5010                 ent->model->DrawSky(ent);
5011                 sky = true;
5012         }
5013         return sky;
5014 }
5015
5016 static void R_DrawNoModel(entity_render_t *ent);
5017 static void R_DrawModels(void)
5018 {
5019         int i;
5020         entity_render_t *ent;
5021
5022         for (i = 0;i < r_refdef.scene.numentities;i++)
5023         {
5024                 if (!r_refdef.viewcache.entityvisible[i])
5025                         continue;
5026                 ent = r_refdef.scene.entities[i];
5027                 r_refdef.stats.entities++;
5028                 /*
5029                 if (ent->model && !strncmp(ent->model->name, "models/proto_", 13))
5030                 {
5031                         vec3_t f, l, u, o;
5032                         Matrix4x4_ToVectors(&ent->matrix, f, l, u, o);
5033                         Con_Printf("R_DrawModels\n");
5034                         Con_Printf("model %s O %f %f %f F %f %f %f L %f %f %f U %f %f %f\n", ent->model->name, o[0], o[1], o[2], f[0], f[1], f[2], l[0], l[1], l[2], u[0], u[1], u[2]);
5035                         Con_Printf("group: %i %f %i %f %i %f %i %f\n", ent->framegroupblend[0].frame, ent->framegroupblend[0].lerp, ent->framegroupblend[1].frame, ent->framegroupblend[1].lerp, ent->framegroupblend[2].frame, ent->framegroupblend[2].lerp, ent->framegroupblend[3].frame, ent->framegroupblend[3].lerp);
5036                         Con_Printf("blend: %i %f %i %f %i %f %i %f %i %f %i %f %i %f %i %f\n", ent->frameblend[0].subframe, ent->frameblend[0].lerp, ent->frameblend[1].subframe, ent->frameblend[1].lerp, ent->frameblend[2].subframe, ent->frameblend[2].lerp, ent->frameblend[3].subframe, ent->frameblend[3].lerp, ent->frameblend[4].subframe, ent->frameblend[4].lerp, ent->frameblend[5].subframe, ent->frameblend[5].lerp, ent->frameblend[6].subframe, ent->frameblend[6].lerp, ent->frameblend[7].subframe, ent->frameblend[7].lerp);
5037                 }
5038                 */
5039                 if (ent->model && ent->model->Draw != NULL)
5040                         ent->model->Draw(ent);
5041                 else
5042                         R_DrawNoModel(ent);
5043         }
5044 }
5045
5046 static void R_DrawModelsDepth(void)
5047 {
5048         int i;
5049         entity_render_t *ent;
5050
5051         for (i = 0;i < r_refdef.scene.numentities;i++)
5052         {
5053                 if (!r_refdef.viewcache.entityvisible[i])
5054                         continue;
5055                 ent = r_refdef.scene.entities[i];
5056                 if (ent->model && ent->model->DrawDepth != NULL)
5057                         ent->model->DrawDepth(ent);
5058         }
5059 }
5060
5061 static void R_DrawModelsDebug(void)
5062 {
5063         int i;
5064         entity_render_t *ent;
5065
5066         for (i = 0;i < r_refdef.scene.numentities;i++)
5067         {
5068                 if (!r_refdef.viewcache.entityvisible[i])
5069                         continue;
5070                 ent = r_refdef.scene.entities[i];
5071                 if (ent->model && ent->model->DrawDebug != NULL)
5072                         ent->model->DrawDebug(ent);
5073         }
5074 }
5075
5076 static void R_DrawModelsAddWaterPlanes(void)
5077 {
5078         int i;
5079         entity_render_t *ent;
5080
5081         for (i = 0;i < r_refdef.scene.numentities;i++)
5082         {
5083                 if (!r_refdef.viewcache.entityvisible[i])
5084                         continue;
5085                 ent = r_refdef.scene.entities[i];
5086                 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
5087                         ent->model->DrawAddWaterPlanes(ent);
5088         }
5089 }
5090
5091 void R_HDR_UpdateIrisAdaptation(const vec3_t point)
5092 {
5093         if (r_hdr_irisadaptation.integer)
5094         {
5095                 vec3_t ambient;
5096                 vec3_t diffuse;
5097                 vec3_t diffusenormal;
5098                 vec_t brightness;
5099                 vec_t goal;
5100                 vec_t current;
5101                 R_CompleteLightPoint(ambient, diffuse, diffusenormal, point, LP_LIGHTMAP | LP_RTWORLD | LP_DYNLIGHT);
5102                 brightness = (ambient[0] + ambient[1] + ambient[2] + diffuse[0] + diffuse[1] + diffuse[2]) * (1.0f / 3.0f);
5103                 brightness = max(0.0000001f, brightness);
5104                 goal = r_hdr_irisadaptation_multiplier.value / brightness;
5105                 goal = bound(r_hdr_irisadaptation_minvalue.value, goal, r_hdr_irisadaptation_maxvalue.value);
5106                 current = r_hdr_irisadaptation_value.value;
5107                 if (current < goal)
5108                         current = min(current + r_hdr_irisadaptation_fade_up.value * cl.realframetime, goal);
5109                 else if (current > goal)
5110                         current = max(current - r_hdr_irisadaptation_fade_down.value * cl.realframetime, goal);
5111                 if (fabs(r_hdr_irisadaptation_value.value - current) > 0.0001f)
5112                         Cvar_SetValueQuick(&r_hdr_irisadaptation_value, current);
5113         }
5114         else if (r_hdr_irisadaptation_value.value != 1.0f)
5115                 Cvar_SetValueQuick(&r_hdr_irisadaptation_value, 1.0f);
5116 }
5117
5118 static void R_View_SetFrustum(const int *scissor)
5119 {
5120         int i;
5121         double fpx = +1, fnx = -1, fpy = +1, fny = -1;
5122         vec3_t forward, left, up, origin, v;
5123
5124         if(scissor)
5125         {
5126                 // flipped x coordinates (because x points left here)
5127                 fpx =  1.0 - 2.0 * (scissor[0]              - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
5128                 fnx =  1.0 - 2.0 * (scissor[0] + scissor[2] - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
5129
5130                 // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
5131                 switch(vid.renderpath)
5132                 {
5133                         case RENDERPATH_D3D9:
5134                         case RENDERPATH_D3D10:
5135                         case RENDERPATH_D3D11:
5136                                 // non-flipped y coordinates
5137                                 fny = -1.0 + 2.0 * (vid.height - scissor[1] - scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
5138                                 fpy = -1.0 + 2.0 * (vid.height - scissor[1]              - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
5139                                 break;
5140                         case RENDERPATH_SOFT:
5141                         case RENDERPATH_GL11:
5142                         case RENDERPATH_GL13:
5143                         case RENDERPATH_GL20:
5144                         case RENDERPATH_GLES1:
5145                         case RENDERPATH_GLES2:
5146                                 // non-flipped y coordinates
5147                                 fny = -1.0 + 2.0 * (scissor[1]              - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
5148                                 fpy = -1.0 + 2.0 * (scissor[1] + scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
5149                                 break;
5150                 }
5151         }
5152
5153         // we can't trust r_refdef.view.forward and friends in reflected scenes
5154         Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
5155
5156 #if 0
5157         r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
5158         r_refdef.view.frustum[0].normal[1] = 0 - 0;
5159         r_refdef.view.frustum[0].normal[2] = -1 - 0;
5160         r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
5161         r_refdef.view.frustum[1].normal[1] = 0 + 0;
5162         r_refdef.view.frustum[1].normal[2] = -1 + 0;
5163         r_refdef.view.frustum[2].normal[0] = 0 - 0;
5164         r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
5165         r_refdef.view.frustum[2].normal[2] = -1 - 0;
5166         r_refdef.view.frustum[3].normal[0] = 0 + 0;
5167         r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
5168         r_refdef.view.frustum[3].normal[2] = -1 + 0;
5169 #endif
5170
5171 #if 0
5172         zNear = r_refdef.nearclip;
5173         nudge = 1.0 - 1.0 / (1<<23);
5174         r_refdef.view.frustum[4].normal[0] = 0 - 0;
5175         r_refdef.view.frustum[4].normal[1] = 0 - 0;
5176         r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
5177         r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
5178         r_refdef.view.frustum[5].normal[0] = 0 + 0;
5179         r_refdef.view.frustum[5].normal[1] = 0 + 0;
5180         r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
5181         r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
5182 #endif
5183
5184
5185
5186 #if 0
5187         r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
5188         r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
5189         r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
5190         r_refdef.view.frustum[0].dist = m[15] - m[12];
5191
5192         r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
5193         r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
5194         r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
5195         r_refdef.view.frustum[1].dist = m[15] + m[12];
5196
5197         r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
5198         r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
5199         r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
5200         r_refdef.view.frustum[2].dist = m[15] - m[13];
5201
5202         r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
5203         r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
5204         r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
5205         r_refdef.view.frustum[3].dist = m[15] + m[13];
5206
5207         r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
5208         r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
5209         r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
5210         r_refdef.view.frustum[4].dist = m[15] - m[14];
5211
5212         r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
5213         r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
5214         r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
5215         r_refdef.view.frustum[5].dist = m[15] + m[14];
5216 #endif
5217
5218         if (r_refdef.view.useperspective)
5219         {
5220                 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
5221                 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[0]);
5222                 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[1]);
5223                 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[2]);
5224                 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[3]);
5225
5226                 // then the normals from the corners relative to origin
5227                 CrossProduct(r_refdef.view.frustumcorner[2], r_refdef.view.frustumcorner[0], r_refdef.view.frustum[0].normal);
5228                 CrossProduct(r_refdef.view.frustumcorner[1], r_refdef.view.frustumcorner[3], r_refdef.view.frustum[1].normal);
5229                 CrossProduct(r_refdef.view.frustumcorner[0], r_refdef.view.frustumcorner[1], r_refdef.view.frustum[2].normal);
5230                 CrossProduct(r_refdef.view.frustumcorner[3], r_refdef.view.frustumcorner[2], r_refdef.view.frustum[3].normal);
5231
5232                 // in a NORMAL view, forward cross left == up
5233                 // in a REFLECTED view, forward cross left == down
5234                 // so our cross products above need to be adjusted for a left handed coordinate system
5235                 CrossProduct(forward, left, v);
5236                 if(DotProduct(v, up) < 0)
5237                 {
5238                         VectorNegate(r_refdef.view.frustum[0].normal, r_refdef.view.frustum[0].normal);
5239                         VectorNegate(r_refdef.view.frustum[1].normal, r_refdef.view.frustum[1].normal);
5240                         VectorNegate(r_refdef.view.frustum[2].normal, r_refdef.view.frustum[2].normal);
5241                         VectorNegate(r_refdef.view.frustum[3].normal, r_refdef.view.frustum[3].normal);
5242                 }
5243
5244                 // Leaving those out was a mistake, those were in the old code, and they
5245                 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
5246                 // I couldn't reproduce it after adding those normalizations. --blub
5247                 VectorNormalize(r_refdef.view.frustum[0].normal);
5248                 VectorNormalize(r_refdef.view.frustum[1].normal);
5249                 VectorNormalize(r_refdef.view.frustum[2].normal);
5250                 VectorNormalize(r_refdef.view.frustum[3].normal);
5251
5252                 // make the corners absolute
5253                 VectorAdd(r_refdef.view.frustumcorner[0], r_refdef.view.origin, r_refdef.view.frustumcorner[0]);
5254                 VectorAdd(r_refdef.view.frustumcorner[1], r_refdef.view.origin, r_refdef.view.frustumcorner[1]);
5255                 VectorAdd(r_refdef.view.frustumcorner[2], r_refdef.view.origin, r_refdef.view.frustumcorner[2]);
5256                 VectorAdd(r_refdef.view.frustumcorner[3], r_refdef.view.origin, r_refdef.view.frustumcorner[3]);
5257
5258                 // one more normal
5259                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
5260
5261                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
5262                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
5263                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
5264                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
5265                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
5266         }
5267         else
5268         {
5269                 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
5270                 VectorScale(left,  r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
5271                 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
5272                 VectorScale(up,  r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
5273                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
5274                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
5275                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
5276                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
5277                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
5278                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
5279         }
5280         r_refdef.view.numfrustumplanes = 5;
5281
5282         if (r_refdef.view.useclipplane)
5283         {
5284                 r_refdef.view.numfrustumplanes = 6;
5285                 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
5286         }
5287
5288         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
5289                 PlaneClassify(r_refdef.view.frustum + i);
5290
5291         // LordHavoc: note to all quake engine coders, Quake had a special case
5292         // for 90 degrees which assumed a square view (wrong), so I removed it,
5293         // Quake2 has it disabled as well.
5294
5295         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
5296         //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
5297         //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
5298         //PlaneClassify(&frustum[0]);
5299
5300         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
5301         //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
5302         //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
5303         //PlaneClassify(&frustum[1]);
5304
5305         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
5306         //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
5307         //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
5308         //PlaneClassify(&frustum[2]);
5309
5310         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
5311         //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
5312         //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
5313         //PlaneClassify(&frustum[3]);
5314
5315         // nearclip plane
5316         //VectorCopy(forward, r_refdef.view.frustum[4].normal);
5317         //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
5318         //PlaneClassify(&frustum[4]);
5319 }
5320
5321 void R_View_UpdateWithScissor(const int *myscissor)
5322 {
5323         R_Main_ResizeViewCache();
5324         R_View_SetFrustum(myscissor);
5325         R_View_WorldVisibility(r_refdef.view.useclipplane);
5326         R_View_UpdateEntityVisible();
5327         R_View_UpdateEntityLighting();
5328 }
5329
5330 void R_View_Update(void)
5331 {
5332         R_Main_ResizeViewCache();
5333         R_View_SetFrustum(NULL);
5334         R_View_WorldVisibility(r_refdef.view.useclipplane);
5335         R_View_UpdateEntityVisible();
5336         R_View_UpdateEntityLighting();
5337 }
5338
5339 float viewscalefpsadjusted = 1.0f;
5340
5341 void R_GetScaledViewSize(int width, int height, int *outwidth, int *outheight)
5342 {
5343         float scale = r_viewscale.value * sqrt(viewscalefpsadjusted);
5344         scale = bound(0.03125f, scale, 1.0f);
5345         *outwidth = (int)ceil(width * scale);
5346         *outheight = (int)ceil(height * scale);
5347 }
5348
5349 void R_Mesh_SetMainRenderTargets(void)
5350 {
5351         if (r_bloomstate.fbo_framebuffer)
5352                 R_Mesh_SetRenderTargets(r_bloomstate.fbo_framebuffer, r_bloomstate.texture_framebufferdepth, r_bloomstate.texture_framebuffercolor, NULL, NULL, NULL);
5353         else
5354                 R_Mesh_ResetRenderTargets();
5355 }
5356
5357 void R_SetupView(qboolean allowwaterclippingplane)
5358 {
5359         const float *customclipplane = NULL;
5360         float plane[4];
5361         int scaledwidth, scaledheight;
5362         if (r_refdef.view.useclipplane && allowwaterclippingplane)
5363         {
5364                 // LordHavoc: couldn't figure out how to make this approach the
5365                 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
5366                 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
5367                 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
5368                         dist = r_refdef.view.clipplane.dist;
5369                 plane[0] = r_refdef.view.clipplane.normal[0];
5370                 plane[1] = r_refdef.view.clipplane.normal[1];
5371                 plane[2] = r_refdef.view.clipplane.normal[2];
5372                 plane[3] = -dist;
5373                 if(vid.renderpath != RENDERPATH_SOFT) customclipplane = plane;
5374         }
5375
5376         R_GetScaledViewSize(r_refdef.view.width, r_refdef.view.height, &scaledwidth, &scaledheight);
5377         if (!r_refdef.view.useperspective)
5378                 R_Viewport_InitOrtho(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - scaledheight - r_refdef.view.y, scaledwidth, scaledheight, -r_refdef.view.ortho_x, -r_refdef.view.ortho_y, r_refdef.view.ortho_x, r_refdef.view.ortho_y, -r_refdef.farclip, r_refdef.farclip, customclipplane);
5379         else if (vid.stencil && r_useinfinitefarclip.integer)
5380                 R_Viewport_InitPerspectiveInfinite(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - scaledheight - r_refdef.view.y, scaledwidth, scaledheight, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, customclipplane);
5381         else
5382                 R_Viewport_InitPerspective(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - scaledheight - r_refdef.view.y, scaledwidth, scaledheight, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, r_refdef.farclip, customclipplane);
5383         R_Mesh_SetMainRenderTargets();
5384         R_SetViewport(&r_refdef.view.viewport);
5385         if (r_refdef.view.useclipplane && allowwaterclippingplane && vid.renderpath == RENDERPATH_SOFT)
5386         {
5387                 matrix4x4_t mvpmatrix, invmvpmatrix, invtransmvpmatrix;
5388                 float screenplane[4];
5389                 Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
5390                 Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
5391                 Matrix4x4_Transpose(&invtransmvpmatrix, &invmvpmatrix);
5392                 Matrix4x4_Transform4(&invtransmvpmatrix, plane, screenplane);
5393                 DPSOFTRAST_ClipPlane(screenplane[0], screenplane[1], screenplane[2], screenplane[3]);
5394         }
5395 }
5396
5397 void R_EntityMatrix(const matrix4x4_t *matrix)
5398 {
5399         if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
5400         {
5401                 gl_modelmatrixchanged = false;
5402                 gl_modelmatrix = *matrix;
5403                 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
5404                 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
5405                 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
5406                 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
5407                 CHECKGLERROR
5408                 switch(vid.renderpath)
5409                 {
5410                 case RENDERPATH_D3D9:
5411 #ifdef SUPPORTD3D
5412                         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
5413                         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
5414 #endif
5415                         break;
5416                 case RENDERPATH_D3D10:
5417                         Con_DPrintf("FIXME D3D10 shader %s:%i\n", __FILE__, __LINE__);
5418                         break;
5419                 case RENDERPATH_D3D11:
5420                         Con_DPrintf("FIXME D3D11 shader %s:%i\n", __FILE__, __LINE__);
5421                         break;
5422                 case RENDERPATH_GL11:
5423                 case RENDERPATH_GL13:
5424                 case RENDERPATH_GLES1:
5425                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
5426                         break;
5427                 case RENDERPATH_SOFT:
5428                         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1, 1, false, gl_modelviewprojection16f);
5429                         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewMatrixM1, 1, false, gl_modelview16f);
5430                         break;
5431                 case RENDERPATH_GL20:
5432                 case RENDERPATH_GLES2:
5433                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
5434                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
5435                         break;
5436                 }
5437         }
5438 }
5439
5440 void R_ResetViewRendering2D(void)
5441 {
5442         r_viewport_t viewport;
5443         DrawQ_Finish();
5444
5445         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
5446         R_Viewport_InitOrtho(&viewport, &identitymatrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, 0, 0, 1, 1, -10, 100, NULL);
5447         R_Mesh_ResetRenderTargets();
5448         R_SetViewport(&viewport);
5449         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
5450         GL_Color(1, 1, 1, 1);
5451         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5452         GL_BlendFunc(GL_ONE, GL_ZERO);
5453         GL_ScissorTest(false);
5454         GL_DepthMask(false);
5455         GL_DepthRange(0, 1);
5456         GL_DepthTest(false);
5457         GL_DepthFunc(GL_LEQUAL);
5458         R_EntityMatrix(&identitymatrix);
5459         R_Mesh_ResetTextureState();
5460         GL_PolygonOffset(0, 0);
5461         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
5462         switch(vid.renderpath)
5463         {
5464         case RENDERPATH_GL11:
5465         case RENDERPATH_GL13:
5466         case RENDERPATH_GL20:
5467         case RENDERPATH_GLES1:
5468         case RENDERPATH_GLES2:
5469                 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
5470                 break;
5471         case RENDERPATH_D3D9:
5472         case RENDERPATH_D3D10:
5473         case RENDERPATH_D3D11:
5474         case RENDERPATH_SOFT:
5475                 break;
5476         }
5477         GL_CullFace(GL_NONE);
5478 }
5479
5480 void R_ResetViewRendering3D(void)
5481 {
5482         DrawQ_Finish();
5483
5484         R_SetupView(true);
5485         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
5486         GL_Color(1, 1, 1, 1);
5487         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5488         GL_BlendFunc(GL_ONE, GL_ZERO);
5489         GL_ScissorTest(true);
5490         GL_DepthMask(true);
5491         GL_DepthRange(0, 1);
5492         GL_DepthTest(true);
5493         GL_DepthFunc(GL_LEQUAL);
5494         R_EntityMatrix(&identitymatrix);
5495         R_Mesh_ResetTextureState();
5496         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
5497         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
5498         switch(vid.renderpath)
5499         {
5500         case RENDERPATH_GL11:
5501         case RENDERPATH_GL13:
5502         case RENDERPATH_GL20:
5503         case RENDERPATH_GLES1:
5504         case RENDERPATH_GLES2:
5505                 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
5506                 break;
5507         case RENDERPATH_D3D9:
5508         case RENDERPATH_D3D10:
5509         case RENDERPATH_D3D11:
5510         case RENDERPATH_SOFT:
5511                 break;
5512         }
5513         GL_CullFace(r_refdef.view.cullface_back);
5514 }
5515
5516 /*
5517 ================
5518 R_RenderView_UpdateViewVectors
5519 ================
5520 */
5521 static void R_RenderView_UpdateViewVectors(void)
5522 {
5523         // break apart the view matrix into vectors for various purposes
5524         // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
5525         // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
5526         Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
5527         VectorNegate(r_refdef.view.left, r_refdef.view.right);
5528         // make an inverted copy of the view matrix for tracking sprites
5529         Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
5530 }
5531
5532 void R_RenderScene(void);
5533 void R_RenderWaterPlanes(void);
5534
5535 static void R_Water_StartFrame(void)
5536 {
5537         int i;
5538         int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
5539         r_waterstate_waterplane_t *p;
5540
5541         if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
5542                 return;
5543
5544         switch(vid.renderpath)
5545         {
5546         case RENDERPATH_GL20:
5547         case RENDERPATH_D3D9:
5548         case RENDERPATH_D3D10:
5549         case RENDERPATH_D3D11:
5550         case RENDERPATH_SOFT:
5551         case RENDERPATH_GLES2:
5552                 break;
5553         case RENDERPATH_GL11:
5554         case RENDERPATH_GL13:
5555         case RENDERPATH_GLES1:
5556                 return;
5557         }
5558
5559         // set waterwidth and waterheight to the water resolution that will be
5560         // used (often less than the screen resolution for faster rendering)
5561         R_GetScaledViewSize(bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width), bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height), &waterwidth, &waterheight);
5562
5563         // calculate desired texture sizes
5564         // can't use water if the card does not support the texture size
5565         if (!r_water.integer || r_showsurfaces.integer)
5566                 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
5567         else if (vid.support.arb_texture_non_power_of_two)
5568         {
5569                 texturewidth = waterwidth;
5570                 textureheight = waterheight;
5571                 camerawidth = waterwidth;
5572                 cameraheight = waterheight;
5573         }
5574         else
5575         {
5576                 for (texturewidth   = 1;texturewidth   < waterwidth ;texturewidth   *= 2);
5577                 for (textureheight  = 1;textureheight  < waterheight;textureheight  *= 2);
5578                 for (camerawidth    = 1;camerawidth   <= waterwidth; camerawidth    *= 2); camerawidth  /= 2;
5579                 for (cameraheight   = 1;cameraheight  <= waterheight;cameraheight   *= 2); cameraheight /= 2;
5580         }
5581
5582         // allocate textures as needed
5583         if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
5584         {
5585                 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
5586                 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
5587                 {
5588                         if (p->texture_refraction)
5589                                 R_FreeTexture(p->texture_refraction);
5590                         p->texture_refraction = NULL;
5591                         if (p->texture_reflection)
5592                                 R_FreeTexture(p->texture_reflection);
5593                         p->texture_reflection = NULL;
5594                         if (p->texture_camera)
5595                                 R_FreeTexture(p->texture_camera);
5596                         p->texture_camera = NULL;
5597                 }
5598                 memset(&r_waterstate, 0, sizeof(r_waterstate));
5599                 r_waterstate.texturewidth = texturewidth;
5600                 r_waterstate.textureheight = textureheight;
5601                 r_waterstate.camerawidth = camerawidth;
5602                 r_waterstate.cameraheight = cameraheight;
5603         }
5604
5605         if (r_waterstate.texturewidth)
5606         {
5607                 int scaledwidth, scaledheight;
5608
5609                 r_waterstate.enabled = true;
5610
5611                 // when doing a reduced render (HDR) we want to use a smaller area
5612                 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
5613                 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
5614                 R_GetScaledViewSize(r_waterstate.waterwidth, r_waterstate.waterheight, &scaledwidth, &scaledheight);
5615
5616                 // set up variables that will be used in shader setup
5617                 r_waterstate.screenscale[0] = 0.5f * (float)scaledwidth / (float)r_waterstate.texturewidth;
5618                 r_waterstate.screenscale[1] = 0.5f * (float)scaledheight / (float)r_waterstate.textureheight;
5619                 r_waterstate.screencenter[0] = 0.5f * (float)scaledwidth / (float)r_waterstate.texturewidth;
5620                 r_waterstate.screencenter[1] = 0.5f * (float)scaledheight / (float)r_waterstate.textureheight;
5621         }
5622
5623         r_waterstate.maxwaterplanes = MAX_WATERPLANES;
5624         r_waterstate.numwaterplanes = 0;
5625 }
5626
5627 void R_Water_AddWaterPlane(msurface_t *surface, int entno)
5628 {
5629         int triangleindex, planeindex;
5630         const int *e;
5631         vec3_t vert[3];
5632         vec3_t normal;
5633         vec3_t center;
5634         mplane_t plane;
5635         r_waterstate_waterplane_t *p;
5636         texture_t *t = R_GetCurrentTexture(surface->texture);
5637
5638         // just use the first triangle with a valid normal for any decisions
5639         VectorClear(normal);
5640         for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
5641         {
5642                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
5643                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
5644                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
5645                 TriangleNormal(vert[0], vert[1], vert[2], normal);
5646                 if (VectorLength2(normal) >= 0.001)
5647                         break;
5648         }
5649
5650         VectorCopy(normal, plane.normal);
5651         VectorNormalize(plane.normal);
5652         plane.dist = DotProduct(vert[0], plane.normal);
5653         PlaneClassify(&plane);
5654         if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
5655         {
5656                 // skip backfaces (except if nocullface is set)
5657                 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
5658                         return;
5659                 VectorNegate(plane.normal, plane.normal);
5660                 plane.dist *= -1;
5661                 PlaneClassify(&plane);
5662         }
5663
5664
5665         // find a matching plane if there is one
5666         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
5667                 if(p->camera_entity == t->camera_entity)
5668                         if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
5669                                 break;
5670         if (planeindex >= r_waterstate.maxwaterplanes)
5671                 return; // nothing we can do, out of planes
5672
5673         // if this triangle does not fit any known plane rendered this frame, add one
5674         if (planeindex >= r_waterstate.numwaterplanes)
5675         {
5676                 // store the new plane
5677                 r_waterstate.numwaterplanes++;
5678                 p->plane = plane;
5679                 // clear materialflags and pvs
5680                 p->materialflags = 0;
5681                 p->pvsvalid = false;
5682                 p->camera_entity = t->camera_entity;
5683                 VectorCopy(surface->mins, p->mins);
5684                 VectorCopy(surface->maxs, p->maxs);
5685         }
5686         else
5687         {
5688                 // merge mins/maxs
5689                 p->mins[0] = min(p->mins[0], surface->mins[0]);
5690                 p->mins[1] = min(p->mins[1], surface->mins[1]);
5691                 p->mins[2] = min(p->mins[2], surface->mins[2]);
5692                 p->maxs[0] = max(p->maxs[0], surface->maxs[0]);
5693                 p->maxs[1] = max(p->maxs[1], surface->maxs[1]);
5694                 p->maxs[2] = max(p->maxs[2], surface->maxs[2]);
5695         }
5696         // merge this surface's materialflags into the waterplane
5697         p->materialflags |= t->currentmaterialflags;
5698         if(!(p->materialflags & MATERIALFLAG_CAMERA))
5699         {
5700                 // merge this surface's PVS into the waterplane
5701                 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
5702                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
5703                  && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
5704                 {
5705                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
5706                         p->pvsvalid = true;
5707                 }
5708         }
5709 }
5710
5711 extern cvar_t r_drawparticles;
5712 extern cvar_t r_drawdecals;
5713
5714 static void R_Water_ProcessPlanes(void)
5715 {
5716         int myscissor[4];
5717         r_refdef_view_t originalview;
5718         r_refdef_view_t myview;
5719         int planeindex, qualityreduction = 0, old_r_dynamic = 0, old_r_shadows = 0, old_r_worldrtlight = 0, old_r_dlight = 0, old_r_particles = 0, old_r_decals = 0;
5720         r_waterstate_waterplane_t *p;
5721         vec3_t visorigin;
5722
5723         originalview = r_refdef.view;
5724
5725         // lowquality hack, temporarily shut down some cvars and restore afterwards
5726         qualityreduction = r_water_lowquality.integer;
5727         if (qualityreduction > 0)
5728         {
5729                 if (qualityreduction >= 1)
5730                 {
5731                         old_r_shadows = r_shadows.integer;
5732                         old_r_worldrtlight = r_shadow_realtime_world.integer;
5733                         old_r_dlight = r_shadow_realtime_dlight.integer;
5734                         Cvar_SetValueQuick(&r_shadows, 0);
5735                         Cvar_SetValueQuick(&r_shadow_realtime_world, 0);
5736                         Cvar_SetValueQuick(&r_shadow_realtime_dlight, 0);
5737                 }
5738                 if (qualityreduction >= 2)
5739                 {
5740                         old_r_dynamic = r_dynamic.integer;
5741                         old_r_particles = r_drawparticles.integer;
5742                         old_r_decals = r_drawdecals.integer;
5743                         Cvar_SetValueQuick(&r_dynamic, 0);
5744                         Cvar_SetValueQuick(&r_drawparticles, 0);
5745                         Cvar_SetValueQuick(&r_drawdecals, 0);
5746                 }
5747         }
5748
5749         // make sure enough textures are allocated
5750         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
5751         {
5752                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
5753                 {
5754                         if (!p->texture_refraction)
5755                                 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
5756                         if (!p->texture_refraction)
5757                                 goto error;
5758                 }
5759                 else if (p->materialflags & MATERIALFLAG_CAMERA)
5760                 {
5761                         if (!p->texture_camera)
5762                                 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR, -1, NULL);
5763                         if (!p->texture_camera)
5764                                 goto error;
5765                 }
5766
5767                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
5768                 {
5769                         if (!p->texture_reflection)
5770                                 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
5771                         if (!p->texture_reflection)
5772                                 goto error;
5773                 }
5774         }
5775
5776         // render views
5777         r_refdef.view = originalview;
5778         r_refdef.view.showdebug = false;
5779         r_refdef.view.width = r_waterstate.waterwidth;
5780         r_refdef.view.height = r_waterstate.waterheight;
5781         r_refdef.view.useclipplane = true;
5782         myview = r_refdef.view;
5783         r_waterstate.renderingscene = true;
5784         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
5785         {
5786                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
5787                 {
5788                         r_refdef.view = myview;
5789                         if(r_water_scissormode.integer)
5790                         {
5791                                 R_SetupView(true);
5792                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
5793                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
5794                         }
5795
5796                         // render reflected scene and copy into texture
5797                         Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
5798                         // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
5799                         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
5800                         r_refdef.view.clipplane = p->plane;
5801                         // reverse the cullface settings for this render
5802                         r_refdef.view.cullface_front = GL_FRONT;
5803                         r_refdef.view.cullface_back = GL_BACK;
5804                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
5805                         {
5806                                 r_refdef.view.usecustompvs = true;
5807                                 if (p->pvsvalid)
5808                                         memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
5809                                 else
5810                                         memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
5811                         }
5812
5813                         R_ResetViewRendering3D();
5814                         R_ClearScreen(r_refdef.fogenabled);
5815                         if(r_water_scissormode.integer & 2)
5816                                 R_View_UpdateWithScissor(myscissor);
5817                         else
5818                                 R_View_Update();
5819                         if(r_water_scissormode.integer & 1)
5820                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
5821                         R_RenderScene();
5822
5823                         R_Mesh_CopyToTexture(p->texture_reflection, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
5824                 }
5825
5826                 // render the normal view scene and copy into texture
5827                 // (except that a clipping plane should be used to hide everything on one side of the water, and the viewer's weapon model should be omitted)
5828                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
5829                 {
5830                         r_refdef.view = myview;
5831                         if(r_water_scissormode.integer)
5832                         {
5833                                 R_SetupView(true);
5834                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
5835                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
5836                         }
5837
5838                         r_waterstate.renderingrefraction = true;
5839
5840                         r_refdef.view.clipplane = p->plane;
5841                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
5842                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
5843
5844                         if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
5845                         {
5846                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
5847                                 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
5848                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
5849                                 R_RenderView_UpdateViewVectors();
5850                                 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
5851                                 {
5852                                         r_refdef.view.usecustompvs = true;
5853                                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
5854                                 }
5855                         }
5856
5857                         PlaneClassify(&r_refdef.view.clipplane);
5858
5859                         R_ResetViewRendering3D();
5860                         R_ClearScreen(r_refdef.fogenabled);
5861                         if(r_water_scissormode.integer & 2)
5862                                 R_View_UpdateWithScissor(myscissor);
5863                         else
5864                                 R_View_Update();
5865                         if(r_water_scissormode.integer & 1)
5866                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
5867                         R_RenderScene();
5868
5869                         R_Mesh_CopyToTexture(p->texture_refraction, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
5870                         r_waterstate.renderingrefraction = false;
5871                 }
5872                 else if (p->materialflags & MATERIALFLAG_CAMERA)
5873                 {
5874                         r_refdef.view = myview;
5875
5876                         r_refdef.view.clipplane = p->plane;
5877                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
5878                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
5879
5880                         r_refdef.view.width = r_waterstate.camerawidth;
5881                         r_refdef.view.height = r_waterstate.cameraheight;
5882                         r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
5883                         r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
5884
5885                         if(p->camera_entity)
5886                         {
5887                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
5888                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
5889                         }
5890
5891                         // note: all of the view is used for displaying... so
5892                         // there is no use in scissoring
5893
5894                         // reverse the cullface settings for this render
5895                         r_refdef.view.cullface_front = GL_FRONT;
5896                         r_refdef.view.cullface_back = GL_BACK;
5897                         // also reverse the view matrix
5898                         Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, 1, -1); // this serves to invert texcoords in the result, as the copied texture is mapped the wrong way round
5899                         R_RenderView_UpdateViewVectors();
5900                         if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
5901                         {
5902                                 r_refdef.view.usecustompvs = true;
5903                                 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
5904                         }
5905                         
5906                         // camera needs no clipplane
5907                         r_refdef.view.useclipplane = false;
5908
5909                         PlaneClassify(&r_refdef.view.clipplane);
5910
5911                         R_ResetViewRendering3D();
5912                         R_ClearScreen(r_refdef.fogenabled);
5913                         R_View_Update();
5914                         R_RenderScene();
5915
5916                         R_Mesh_CopyToTexture(p->texture_camera, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
5917                         r_waterstate.renderingrefraction = false;
5918                 }
5919
5920         }
5921         if(vid.renderpath==RENDERPATH_SOFT) DPSOFTRAST_ClipPlane(0, 0, 0, 1);
5922         r_waterstate.renderingscene = false;
5923         r_refdef.view = originalview;
5924         R_ResetViewRendering3D();
5925         R_ClearScreen(r_refdef.fogenabled);
5926         R_View_Update();
5927         goto finish;
5928 error:
5929         r_refdef.view = originalview;
5930         r_waterstate.renderingscene = false;
5931         Cvar_SetValueQuick(&r_water, 0);
5932         Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed!  Turned off r_water.\n");
5933 finish:
5934         // lowquality hack, restore cvars
5935         if (qualityreduction > 0)
5936         {
5937                 if (qualityreduction >= 1)
5938                 {
5939                         Cvar_SetValueQuick(&r_shadows, old_r_shadows);
5940                         Cvar_SetValueQuick(&r_shadow_realtime_world, old_r_worldrtlight);
5941                         Cvar_SetValueQuick(&r_shadow_realtime_dlight, old_r_dlight);
5942                 }
5943                 if (qualityreduction >= 2)
5944                 {
5945                         Cvar_SetValueQuick(&r_dynamic, old_r_dynamic);
5946                         Cvar_SetValueQuick(&r_drawparticles, old_r_particles);
5947                         Cvar_SetValueQuick(&r_drawdecals, old_r_decals);
5948                 }
5949         }
5950 }
5951
5952 void R_Bloom_StartFrame(void)
5953 {
5954         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
5955         int viewwidth, viewheight;
5956         textype_t textype;
5957
5958         if (r_viewscale_fpsscaling.integer)
5959         {
5960                 double actualframetime;
5961                 double targetframetime;
5962                 double adjust;
5963                 actualframetime = r_refdef.lastdrawscreentime;
5964                 targetframetime = (1.0 / r_viewscale_fpsscaling_target.value);
5965                 adjust = (targetframetime - actualframetime) * r_viewscale_fpsscaling_multiply.value;
5966                 adjust = bound(-r_viewscale_fpsscaling_stepmax.value, adjust, r_viewscale_fpsscaling_stepmax.value);
5967                 if (r_viewscale_fpsscaling_stepsize.value > 0)
5968                         adjust = (int)(adjust / r_viewscale_fpsscaling_stepsize.value) * r_viewscale_fpsscaling_stepsize.value;
5969                 viewscalefpsadjusted += adjust;
5970                 viewscalefpsadjusted = bound(r_viewscale_fpsscaling_min.value, viewscalefpsadjusted, 1.0f);
5971         }
5972         else
5973                 viewscalefpsadjusted = 1.0f;
5974
5975         R_GetScaledViewSize(r_refdef.view.width, r_refdef.view.height, &viewwidth, &viewheight);
5976
5977         switch(vid.renderpath)
5978         {
5979         case RENDERPATH_GL20:
5980         case RENDERPATH_D3D9:
5981         case RENDERPATH_D3D10:
5982         case RENDERPATH_D3D11:
5983         case RENDERPATH_SOFT:
5984         case RENDERPATH_GLES2:
5985                 break;
5986         case RENDERPATH_GL11:
5987         case RENDERPATH_GL13:
5988         case RENDERPATH_GLES1:
5989                 return;
5990         }
5991
5992         // set bloomwidth and bloomheight to the bloom resolution that will be
5993         // used (often less than the screen resolution for faster rendering)
5994         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
5995         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
5996         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
5997         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
5998         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
5999
6000         // calculate desired texture sizes
6001         if (vid.support.arb_texture_non_power_of_two)
6002         {
6003                 screentexturewidth = vid.width;
6004                 screentextureheight = vid.height;
6005                 bloomtexturewidth = r_bloomstate.bloomwidth;
6006                 bloomtextureheight = r_bloomstate.bloomheight;
6007         }
6008         else
6009         {
6010                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
6011                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
6012                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
6013                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
6014         }
6015
6016         if ((r_hdr.integer || r_bloom.integer || (!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))) && ((r_bloom_resolution.integer < 4 || r_bloom_blur.value < 1 || r_bloom_blur.value >= 512) || r_refdef.view.width > (int)vid.maxtexturesize_2d || r_refdef.view.height > (int)vid.maxtexturesize_2d))
6017         {
6018                 Cvar_SetValueQuick(&r_hdr, 0);
6019                 Cvar_SetValueQuick(&r_bloom, 0);
6020                 Cvar_SetValueQuick(&r_motionblur, 0);
6021                 Cvar_SetValueQuick(&r_damageblur, 0);
6022         }
6023
6024         if (!(r_glsl_postprocess.integer || (!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) || (v_glslgamma.integer && !vid_gammatables_trivial)) && !r_bloom.integer && !r_hdr.integer && (R_Stereo_Active() || (r_motionblur.value <= 0 && r_damageblur.value <= 0)) && r_viewfbo.integer < 1 && r_viewscale.value == 1.0f && !r_viewscale_fpsscaling.integer)
6025                 screentexturewidth = screentextureheight = 0;
6026         if (!r_hdr.integer && !r_bloom.integer)
6027                 bloomtexturewidth = bloomtextureheight = 0;
6028
6029         textype = TEXTYPE_COLORBUFFER;
6030         switch (vid.renderpath)
6031         {
6032         case RENDERPATH_GL20:
6033         case RENDERPATH_GLES2:
6034                 if (vid.support.ext_framebuffer_object)
6035                 {
6036                         if (r_viewfbo.integer == 2) textype = TEXTYPE_COLORBUFFER16F;
6037                         if (r_viewfbo.integer == 3) textype = TEXTYPE_COLORBUFFER32F;
6038                 }
6039                 break;
6040         case RENDERPATH_GL11:
6041         case RENDERPATH_GL13:
6042         case RENDERPATH_GLES1:
6043         case RENDERPATH_D3D9:
6044         case RENDERPATH_D3D10:
6045         case RENDERPATH_D3D11:
6046         case RENDERPATH_SOFT:
6047                 break;
6048         }
6049
6050         // allocate textures as needed
6051         if (r_bloomstate.screentexturewidth != screentexturewidth
6052          || r_bloomstate.screentextureheight != screentextureheight
6053          || r_bloomstate.bloomtexturewidth != bloomtexturewidth
6054          || r_bloomstate.bloomtextureheight != bloomtextureheight
6055          || r_bloomstate.texturetype != textype
6056          || r_bloomstate.viewfbo != r_viewfbo.integer)
6057         {
6058                 if (r_bloomstate.texture_bloom)
6059                         R_FreeTexture(r_bloomstate.texture_bloom);
6060                 r_bloomstate.texture_bloom = NULL;
6061                 if (r_bloomstate.texture_screen)
6062                         R_FreeTexture(r_bloomstate.texture_screen);
6063                 r_bloomstate.texture_screen = NULL;
6064                 if (r_bloomstate.fbo_framebuffer)
6065                         R_Mesh_DestroyFramebufferObject(r_bloomstate.fbo_framebuffer);
6066                 r_bloomstate.fbo_framebuffer = 0;
6067                 if (r_bloomstate.texture_framebuffercolor)
6068                         R_FreeTexture(r_bloomstate.texture_framebuffercolor);
6069                 r_bloomstate.texture_framebuffercolor = NULL;
6070                 if (r_bloomstate.texture_framebufferdepth)
6071                         R_FreeTexture(r_bloomstate.texture_framebufferdepth);
6072                 r_bloomstate.texture_framebufferdepth = NULL;
6073                 r_bloomstate.screentexturewidth = screentexturewidth;
6074                 r_bloomstate.screentextureheight = screentextureheight;
6075                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
6076                         r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, textype, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6077                 if (r_viewfbo.integer >= 1 && vid.support.ext_framebuffer_object)
6078                 {
6079                         // FIXME: choose depth bits based on a cvar
6080                         r_bloomstate.texture_framebufferdepth = R_LoadTextureShadowMap2D(r_main_texturepool, "framebufferdepth", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, 24, false);
6081                         r_bloomstate.texture_framebuffercolor = R_LoadTexture2D(r_main_texturepool, "framebuffercolor", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, textype, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6082                         r_bloomstate.fbo_framebuffer = R_Mesh_CreateFramebufferObject(r_bloomstate.texture_framebufferdepth, r_bloomstate.texture_framebuffercolor, NULL, NULL, NULL);
6083                         R_Mesh_SetRenderTargets(r_bloomstate.fbo_framebuffer, r_bloomstate.texture_framebufferdepth, r_bloomstate.texture_framebuffercolor, NULL, NULL, NULL);
6084 #ifndef USE_GLES2
6085                         // render depth into one texture and normalmap into the other
6086                         if (qglDrawBuffer)
6087                         {
6088                                 int status;
6089                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
6090                                 qglReadBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
6091                                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER);CHECKGLERROR
6092                                 if (status != GL_FRAMEBUFFER_COMPLETE)
6093                                         Con_Printf("R_Bloom_StartFrame: glCheckFramebufferStatusEXT returned %i\n", status);
6094                         }
6095 #endif
6096                 }
6097                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
6098                 r_bloomstate.bloomtextureheight = bloomtextureheight;
6099                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
6100                         r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, textype, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6101                 r_bloomstate.viewfbo = r_viewfbo.integer;
6102                 r_bloomstate.texturetype = textype;
6103         }
6104
6105         // when doing a reduced render (HDR) we want to use a smaller area
6106         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
6107         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
6108         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
6109         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
6110         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
6111
6112         // set up a texcoord array for the full resolution screen image
6113         // (we have to keep this around to copy back during final render)
6114         r_bloomstate.screentexcoord2f[0] = 0;
6115         r_bloomstate.screentexcoord2f[1] = (float)viewheight    / (float)r_bloomstate.screentextureheight;
6116         r_bloomstate.screentexcoord2f[2] = (float)viewwidth     / (float)r_bloomstate.screentexturewidth;
6117         r_bloomstate.screentexcoord2f[3] = (float)viewheight    / (float)r_bloomstate.screentextureheight;
6118         r_bloomstate.screentexcoord2f[4] = (float)viewwidth     / (float)r_bloomstate.screentexturewidth;
6119         r_bloomstate.screentexcoord2f[5] = 0;
6120         r_bloomstate.screentexcoord2f[6] = 0;
6121         r_bloomstate.screentexcoord2f[7] = 0;
6122
6123         // set up a texcoord array for the reduced resolution bloom image
6124         // (which will be additive blended over the screen image)
6125         r_bloomstate.bloomtexcoord2f[0] = 0;
6126         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
6127         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
6128         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
6129         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
6130         r_bloomstate.bloomtexcoord2f[5] = 0;
6131         r_bloomstate.bloomtexcoord2f[6] = 0;
6132         r_bloomstate.bloomtexcoord2f[7] = 0;
6133
6134         switch(vid.renderpath)
6135         {
6136         case RENDERPATH_GL11:
6137         case RENDERPATH_GL13:
6138         case RENDERPATH_GL20:
6139         case RENDERPATH_SOFT:
6140         case RENDERPATH_GLES1:
6141         case RENDERPATH_GLES2:
6142                 break;
6143         case RENDERPATH_D3D9:
6144         case RENDERPATH_D3D10:
6145         case RENDERPATH_D3D11:
6146                 {
6147                         int i;
6148                         for (i = 0;i < 4;i++)
6149                         {
6150                                 r_bloomstate.screentexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.screentexturewidth;
6151                                 r_bloomstate.screentexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.screentextureheight;
6152                                 r_bloomstate.bloomtexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.bloomtexturewidth;
6153                                 r_bloomstate.bloomtexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.bloomtextureheight;
6154                         }
6155                 }
6156                 break;
6157         }
6158
6159         if ((r_hdr.integer || r_bloom.integer) && r_bloomstate.bloomwidth)
6160         {
6161                 r_bloomstate.enabled = true;
6162                 r_bloomstate.hdr = r_hdr.integer != 0 && !r_bloomstate.fbo_framebuffer;
6163         }
6164
6165         R_Viewport_InitOrtho(&r_bloomstate.viewport, &identitymatrix, r_refdef.view.x, vid.height - r_bloomstate.bloomheight - r_refdef.view.y, r_bloomstate.bloomwidth, r_bloomstate.bloomheight, 0, 0, 1, 1, -10, 100, NULL);
6166
6167         if (r_bloomstate.fbo_framebuffer)
6168                 r_refdef.view.clear = true;
6169 }
6170
6171 void R_Bloom_CopyBloomTexture(float colorscale)
6172 {
6173         r_refdef.stats.bloom++;
6174
6175         // scale down screen texture to the bloom texture size
6176         CHECKGLERROR
6177         R_Mesh_SetMainRenderTargets();
6178         R_SetViewport(&r_bloomstate.viewport);
6179         GL_BlendFunc(GL_ONE, GL_ZERO);
6180         GL_Color(colorscale, colorscale, colorscale, 1);
6181         // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
6182         switch(vid.renderpath)
6183         {
6184         case RENDERPATH_GL11:
6185         case RENDERPATH_GL13:
6186         case RENDERPATH_GL20:
6187         case RENDERPATH_GLES1:
6188         case RENDERPATH_GLES2:
6189         case RENDERPATH_SOFT:
6190                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
6191                 break;
6192         case RENDERPATH_D3D9:
6193         case RENDERPATH_D3D10:
6194         case RENDERPATH_D3D11:
6195                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
6196                 break;
6197         }
6198         // TODO: do boxfilter scale-down in shader?
6199         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1, false, true);
6200         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
6201         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
6202
6203         // we now have a bloom image in the framebuffer
6204         // copy it into the bloom image texture for later processing
6205         R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
6206         r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
6207 }
6208
6209 void R_Bloom_CopyHDRTexture(void)
6210 {
6211         R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
6212         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
6213 }
6214
6215 void R_Bloom_MakeTexture(void)
6216 {
6217         int x, range, dir;
6218         float xoffset, yoffset, r, brighten;
6219
6220         r_refdef.stats.bloom++;
6221
6222         R_ResetViewRendering2D();
6223
6224         // we have a bloom image in the framebuffer
6225         CHECKGLERROR
6226         R_SetViewport(&r_bloomstate.viewport);
6227
6228         for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
6229         {
6230                 x *= 2;
6231                 r = bound(0, r_bloom_colorexponent.value / x, 1);
6232                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
6233                 GL_Color(r,r,r,1);
6234                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
6235                 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1, false, true);
6236                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
6237                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
6238
6239                 // copy the vertically blurred bloom view to a texture
6240                 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
6241                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
6242         }
6243
6244         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
6245         brighten = r_bloom_brighten.value;
6246         if (r_bloomstate.hdr)
6247                 brighten *= r_hdr_range.value;
6248         brighten = sqrt(brighten);
6249         if(range >= 1)
6250                 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
6251         R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1, false, true);
6252
6253         for (dir = 0;dir < 2;dir++)
6254         {
6255                 // blend on at multiple vertical offsets to achieve a vertical blur
6256                 // TODO: do offset blends using GLSL
6257                 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
6258                 GL_BlendFunc(GL_ONE, GL_ZERO);
6259                 for (x = -range;x <= range;x++)
6260                 {
6261                         if (!dir){xoffset = 0;yoffset = x;}
6262                         else {xoffset = x;yoffset = 0;}
6263                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
6264                         yoffset /= (float)r_bloomstate.bloomtextureheight;
6265                         // compute a texcoord array with the specified x and y offset
6266                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
6267                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
6268                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
6269                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
6270                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
6271                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
6272                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
6273                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
6274                         // this r value looks like a 'dot' particle, fading sharply to
6275                         // black at the edges
6276                         // (probably not realistic but looks good enough)
6277                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
6278                         //r = brighten/(range*2+1);
6279                         r = brighten / (range * 2 + 1);
6280                         if(range >= 1)
6281                                 r *= (1 - x*x/(float)(range*range));
6282                         GL_Color(r, r, r, 1);
6283                         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
6284                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
6285                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
6286                         GL_BlendFunc(GL_ONE, GL_ONE);
6287                 }
6288
6289                 // copy the vertically blurred bloom view to a texture
6290                 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
6291                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
6292         }
6293 }
6294
6295 void R_HDR_RenderBloomTexture(void)
6296 {
6297         int oldwidth, oldheight;
6298         float oldcolorscale;
6299         qboolean oldwaterstate;
6300
6301         oldwaterstate = r_waterstate.enabled;
6302         oldcolorscale = r_refdef.view.colorscale;
6303         oldwidth = r_refdef.view.width;
6304         oldheight = r_refdef.view.height;
6305         r_refdef.view.width = r_bloomstate.bloomwidth;
6306         r_refdef.view.height = r_bloomstate.bloomheight;
6307
6308         if(r_hdr.integer < 2)
6309                 r_waterstate.enabled = false;
6310
6311         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
6312         // TODO: add exposure compensation features
6313         // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
6314
6315         r_refdef.view.showdebug = false;
6316         r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
6317
6318         R_ResetViewRendering3D();
6319
6320         R_ClearScreen(r_refdef.fogenabled);
6321         if (r_timereport_active)
6322                 R_TimeReport("HDRclear");
6323
6324         R_View_Update();
6325         if (r_timereport_active)
6326                 R_TimeReport("visibility");
6327
6328         // only do secondary renders with HDR if r_hdr is 2 or higher
6329         r_waterstate.numwaterplanes = 0;
6330         if (r_waterstate.enabled)
6331                 R_RenderWaterPlanes();
6332
6333         r_refdef.view.showdebug = true;
6334         R_RenderScene();
6335         r_waterstate.numwaterplanes = 0;
6336
6337         R_ResetViewRendering2D();
6338
6339         R_Bloom_CopyHDRTexture();
6340         R_Bloom_MakeTexture();
6341
6342         // restore the view settings
6343         r_waterstate.enabled = oldwaterstate;
6344         r_refdef.view.width = oldwidth;
6345         r_refdef.view.height = oldheight;
6346         r_refdef.view.colorscale = oldcolorscale;
6347
6348         R_ResetViewRendering3D();
6349
6350         R_ClearScreen(r_refdef.fogenabled);
6351         if (r_timereport_active)
6352                 R_TimeReport("viewclear");
6353 }
6354
6355 static void R_BlendView(void)
6356 {
6357         unsigned int permutation;
6358         float uservecs[4][4];
6359
6360         switch (vid.renderpath)
6361         {
6362         case RENDERPATH_GL20:
6363         case RENDERPATH_D3D9:
6364         case RENDERPATH_D3D10:
6365         case RENDERPATH_D3D11:
6366         case RENDERPATH_SOFT:
6367         case RENDERPATH_GLES2:
6368                 permutation =
6369                           (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
6370                         | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
6371                         | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
6372                         | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
6373                         | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
6374
6375                 if (r_bloomstate.texture_screen)
6376                 {
6377                         // make sure the buffer is available
6378                         if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
6379
6380                         R_ResetViewRendering2D();
6381                         R_Mesh_SetMainRenderTargets();
6382
6383                         if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
6384                         {
6385                                 // declare variables
6386                                 float blur_factor, blur_mouseaccel, blur_velocity;
6387                                 static float blur_average; 
6388                                 static vec3_t blur_oldangles; // used to see how quickly the mouse is moving
6389
6390                                 // set a goal for the factoring
6391                                 blur_velocity = bound(0, (VectorLength(cl.movement_velocity) - r_motionblur_velocityfactor_minspeed.value) 
6392                                         / max(1, r_motionblur_velocityfactor_maxspeed.value - r_motionblur_velocityfactor_minspeed.value), 1);
6393                                 blur_mouseaccel = bound(0, ((fabs(VectorLength(cl.viewangles) - VectorLength(blur_oldangles)) * 10) - r_motionblur_mousefactor_minspeed.value) 
6394                                         / max(1, r_motionblur_mousefactor_maxspeed.value - r_motionblur_mousefactor_minspeed.value), 1);
6395                                 blur_factor = ((blur_velocity * r_motionblur_velocityfactor.value) 
6396                                         + (blur_mouseaccel * r_motionblur_mousefactor.value));
6397
6398                                 // from the goal, pick an averaged value between goal and last value
6399                                 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_averaging.value), 1);
6400                                 blur_average = blur_average * (1 - cl.motionbluralpha) + blur_factor * cl.motionbluralpha;
6401                                 
6402                                 // enforce minimum amount of blur 
6403                                 blur_factor = blur_average * (1 - r_motionblur_minblur.value) + r_motionblur_minblur.value;
6404                                 
6405                                 //Con_Printf("motionblur: direct factor: %f, averaged factor: %f, velocity: %f, mouse accel: %f \n", blur_factor, blur_average, blur_velocity, blur_mouseaccel);
6406
6407                                 // calculate values into a standard alpha
6408                                 cl.motionbluralpha = 1 - exp(-
6409                                                 (
6410                                                  (r_motionblur.value * blur_factor / 80)
6411                                                  +
6412                                                  (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
6413                                                 )
6414                                                 /
6415                                                 max(0.0001, cl.time - cl.oldtime) // fps independent
6416                                           );
6417                                 
6418                                 // randomization for the blur value to combat persistent ghosting
6419                                 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
6420                                 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
6421                                 
6422                                 // apply the blur
6423                                 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
6424                                 {
6425                                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6426                                         GL_Color(1, 1, 1, cl.motionbluralpha);
6427                                         switch(vid.renderpath)
6428                                         {
6429                                         case RENDERPATH_GL11:
6430                                         case RENDERPATH_GL13:
6431                                         case RENDERPATH_GL20:
6432                                         case RENDERPATH_GLES1:
6433                                         case RENDERPATH_GLES2:
6434                                         case RENDERPATH_SOFT:
6435                                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
6436                                                 break;
6437                                         case RENDERPATH_D3D9:
6438                                         case RENDERPATH_D3D10:
6439                                         case RENDERPATH_D3D11:
6440                                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
6441                                                 break;
6442                                         }
6443                                         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1, false, true);
6444                                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
6445                                         r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
6446                                 }
6447                                 
6448                                 // updates old view angles for next pass 
6449                                 VectorCopy(cl.viewangles, blur_oldangles);
6450                         }
6451
6452                         // copy view into the screen texture
6453                         R_Mesh_CopyToTexture(r_bloomstate.texture_screen, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
6454                         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
6455                 }
6456                 else if (!r_bloomstate.texture_bloom)
6457                 {
6458                         // we may still have to do view tint...
6459                         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
6460                         {
6461                                 // apply a color tint to the whole view
6462                                 R_ResetViewRendering2D();
6463                                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
6464                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
6465                                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, true);
6466                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6467                                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
6468                         }
6469                         break; // no screen processing, no bloom, skip it
6470                 }
6471
6472                 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
6473                 {
6474                         // render simple bloom effect
6475                         // copy the screen and shrink it and darken it for the bloom process
6476                         R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
6477                         // make the bloom texture
6478                         R_Bloom_MakeTexture();
6479                 }
6480
6481 #if _MSC_VER >= 1400
6482 #define sscanf sscanf_s
6483 #endif
6484                 memset(uservecs, 0, sizeof(uservecs));
6485                 if (r_glsl_postprocess_uservec1_enable.integer)
6486                         sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
6487                 if (r_glsl_postprocess_uservec2_enable.integer)
6488                         sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
6489                 if (r_glsl_postprocess_uservec3_enable.integer)
6490                         sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
6491                 if (r_glsl_postprocess_uservec4_enable.integer)
6492                         sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
6493
6494                 R_ResetViewRendering2D();
6495                 GL_Color(1, 1, 1, 1);
6496                 GL_BlendFunc(GL_ONE, GL_ZERO);
6497
6498                 switch(vid.renderpath)
6499                 {
6500                 case RENDERPATH_GL20:
6501                 case RENDERPATH_GLES2:
6502                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
6503                         R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
6504                         if (r_glsl_permutation->tex_Texture_First           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First     , r_bloomstate.texture_screen);
6505                         if (r_glsl_permutation->tex_Texture_Second          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second    , r_bloomstate.texture_bloom );
6506                         if (r_glsl_permutation->tex_Texture_GammaRamps      >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps, r_texture_gammaramps       );
6507                         if (r_glsl_permutation->loc_ViewTintColor           >= 0) qglUniform4f(r_glsl_permutation->loc_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
6508                         if (r_glsl_permutation->loc_PixelSize               >= 0) qglUniform2f(r_glsl_permutation->loc_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
6509                         if (r_glsl_permutation->loc_UserVec1                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
6510                         if (r_glsl_permutation->loc_UserVec2                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
6511                         if (r_glsl_permutation->loc_UserVec3                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
6512                         if (r_glsl_permutation->loc_UserVec4                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
6513                         if (r_glsl_permutation->loc_Saturation              >= 0) qglUniform1f(r_glsl_permutation->loc_Saturation        , r_glsl_saturation.value);
6514                         if (r_glsl_permutation->loc_PixelToScreenTexCoord   >= 0) qglUniform2f(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
6515                         if (r_glsl_permutation->loc_BloomColorSubtract      >= 0) qglUniform4f(r_glsl_permutation->loc_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
6516                         break;
6517                 case RENDERPATH_D3D9:
6518 #ifdef SUPPORTD3D
6519                         // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
6520                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_d3dscreenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
6521                         R_SetupShader_SetPermutationHLSL(SHADERMODE_POSTPROCESS, permutation);
6522                         R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
6523                         R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
6524                         R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
6525                         hlslPSSetParameter4f(D3DPSREGISTER_ViewTintColor        , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
6526                         hlslPSSetParameter2f(D3DPSREGISTER_PixelSize            , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
6527                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec1             , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
6528                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec2             , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
6529                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec3             , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
6530                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec4             , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
6531                         hlslPSSetParameter1f(D3DPSREGISTER_Saturation           , r_glsl_saturation.value);
6532                         hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
6533                         hlslPSSetParameter4f(D3DPSREGISTER_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
6534 #endif
6535                         break;
6536                 case RENDERPATH_D3D10:
6537                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6538                         break;
6539                 case RENDERPATH_D3D11:
6540                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6541                         break;
6542                 case RENDERPATH_SOFT:
6543                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
6544                         R_SetupShader_SetPermutationSoft(SHADERMODE_POSTPROCESS, permutation);
6545                         R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
6546                         R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
6547                         R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
6548                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
6549                         DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
6550                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
6551                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
6552                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
6553                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
6554                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_Saturation        , r_glsl_saturation.value);
6555                         DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
6556                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
6557                         break;
6558                 default:
6559                         break;
6560                 }
6561                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
6562                 r_refdef.stats.bloom_drawpixels += r_refdef.view.width * r_refdef.view.height;
6563                 break;
6564         case RENDERPATH_GL11:
6565         case RENDERPATH_GL13:
6566         case RENDERPATH_GLES1:
6567                 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
6568                 {
6569                         // apply a color tint to the whole view
6570                         R_ResetViewRendering2D();
6571                         GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
6572                         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
6573                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, true);
6574                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6575                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
6576                 }
6577                 break;
6578         }
6579 }
6580
6581 matrix4x4_t r_waterscrollmatrix;
6582
6583 void R_UpdateFog(void) // needs to be called before HDR subrender too, as that changes colorscale!
6584 {
6585         // Nehahra fog
6586         if (gamemode == GAME_NEHAHRA)
6587         {
6588                 if (gl_fogenable.integer)
6589                 {
6590                         r_refdef.oldgl_fogenable = true;
6591                         r_refdef.fog_density = gl_fogdensity.value;
6592                         r_refdef.fog_red = gl_fogred.value;
6593                         r_refdef.fog_green = gl_foggreen.value;
6594                         r_refdef.fog_blue = gl_fogblue.value;
6595                         r_refdef.fog_alpha = 1;
6596                         r_refdef.fog_start = 0;
6597                         r_refdef.fog_end = gl_skyclip.value;
6598                         r_refdef.fog_height = 1<<30;
6599                         r_refdef.fog_fadedepth = 128;
6600                 }
6601                 else if (r_refdef.oldgl_fogenable)
6602                 {
6603                         r_refdef.oldgl_fogenable = false;
6604                         r_refdef.fog_density = 0;
6605                         r_refdef.fog_red = 0;
6606                         r_refdef.fog_green = 0;
6607                         r_refdef.fog_blue = 0;
6608                         r_refdef.fog_alpha = 0;
6609                         r_refdef.fog_start = 0;
6610                         r_refdef.fog_end = 0;
6611                         r_refdef.fog_height = 1<<30;
6612                         r_refdef.fog_fadedepth = 128;
6613                 }
6614         }
6615
6616         // fog parms
6617         r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
6618         r_refdef.fog_start = max(0, r_refdef.fog_start);
6619         r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
6620
6621         if (r_refdef.fog_density && r_drawfog.integer)
6622         {
6623                 r_refdef.fogenabled = true;
6624                 // this is the point where the fog reaches 0.9986 alpha, which we
6625                 // consider a good enough cutoff point for the texture
6626                 // (0.9986 * 256 == 255.6)
6627                 if (r_fog_exp2.integer)
6628                         r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
6629                 else
6630                         r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
6631                 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
6632                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
6633                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
6634                 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
6635                         R_BuildFogHeightTexture();
6636                 // fog color was already set
6637                 // update the fog texture
6638                 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)
6639                         R_BuildFogTexture();
6640                 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
6641                 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
6642         }
6643         else
6644                 r_refdef.fogenabled = false;
6645
6646         // fog color
6647         if (r_refdef.fog_density)
6648         {
6649                 r_refdef.fogcolor[0] = r_refdef.fog_red;
6650                 r_refdef.fogcolor[1] = r_refdef.fog_green;
6651                 r_refdef.fogcolor[2] = r_refdef.fog_blue;
6652
6653                 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
6654                 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
6655                 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
6656                 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
6657
6658                 {
6659                         vec3_t fogvec;
6660                         VectorCopy(r_refdef.fogcolor, fogvec);
6661                         //   color.rgb *= ContrastBoost * SceneBrightness;
6662                         VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
6663                         r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
6664                         r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
6665                         r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
6666                 }
6667         }
6668 }
6669
6670 void R_UpdateVariables(void)
6671 {
6672         R_Textures_Frame();
6673
6674         r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
6675
6676         r_refdef.farclip = r_farclip_base.value;
6677         if (r_refdef.scene.worldmodel)
6678                 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
6679         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
6680
6681         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
6682                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
6683         r_refdef.polygonfactor = 0;
6684         r_refdef.polygonoffset = 0;
6685         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
6686         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
6687
6688         r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
6689         r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
6690         r_refdef.scene.rtdlight = r_shadow_realtime_dlight.integer != 0 && !gl_flashblend.integer && r_dynamic.integer;
6691         r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
6692         r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
6693         if (FAKELIGHT_ENABLED)
6694         {
6695                 r_refdef.lightmapintensity *= r_fakelight_intensity.value;
6696         }
6697         if (r_showsurfaces.integer)
6698         {
6699                 r_refdef.scene.rtworld = false;
6700                 r_refdef.scene.rtworldshadows = false;
6701                 r_refdef.scene.rtdlight = false;
6702                 r_refdef.scene.rtdlightshadows = false;
6703                 r_refdef.lightmapintensity = 0;
6704         }
6705
6706         switch(vid.renderpath)
6707         {
6708         case RENDERPATH_GL20:
6709         case RENDERPATH_D3D9:
6710         case RENDERPATH_D3D10:
6711         case RENDERPATH_D3D11:
6712         case RENDERPATH_SOFT:
6713         case RENDERPATH_GLES2:
6714                 if(v_glslgamma.integer && !vid_gammatables_trivial)
6715                 {
6716                         if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
6717                         {
6718                                 // build GLSL gamma texture
6719 #define RAMPWIDTH 256
6720                                 unsigned short ramp[RAMPWIDTH * 3];
6721                                 unsigned char rampbgr[RAMPWIDTH][4];
6722                                 int i;
6723
6724                                 r_texture_gammaramps_serial = vid_gammatables_serial;
6725
6726                                 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
6727                                 for(i = 0; i < RAMPWIDTH; ++i)
6728                                 {
6729                                         rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
6730                                         rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
6731                                         rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
6732                                         rampbgr[i][3] = 0;
6733                                 }
6734                                 if (r_texture_gammaramps)
6735                                 {
6736                                         R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, 0, RAMPWIDTH, 1, 1);
6737                                 }
6738                                 else
6739                                 {
6740                                         r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
6741                                 }
6742                         }
6743                 }
6744                 else
6745                 {
6746                         // remove GLSL gamma texture
6747                 }
6748                 break;
6749         case RENDERPATH_GL11:
6750         case RENDERPATH_GL13:
6751         case RENDERPATH_GLES1:
6752                 break;
6753         }
6754 }
6755
6756 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
6757 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
6758 /*
6759 ================
6760 R_SelectScene
6761 ================
6762 */
6763 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
6764         if( scenetype != r_currentscenetype ) {
6765                 // store the old scenetype
6766                 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
6767                 r_currentscenetype = scenetype;
6768                 // move in the new scene
6769                 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
6770         }
6771 }
6772
6773 /*
6774 ================
6775 R_GetScenePointer
6776 ================
6777 */
6778 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
6779 {
6780         // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
6781         if( scenetype == r_currentscenetype ) {
6782                 return &r_refdef.scene;
6783         } else {
6784                 return &r_scenes_store[ scenetype ];
6785         }
6786 }
6787
6788 int R_SortEntities_Compare(const void *ap, const void *bp)
6789 {
6790         const entity_render_t *a = *(const entity_render_t **)ap;
6791         const entity_render_t *b = *(const entity_render_t **)bp;
6792
6793         // 1. compare model
6794         if(a->model < b->model)
6795                 return -1;
6796         if(a->model > b->model)
6797                 return +1;
6798
6799         // 2. compare skin
6800         // TODO possibly calculate the REAL skinnum here first using
6801         // skinscenes?
6802         if(a->skinnum < b->skinnum)
6803                 return -1;
6804         if(a->skinnum > b->skinnum)
6805                 return +1;
6806
6807         // everything we compared is equal
6808         return 0;
6809 }
6810 void R_SortEntities(void)
6811 {
6812         // below or equal 2 ents, sorting never gains anything
6813         if(r_refdef.scene.numentities <= 2)
6814                 return;
6815         // sort
6816         qsort(r_refdef.scene.entities, r_refdef.scene.numentities, sizeof(*r_refdef.scene.entities), R_SortEntities_Compare);
6817 }
6818
6819 /*
6820 ================
6821 R_RenderView
6822 ================
6823 */
6824 int dpsoftrast_test;
6825 extern void R_Shadow_UpdateBounceGridTexture(void);
6826 extern cvar_t r_shadow_bouncegrid;
6827 void R_RenderView(void)
6828 {
6829         matrix4x4_t originalmatrix = r_refdef.view.matrix, offsetmatrix;
6830
6831         dpsoftrast_test = r_test.integer;
6832
6833         if (r_timereport_active)
6834                 R_TimeReport("start");
6835         r_textureframe++; // used only by R_GetCurrentTexture
6836         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
6837
6838         if(R_CompileShader_CheckStaticParms())
6839                 R_GLSL_Restart_f();
6840
6841         if (!r_drawentities.integer)
6842                 r_refdef.scene.numentities = 0;
6843         else if (r_sortentities.integer)
6844                 R_SortEntities();
6845
6846         R_AnimCache_ClearCache();
6847         R_FrameData_NewFrame();
6848
6849         /* adjust for stereo display */
6850         if(R_Stereo_Active())
6851         {
6852                 Matrix4x4_CreateFromQuakeEntity(&offsetmatrix, 0, r_stereo_separation.value * (0.5f - r_stereo_side), 0, 0, r_stereo_angle.value * (0.5f - r_stereo_side), 0, 1);
6853                 Matrix4x4_Concat(&r_refdef.view.matrix, &originalmatrix, &offsetmatrix);
6854         }
6855
6856         if (r_refdef.view.isoverlay)
6857         {
6858                 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
6859                 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
6860                 R_TimeReport("depthclear");
6861
6862                 r_refdef.view.showdebug = false;
6863
6864                 r_waterstate.enabled = false;
6865                 r_waterstate.numwaterplanes = 0;
6866
6867                 R_RenderScene();
6868
6869                 r_refdef.view.matrix = originalmatrix;
6870
6871                 CHECKGLERROR
6872                 return;
6873         }
6874
6875         if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
6876         {
6877                 r_refdef.view.matrix = originalmatrix;
6878                 return; //Host_Error ("R_RenderView: NULL worldmodel");
6879         }
6880
6881         r_refdef.view.colorscale = r_hdr_scenebrightness.value * r_hdr_irisadaptation_value.value;
6882
6883         R_RenderView_UpdateViewVectors();
6884
6885         R_Shadow_UpdateWorldLightSelection();
6886
6887         R_Bloom_StartFrame();
6888         R_Water_StartFrame();
6889
6890         CHECKGLERROR
6891         if (r_timereport_active)
6892                 R_TimeReport("viewsetup");
6893
6894         R_ResetViewRendering3D();
6895
6896         if (r_refdef.view.clear || r_refdef.fogenabled)
6897         {
6898                 R_ClearScreen(r_refdef.fogenabled);
6899                 if (r_timereport_active)
6900                         R_TimeReport("viewclear");
6901         }
6902         r_refdef.view.clear = true;
6903
6904         // this produces a bloom texture to be used in R_BlendView() later
6905         if (r_bloomstate.hdr)
6906         {
6907                 R_HDR_RenderBloomTexture();
6908                 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
6909                 r_textureframe++; // used only by R_GetCurrentTexture
6910         }
6911
6912         r_refdef.view.showdebug = true;
6913
6914         R_View_Update();
6915         if (r_timereport_active)
6916                 R_TimeReport("visibility");
6917
6918         R_Shadow_UpdateBounceGridTexture();
6919         if (r_timereport_active && r_shadow_bouncegrid.integer)
6920                 R_TimeReport("bouncegrid");
6921
6922         r_waterstate.numwaterplanes = 0;
6923         if (r_waterstate.enabled)
6924                 R_RenderWaterPlanes();
6925
6926         R_RenderScene();
6927         r_waterstate.numwaterplanes = 0;
6928
6929         R_BlendView();
6930         if (r_timereport_active)
6931                 R_TimeReport("blendview");
6932
6933         GL_Scissor(0, 0, vid.width, vid.height);
6934         GL_ScissorTest(false);
6935
6936         r_refdef.view.matrix = originalmatrix;
6937
6938         CHECKGLERROR
6939 }
6940
6941 void R_RenderWaterPlanes(void)
6942 {
6943         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
6944         {
6945                 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
6946                 if (r_timereport_active)
6947                         R_TimeReport("waterworld");
6948         }
6949
6950         // don't let sound skip if going slow
6951         if (r_refdef.scene.extraupdate)
6952                 S_ExtraUpdate ();
6953
6954         R_DrawModelsAddWaterPlanes();
6955         if (r_timereport_active)
6956                 R_TimeReport("watermodels");
6957
6958         if (r_waterstate.numwaterplanes)
6959         {
6960                 R_Water_ProcessPlanes();
6961                 if (r_timereport_active)
6962                         R_TimeReport("waterscenes");
6963         }
6964 }
6965
6966 extern void R_DrawLightningBeams (void);
6967 extern void VM_CL_AddPolygonsToMeshQueue (void);
6968 extern void R_DrawPortals (void);
6969 extern cvar_t cl_locs_show;
6970 static void R_DrawLocs(void);
6971 static void R_DrawEntityBBoxes(void);
6972 static void R_DrawModelDecals(void);
6973 extern void R_DrawModelShadows(void);
6974 extern void R_DrawModelShadowMaps(void);
6975 extern cvar_t cl_decals_newsystem;
6976 extern qboolean r_shadow_usingdeferredprepass;
6977 void R_RenderScene(void)
6978 {
6979         qboolean shadowmapping = false;
6980
6981         if (r_timereport_active)
6982                 R_TimeReport("beginscene");
6983
6984         r_refdef.stats.renders++;
6985
6986         R_UpdateFog();
6987
6988         // don't let sound skip if going slow
6989         if (r_refdef.scene.extraupdate)
6990                 S_ExtraUpdate ();
6991
6992         R_MeshQueue_BeginScene();
6993
6994         R_SkyStartFrame();
6995
6996         Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.scene.time) * 0.025 * r_waterscroll.value, sin(r_refdef.scene.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
6997
6998         if (r_timereport_active)
6999                 R_TimeReport("skystartframe");
7000
7001         if (cl.csqc_vidvars.drawworld)
7002         {
7003                 // don't let sound skip if going slow
7004                 if (r_refdef.scene.extraupdate)
7005                         S_ExtraUpdate ();
7006
7007                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
7008                 {
7009                         r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
7010                         if (r_timereport_active)
7011                                 R_TimeReport("worldsky");
7012                 }
7013
7014                 if (R_DrawBrushModelsSky() && r_timereport_active)
7015                         R_TimeReport("bmodelsky");
7016
7017                 if (skyrendermasked && skyrenderlater)
7018                 {
7019                         // we have to force off the water clipping plane while rendering sky
7020                         R_SetupView(false);
7021                         R_Sky();
7022                         R_SetupView(true);
7023                         if (r_timereport_active)
7024                                 R_TimeReport("sky");
7025                 }
7026         }
7027
7028         R_AnimCache_CacheVisibleEntities();
7029         if (r_timereport_active)
7030                 R_TimeReport("animation");
7031
7032         R_Shadow_PrepareLights();
7033         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
7034                 R_Shadow_PrepareModelShadows();
7035         if (r_timereport_active)
7036                 R_TimeReport("preparelights");
7037
7038         if (R_Shadow_ShadowMappingEnabled())
7039                 shadowmapping = true;
7040
7041         if (r_shadow_usingdeferredprepass)
7042                 R_Shadow_DrawPrepass();
7043
7044         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
7045         {
7046                 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
7047                 if (r_timereport_active)
7048                         R_TimeReport("worlddepth");
7049         }
7050         if (r_depthfirst.integer >= 2)
7051         {
7052                 R_DrawModelsDepth();
7053                 if (r_timereport_active)
7054                         R_TimeReport("modeldepth");
7055         }
7056
7057         if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
7058         {
7059                 R_DrawModelShadowMaps();
7060                 R_ResetViewRendering3D();
7061                 // don't let sound skip if going slow
7062                 if (r_refdef.scene.extraupdate)
7063                         S_ExtraUpdate ();
7064         }
7065
7066         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
7067         {
7068                 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
7069                 if (r_timereport_active)
7070                         R_TimeReport("world");
7071         }
7072
7073         // don't let sound skip if going slow
7074         if (r_refdef.scene.extraupdate)
7075                 S_ExtraUpdate ();
7076
7077         R_DrawModels();
7078         if (r_timereport_active)
7079                 R_TimeReport("models");
7080
7081         // don't let sound skip if going slow
7082         if (r_refdef.scene.extraupdate)
7083                 S_ExtraUpdate ();
7084
7085         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
7086         {
7087                 R_DrawModelShadows();
7088                 R_ResetViewRendering3D();
7089                 // don't let sound skip if going slow
7090                 if (r_refdef.scene.extraupdate)
7091                         S_ExtraUpdate ();
7092         }
7093
7094         if (!r_shadow_usingdeferredprepass)
7095         {
7096                 R_Shadow_DrawLights();
7097                 if (r_timereport_active)
7098                         R_TimeReport("rtlights");
7099         }
7100
7101         // don't let sound skip if going slow
7102         if (r_refdef.scene.extraupdate)
7103                 S_ExtraUpdate ();
7104
7105         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
7106         {
7107                 R_DrawModelShadows();
7108                 R_ResetViewRendering3D();
7109                 // don't let sound skip if going slow
7110                 if (r_refdef.scene.extraupdate)
7111                         S_ExtraUpdate ();
7112         }
7113
7114         if (cl.csqc_vidvars.drawworld)
7115         {
7116                 if (cl_decals_newsystem.integer)
7117                 {
7118                         R_DrawModelDecals();
7119                         if (r_timereport_active)
7120                                 R_TimeReport("modeldecals");
7121                 }
7122                 else
7123                 {
7124                         R_DrawDecals();
7125                         if (r_timereport_active)
7126                                 R_TimeReport("decals");
7127                 }
7128
7129                 R_DrawParticles();
7130                 if (r_timereport_active)
7131                         R_TimeReport("particles");
7132
7133                 R_DrawExplosions();
7134                 if (r_timereport_active)
7135                         R_TimeReport("explosions");
7136
7137                 R_DrawLightningBeams();
7138                 if (r_timereport_active)
7139                         R_TimeReport("lightning");
7140         }
7141
7142         VM_CL_AddPolygonsToMeshQueue();
7143
7144         if (r_refdef.view.showdebug)
7145         {
7146                 if (cl_locs_show.integer)
7147                 {
7148                         R_DrawLocs();
7149                         if (r_timereport_active)
7150                                 R_TimeReport("showlocs");
7151                 }
7152
7153                 if (r_drawportals.integer)
7154                 {
7155                         R_DrawPortals();
7156                         if (r_timereport_active)
7157                                 R_TimeReport("portals");
7158                 }
7159
7160                 if (r_showbboxes.value > 0)
7161                 {
7162                         R_DrawEntityBBoxes();
7163                         if (r_timereport_active)
7164                                 R_TimeReport("bboxes");
7165                 }
7166         }
7167
7168         if (r_transparent.integer)
7169         {
7170                 R_MeshQueue_RenderTransparent();
7171                 if (r_timereport_active)
7172                         R_TimeReport("drawtrans");
7173         }
7174
7175         if (r_refdef.view.showdebug && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDebug && (r_showtris.value > 0 || r_shownormals.value != 0 || r_showcollisionbrushes.value > 0 || r_showoverdraw.value > 0))
7176         {
7177                 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
7178                 if (r_timereport_active)
7179                         R_TimeReport("worlddebug");
7180                 R_DrawModelsDebug();
7181                 if (r_timereport_active)
7182                         R_TimeReport("modeldebug");
7183         }
7184
7185         if (cl.csqc_vidvars.drawworld)
7186         {
7187                 R_Shadow_DrawCoronas();
7188                 if (r_timereport_active)
7189                         R_TimeReport("coronas");
7190         }
7191
7192 #if 0
7193         {
7194                 GL_DepthTest(false);
7195                 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
7196                 GL_Color(1, 1, 1, 1);
7197                 qglBegin(GL_POLYGON);
7198                 qglVertex3f(r_refdef.view.frustumcorner[0][0], r_refdef.view.frustumcorner[0][1], r_refdef.view.frustumcorner[0][2]);
7199                 qglVertex3f(r_refdef.view.frustumcorner[1][0], r_refdef.view.frustumcorner[1][1], r_refdef.view.frustumcorner[1][2]);
7200                 qglVertex3f(r_refdef.view.frustumcorner[3][0], r_refdef.view.frustumcorner[3][1], r_refdef.view.frustumcorner[3][2]);
7201                 qglVertex3f(r_refdef.view.frustumcorner[2][0], r_refdef.view.frustumcorner[2][1], r_refdef.view.frustumcorner[2][2]);
7202                 qglEnd();
7203                 qglBegin(GL_POLYGON);
7204                 qglVertex3f(r_refdef.view.frustumcorner[0][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[0][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[0][2] + 1000 * r_refdef.view.forward[2]);
7205                 qglVertex3f(r_refdef.view.frustumcorner[1][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[1][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[1][2] + 1000 * r_refdef.view.forward[2]);
7206                 qglVertex3f(r_refdef.view.frustumcorner[3][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[3][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[3][2] + 1000 * r_refdef.view.forward[2]);
7207                 qglVertex3f(r_refdef.view.frustumcorner[2][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[2][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[2][2] + 1000 * r_refdef.view.forward[2]);
7208                 qglEnd();
7209                 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
7210         }
7211 #endif
7212
7213         // don't let sound skip if going slow
7214         if (r_refdef.scene.extraupdate)
7215                 S_ExtraUpdate ();
7216
7217         R_ResetViewRendering2D();
7218 }
7219
7220 static const unsigned short bboxelements[36] =
7221 {
7222         5, 1, 3, 5, 3, 7,
7223         6, 2, 0, 6, 0, 4,
7224         7, 3, 2, 7, 2, 6,
7225         4, 0, 1, 4, 1, 5,
7226         4, 5, 7, 4, 7, 6,
7227         1, 0, 2, 1, 2, 3,
7228 };
7229
7230 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
7231 {
7232         int i;
7233         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
7234
7235         RSurf_ActiveWorldEntity();
7236
7237         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
7238         GL_DepthMask(false);
7239         GL_DepthRange(0, 1);
7240         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
7241 //      R_Mesh_ResetTextureState();
7242
7243         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
7244         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
7245         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
7246         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
7247         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
7248         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
7249         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
7250         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
7251         R_FillColors(color4f, 8, cr, cg, cb, ca);
7252         if (r_refdef.fogenabled)
7253         {
7254                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
7255                 {
7256                         f1 = RSurf_FogVertex(v);
7257                         f2 = 1 - f1;
7258                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
7259                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
7260                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
7261                 }
7262         }
7263         R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
7264         R_Mesh_ResetTextureState();
7265         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
7266         R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
7267 }
7268
7269 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
7270 {
7271         int i;
7272         float color[4];
7273         prvm_edict_t *edict;
7274         prvm_prog_t *prog_save = prog;
7275
7276         // this function draws bounding boxes of server entities
7277         if (!sv.active)
7278                 return;
7279
7280         GL_CullFace(GL_NONE);
7281         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
7282
7283         prog = 0;
7284         SV_VM_Begin();
7285         for (i = 0;i < numsurfaces;i++)
7286         {
7287                 edict = PRVM_EDICT_NUM(surfacelist[i]);
7288                 switch ((int)PRVM_serveredictfloat(edict, solid))
7289                 {
7290                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
7291                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
7292                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
7293                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
7294                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
7295                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
7296                 }
7297                 color[3] *= r_showbboxes.value;
7298                 color[3] = bound(0, color[3], 1);
7299                 GL_DepthTest(!r_showdisabledepthtest.integer);
7300                 GL_CullFace(r_refdef.view.cullface_front);
7301                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
7302         }
7303         SV_VM_End();
7304         prog = prog_save;
7305 }
7306
7307 static void R_DrawEntityBBoxes(void)
7308 {
7309         int i;
7310         prvm_edict_t *edict;
7311         vec3_t center;
7312         prvm_prog_t *prog_save = prog;
7313
7314         // this function draws bounding boxes of server entities
7315         if (!sv.active)
7316                 return;
7317
7318         prog = 0;
7319         SV_VM_Begin();
7320         for (i = 0;i < prog->num_edicts;i++)
7321         {
7322                 edict = PRVM_EDICT_NUM(i);
7323                 if (edict->priv.server->free)
7324                         continue;
7325                 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
7326                 if(PRVM_serveredictedict(edict, tag_entity) != 0)
7327                         continue;
7328                 if(PRVM_serveredictedict(edict, viewmodelforclient) != 0)
7329                         continue;
7330                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
7331                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
7332         }
7333         SV_VM_End();
7334         prog = prog_save;
7335 }
7336
7337 static const int nomodelelement3i[24] =
7338 {
7339         5, 2, 0,
7340         5, 1, 2,
7341         5, 0, 3,
7342         5, 3, 1,
7343         0, 2, 4,
7344         2, 1, 4,
7345         3, 0, 4,
7346         1, 3, 4
7347 };
7348
7349 static const unsigned short nomodelelement3s[24] =
7350 {
7351         5, 2, 0,
7352         5, 1, 2,
7353         5, 0, 3,
7354         5, 3, 1,
7355         0, 2, 4,
7356         2, 1, 4,
7357         3, 0, 4,
7358         1, 3, 4
7359 };
7360
7361 static const float nomodelvertex3f[6*3] =
7362 {
7363         -16,   0,   0,
7364          16,   0,   0,
7365           0, -16,   0,
7366           0,  16,   0,
7367           0,   0, -16,
7368           0,   0,  16
7369 };
7370
7371 static const float nomodelcolor4f[6*4] =
7372 {
7373         0.0f, 0.0f, 0.5f, 1.0f,
7374         0.0f, 0.0f, 0.5f, 1.0f,
7375         0.0f, 0.5f, 0.0f, 1.0f,
7376         0.0f, 0.5f, 0.0f, 1.0f,
7377         0.5f, 0.0f, 0.0f, 1.0f,
7378         0.5f, 0.0f, 0.0f, 1.0f
7379 };
7380
7381 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
7382 {
7383         int i;
7384         float f1, f2, *c;
7385         float color4f[6*4];
7386
7387         RSurf_ActiveCustomEntity(&ent->matrix, &ent->inversematrix, ent->flags, ent->shadertime, ent->colormod[0], ent->colormod[1], ent->colormod[2], ent->alpha, 6, nomodelvertex3f, NULL, NULL, NULL, NULL, nomodelcolor4f, 8, nomodelelement3i, nomodelelement3s, false, false);
7388
7389         // this is only called once per entity so numsurfaces is always 1, and
7390         // surfacelist is always {0}, so this code does not handle batches
7391
7392         if (rsurface.ent_flags & RENDER_ADDITIVE)
7393         {
7394                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
7395                 GL_DepthMask(false);
7396         }
7397         else if (rsurface.colormod[3] < 1)
7398         {
7399                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
7400                 GL_DepthMask(false);
7401         }
7402         else
7403         {
7404                 GL_BlendFunc(GL_ONE, GL_ZERO);
7405                 GL_DepthMask(true);
7406         }
7407         GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
7408         GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
7409         GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
7410         GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
7411         memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
7412         for (i = 0, c = color4f;i < 6;i++, c += 4)
7413         {
7414                 c[0] *= rsurface.colormod[0];
7415                 c[1] *= rsurface.colormod[1];
7416                 c[2] *= rsurface.colormod[2];
7417                 c[3] *= rsurface.colormod[3];
7418         }
7419         if (r_refdef.fogenabled)
7420         {
7421                 for (i = 0, c = color4f;i < 6;i++, c += 4)
7422                 {
7423                         f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
7424                         f2 = 1 - f1;
7425                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
7426                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
7427                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
7428                 }
7429         }
7430 //      R_Mesh_ResetTextureState();
7431         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
7432         R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
7433         R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
7434 }
7435
7436 void R_DrawNoModel(entity_render_t *ent)
7437 {
7438         vec3_t org;
7439         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
7440         if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
7441                 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
7442         else
7443                 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
7444 }
7445
7446 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
7447 {
7448         vec3_t right1, right2, diff, normal;
7449
7450         VectorSubtract (org2, org1, normal);
7451
7452         // calculate 'right' vector for start
7453         VectorSubtract (r_refdef.view.origin, org1, diff);
7454         CrossProduct (normal, diff, right1);
7455         VectorNormalize (right1);
7456
7457         // calculate 'right' vector for end
7458         VectorSubtract (r_refdef.view.origin, org2, diff);
7459         CrossProduct (normal, diff, right2);
7460         VectorNormalize (right2);
7461
7462         vert[ 0] = org1[0] + width * right1[0];
7463         vert[ 1] = org1[1] + width * right1[1];
7464         vert[ 2] = org1[2] + width * right1[2];
7465         vert[ 3] = org1[0] - width * right1[0];
7466         vert[ 4] = org1[1] - width * right1[1];
7467         vert[ 5] = org1[2] - width * right1[2];
7468         vert[ 6] = org2[0] - width * right2[0];
7469         vert[ 7] = org2[1] - width * right2[1];
7470         vert[ 8] = org2[2] - width * right2[2];
7471         vert[ 9] = org2[0] + width * right2[0];
7472         vert[10] = org2[1] + width * right2[1];
7473         vert[11] = org2[2] + width * right2[2];
7474 }
7475
7476 void R_CalcSprite_Vertex3f(float *vertex3f, const vec3_t origin, const vec3_t left, const vec3_t up, float scalex1, float scalex2, float scaley1, float scaley2)
7477 {
7478         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
7479         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
7480         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
7481         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
7482         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
7483         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
7484         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
7485         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
7486         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
7487         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
7488         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
7489         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
7490 }
7491
7492 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
7493 {
7494         int i;
7495         float *vertex3f;
7496         float v[3];
7497         VectorSet(v, x, y, z);
7498         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
7499                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
7500                         break;
7501         if (i == mesh->numvertices)
7502         {
7503                 if (mesh->numvertices < mesh->maxvertices)
7504                 {
7505                         VectorCopy(v, vertex3f);
7506                         mesh->numvertices++;
7507                 }
7508                 return mesh->numvertices;
7509         }
7510         else
7511                 return i;
7512 }
7513
7514 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
7515 {
7516         int i;
7517         int *e, element[3];
7518         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
7519         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
7520         e = mesh->element3i + mesh->numtriangles * 3;
7521         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
7522         {
7523                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
7524                 if (mesh->numtriangles < mesh->maxtriangles)
7525                 {
7526                         *e++ = element[0];
7527                         *e++ = element[1];
7528                         *e++ = element[2];
7529                         mesh->numtriangles++;
7530                 }
7531                 element[1] = element[2];
7532         }
7533 }
7534
7535 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
7536 {
7537         int i;
7538         int *e, element[3];
7539         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
7540         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
7541         e = mesh->element3i + mesh->numtriangles * 3;
7542         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
7543         {
7544                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
7545                 if (mesh->numtriangles < mesh->maxtriangles)
7546                 {
7547                         *e++ = element[0];
7548                         *e++ = element[1];
7549                         *e++ = element[2];
7550                         mesh->numtriangles++;
7551                 }
7552                 element[1] = element[2];
7553         }
7554 }
7555
7556 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
7557 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
7558 {
7559         int planenum, planenum2;
7560         int w;
7561         int tempnumpoints;
7562         mplane_t *plane, *plane2;
7563         double maxdist;
7564         double temppoints[2][256*3];
7565         // figure out how large a bounding box we need to properly compute this brush
7566         maxdist = 0;
7567         for (w = 0;w < numplanes;w++)
7568                 maxdist = max(maxdist, fabs(planes[w].dist));
7569         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
7570         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
7571         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
7572         {
7573                 w = 0;
7574                 tempnumpoints = 4;
7575                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
7576                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
7577                 {
7578                         if (planenum2 == planenum)
7579                                 continue;
7580                         PolygonD_Divide(tempnumpoints, temppoints[w], plane2->normal[0], plane2->normal[1], plane2->normal[2], plane2->dist, R_MESH_PLANE_DIST_EPSILON, 0, NULL, NULL, 256, temppoints[!w], &tempnumpoints, NULL);
7581                         w = !w;
7582                 }
7583                 if (tempnumpoints < 3)
7584                         continue;
7585                 // generate elements forming a triangle fan for this polygon
7586                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
7587         }
7588 }
7589
7590 static void R_Texture_AddLayer(texture_t *t, qboolean depthmask, int blendfunc1, int blendfunc2, texturelayertype_t type, rtexture_t *texture, const matrix4x4_t *matrix, float r, float g, float b, float a)
7591 {
7592         texturelayer_t *layer;
7593         layer = t->currentlayers + t->currentnumlayers++;
7594         layer->type = type;
7595         layer->depthmask = depthmask;
7596         layer->blendfunc1 = blendfunc1;
7597         layer->blendfunc2 = blendfunc2;
7598         layer->texture = texture;
7599         layer->texmatrix = *matrix;
7600         layer->color[0] = r;
7601         layer->color[1] = g;
7602         layer->color[2] = b;
7603         layer->color[3] = a;
7604 }
7605
7606 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
7607 {
7608         if(parms[0] == 0 && parms[1] == 0)
7609                 return false;
7610         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
7611                 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT - 1)] == 0)
7612                         return false;
7613         return true;
7614 }
7615
7616 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
7617 {
7618         double index, f;
7619         index = parms[2] + rsurface.shadertime * parms[3];
7620         index -= floor(index);
7621         switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
7622         {
7623         default:
7624         case Q3WAVEFUNC_NONE:
7625         case Q3WAVEFUNC_NOISE:
7626         case Q3WAVEFUNC_COUNT:
7627                 f = 0;
7628                 break;
7629         case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
7630         case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
7631         case Q3WAVEFUNC_SAWTOOTH: f = index;break;
7632         case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
7633         case Q3WAVEFUNC_TRIANGLE:
7634                 index *= 4;
7635                 f = index - floor(index);
7636                 if (index < 1)
7637                 {
7638                         // f = f;
7639                 }
7640                 else if (index < 2)
7641                         f = 1 - f;
7642                 else if (index < 3)
7643                         f = -f;
7644                 else
7645                         f = -(1 - f);
7646                 break;
7647         }
7648         f = parms[0] + parms[1] * f;
7649         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
7650                 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT - 1)];
7651         return (float) f;
7652 }
7653
7654 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
7655 {
7656         int w, h, idx;
7657         double f;
7658         double offsetd[2];
7659         float tcmat[12];
7660         matrix4x4_t matrix, temp;
7661         switch(tcmod->tcmod)
7662         {
7663                 case Q3TCMOD_COUNT:
7664                 case Q3TCMOD_NONE:
7665                         if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
7666                                 matrix = r_waterscrollmatrix;
7667                         else
7668                                 matrix = identitymatrix;
7669                         break;
7670                 case Q3TCMOD_ENTITYTRANSLATE:
7671                         // this is used in Q3 to allow the gamecode to control texcoord
7672                         // scrolling on the entity, which is not supported in darkplaces yet.
7673                         Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
7674                         break;
7675                 case Q3TCMOD_ROTATE:
7676                         f = tcmod->parms[0] * rsurface.shadertime;
7677                         Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
7678                         Matrix4x4_ConcatRotate(&matrix, (f / 360 - floor(f / 360)) * 360, 0, 0, 1);
7679                         Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
7680                         break;
7681                 case Q3TCMOD_SCALE:
7682                         Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
7683                         break;
7684                 case Q3TCMOD_SCROLL:
7685                         // extra care is needed because of precision breakdown with large values of time
7686                         offsetd[0] = tcmod->parms[0] * rsurface.shadertime;
7687                         offsetd[1] = tcmod->parms[1] * rsurface.shadertime;
7688                         Matrix4x4_CreateTranslate(&matrix, offsetd[0] - floor(offsetd[0]), offsetd[1] - floor(offsetd[1]), 0);
7689                         break;
7690                 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
7691                         w = (int) tcmod->parms[0];
7692                         h = (int) tcmod->parms[1];
7693                         f = rsurface.shadertime / (tcmod->parms[2] * w * h);
7694                         f = f - floor(f);
7695                         idx = (int) floor(f * w * h);
7696                         Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
7697                         break;
7698                 case Q3TCMOD_STRETCH:
7699                         f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
7700                         Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
7701                         break;
7702                 case Q3TCMOD_TRANSFORM:
7703                         VectorSet(tcmat +  0, tcmod->parms[0], tcmod->parms[1], 0);
7704                         VectorSet(tcmat +  3, tcmod->parms[2], tcmod->parms[3], 0);
7705                         VectorSet(tcmat +  6, 0                   , 0                , 1);
7706                         VectorSet(tcmat +  9, tcmod->parms[4], tcmod->parms[5], 0);
7707                         Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
7708                         break;
7709                 case Q3TCMOD_TURBULENT:
7710                         // this is handled in the RSurf_PrepareVertices function
7711                         matrix = identitymatrix;
7712                         break;
7713         }
7714         temp = *texmatrix;
7715         Matrix4x4_Concat(texmatrix, &matrix, &temp);
7716 }
7717
7718 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
7719 {
7720         int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP;
7721         char name[MAX_QPATH];
7722         skinframe_t *skinframe;
7723         unsigned char pixels[296*194];
7724         strlcpy(cache->name, skinname, sizeof(cache->name));
7725         dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
7726         if (developer_loading.integer)
7727                 Con_Printf("loading %s\n", name);
7728         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
7729         if (!skinframe || !skinframe->base)
7730         {
7731                 unsigned char *f;
7732                 fs_offset_t filesize;
7733                 skinframe = NULL;
7734                 f = FS_LoadFile(name, tempmempool, true, &filesize);
7735                 if (f)
7736                 {
7737                         if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
7738                                 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
7739                         Mem_Free(f);
7740                 }
7741         }
7742         cache->skinframe = skinframe;
7743 }
7744
7745 texture_t *R_GetCurrentTexture(texture_t *t)
7746 {
7747         int i;
7748         const entity_render_t *ent = rsurface.entity;
7749         dp_model_t *model = ent->model;
7750         q3shaderinfo_layer_tcmod_t *tcmod;
7751
7752         if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
7753                 return t->currentframe;
7754         t->update_lastrenderframe = r_textureframe;
7755         t->update_lastrenderentity = (void *)ent;
7756
7757         if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
7758                 t->camera_entity = ent->entitynumber;
7759         else
7760                 t->camera_entity = 0;
7761
7762         // switch to an alternate material if this is a q1bsp animated material
7763         {
7764                 texture_t *texture = t;
7765                 int s = rsurface.ent_skinnum;
7766                 if ((unsigned int)s >= (unsigned int)model->numskins)
7767                         s = 0;
7768                 if (model->skinscenes)
7769                 {
7770                         if (model->skinscenes[s].framecount > 1)
7771                                 s = model->skinscenes[s].firstframe + (unsigned int) (rsurface.shadertime * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
7772                         else
7773                                 s = model->skinscenes[s].firstframe;
7774                 }
7775                 if (s > 0)
7776                         t = t + s * model->num_surfaces;
7777                 if (t->animated)
7778                 {
7779                         // use an alternate animation if the entity's frame is not 0,
7780                         // and only if the texture has an alternate animation
7781                         if (rsurface.ent_alttextures && t->anim_total[1])
7782                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(rsurface.shadertime * 5.0f) % t->anim_total[1]) : 0];
7783                         else
7784                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(rsurface.shadertime * 5.0f) % t->anim_total[0]) : 0];
7785                 }
7786                 texture->currentframe = t;
7787         }
7788
7789         // update currentskinframe to be a qw skin or animation frame
7790         if (rsurface.ent_qwskin >= 0)
7791         {
7792                 i = rsurface.ent_qwskin;
7793                 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
7794                 {
7795                         r_qwskincache_size = cl.maxclients;
7796                         if (r_qwskincache)
7797                                 Mem_Free(r_qwskincache);
7798                         r_qwskincache = (r_qwskincache_t *)Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
7799                 }
7800                 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
7801                         R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
7802                 t->currentskinframe = r_qwskincache[i].skinframe;
7803                 if (t->currentskinframe == NULL)
7804                         t->currentskinframe = t->skinframes[LoopingFrameNumberFromDouble(rsurface.shadertime * t->skinframerate, t->numskinframes)];
7805         }
7806         else if (t->numskinframes >= 2)
7807                 t->currentskinframe = t->skinframes[LoopingFrameNumberFromDouble(rsurface.shadertime * t->skinframerate, t->numskinframes)];
7808         if (t->backgroundnumskinframes >= 2)
7809                 t->backgroundcurrentskinframe = t->backgroundskinframes[LoopingFrameNumberFromDouble(rsurface.shadertime * t->backgroundskinframerate, t->backgroundnumskinframes)];
7810
7811         t->currentmaterialflags = t->basematerialflags;
7812         t->currentalpha = rsurface.colormod[3];
7813         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer || r_trippy.integer))
7814                 t->currentalpha *= r_wateralpha.value;
7815         if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
7816                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW; // we apply wateralpha later
7817         if(!r_waterstate.enabled || r_refdef.view.isoverlay)
7818                 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
7819         if (!(rsurface.ent_flags & RENDER_LIGHT))
7820                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
7821         else if (FAKELIGHT_ENABLED)
7822         {
7823                 // no modellight if using fakelight for the map
7824         }
7825         else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
7826         {
7827                 // pick a model lighting mode
7828                 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
7829                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
7830                 else
7831                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
7832         }
7833         if (rsurface.ent_flags & RENDER_ADDITIVE)
7834                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
7835         else if (t->currentalpha < 1)
7836                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
7837         if (rsurface.ent_flags & RENDER_DOUBLESIDED)
7838                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
7839         if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
7840                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
7841         if (t->backgroundnumskinframes)
7842                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
7843         if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
7844         {
7845                 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
7846                         t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
7847         }
7848         else
7849                 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
7850         if (vid.allowalphatocoverage && r_transparent_alphatocoverage.integer >= 2 && ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHA | MATERIALFLAG_ADD | MATERIALFLAG_CUSTOMBLEND)) == (MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHA)))
7851         {
7852                 // promote alphablend to alphatocoverage (a type of alphatest) if antialiasing is on
7853                 t->currentmaterialflags = (t->currentmaterialflags & ~(MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHA)) | MATERIALFLAG_ALPHATEST;
7854         }
7855         if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
7856                 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
7857
7858         // there is no tcmod
7859         if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
7860         {
7861                 t->currenttexmatrix = r_waterscrollmatrix;
7862                 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
7863         }
7864         else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
7865         {
7866                 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
7867                 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
7868         }
7869
7870         for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
7871                 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
7872         for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
7873                 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
7874
7875         t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
7876         if (t->currentskinframe->qpixels)
7877                 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
7878         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
7879         if (!t->basetexture)
7880                 t->basetexture = r_texture_notexture;
7881         t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
7882         t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
7883         t->nmaptexture = t->currentskinframe->nmap;
7884         if (!t->nmaptexture)
7885                 t->nmaptexture = r_texture_blanknormalmap;
7886         t->glosstexture = r_texture_black;
7887         t->glowtexture = t->currentskinframe->glow;
7888         t->fogtexture = t->currentskinframe->fog;
7889         t->reflectmasktexture = t->currentskinframe->reflect;
7890         if (t->backgroundnumskinframes)
7891         {
7892                 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
7893                 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
7894                 t->backgroundglosstexture = r_texture_black;
7895                 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
7896                 if (!t->backgroundnmaptexture)
7897                         t->backgroundnmaptexture = r_texture_blanknormalmap;
7898         }
7899         else
7900         {
7901                 t->backgroundbasetexture = r_texture_white;
7902                 t->backgroundnmaptexture = r_texture_blanknormalmap;
7903                 t->backgroundglosstexture = r_texture_black;
7904                 t->backgroundglowtexture = NULL;
7905         }
7906         t->specularpower = r_shadow_glossexponent.value;
7907         // TODO: store reference values for these in the texture?
7908         t->specularscale = 0;
7909         if (r_shadow_gloss.integer > 0)
7910         {
7911                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
7912                 {
7913                         if (r_shadow_glossintensity.value > 0)
7914                         {
7915                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
7916                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
7917                                 t->specularscale = r_shadow_glossintensity.value;
7918                         }
7919                 }
7920                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
7921                 {
7922                         t->glosstexture = r_texture_white;
7923                         t->backgroundglosstexture = r_texture_white;
7924                         t->specularscale = r_shadow_gloss2intensity.value;
7925                         t->specularpower = r_shadow_gloss2exponent.value;
7926                 }
7927         }
7928         t->specularscale *= t->specularscalemod;
7929         t->specularpower *= t->specularpowermod;
7930         t->rtlightambient = 0;
7931
7932         // lightmaps mode looks bad with dlights using actual texturing, so turn
7933         // off the colormap and glossmap, but leave the normalmap on as it still
7934         // accurately represents the shading involved
7935         if (gl_lightmaps.integer)
7936         {
7937                 t->basetexture = r_texture_grey128;
7938                 t->pantstexture = r_texture_black;
7939                 t->shirttexture = r_texture_black;
7940                 t->nmaptexture = r_texture_blanknormalmap;
7941                 t->glosstexture = r_texture_black;
7942                 t->glowtexture = NULL;
7943                 t->fogtexture = NULL;
7944                 t->reflectmasktexture = NULL;
7945                 t->backgroundbasetexture = NULL;
7946                 t->backgroundnmaptexture = r_texture_blanknormalmap;
7947                 t->backgroundglosstexture = r_texture_black;
7948                 t->backgroundglowtexture = NULL;
7949                 t->specularscale = 0;
7950                 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
7951         }
7952
7953         Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
7954         VectorClear(t->dlightcolor);
7955         t->currentnumlayers = 0;
7956         if (t->currentmaterialflags & MATERIALFLAG_WALL)
7957         {
7958                 int blendfunc1, blendfunc2;
7959                 qboolean depthmask;
7960                 if (t->currentmaterialflags & MATERIALFLAG_ADD)
7961                 {
7962                         blendfunc1 = GL_SRC_ALPHA;
7963                         blendfunc2 = GL_ONE;
7964                 }
7965                 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
7966                 {
7967                         blendfunc1 = GL_SRC_ALPHA;
7968                         blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
7969                 }
7970                 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
7971                 {
7972                         blendfunc1 = t->customblendfunc[0];
7973                         blendfunc2 = t->customblendfunc[1];
7974                 }
7975                 else
7976                 {
7977                         blendfunc1 = GL_ONE;
7978                         blendfunc2 = GL_ZERO;
7979                 }
7980                 // don't colormod evilblend textures
7981                 if(!R_BlendFuncFlags(blendfunc1, blendfunc2) & BLENDFUNC_ALLOWS_COLORMOD)
7982                         VectorSet(t->lightmapcolor, 1, 1, 1);
7983                 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
7984                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
7985                 {
7986                         // fullbright is not affected by r_refdef.lightmapintensity
7987                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
7988                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
7989                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
7990                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
7991                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
7992                 }
7993                 else
7994                 {
7995                         vec3_t ambientcolor;
7996                         float colorscale;
7997                         // set the color tint used for lights affecting this surface
7998                         VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
7999                         colorscale = 2;
8000                         // q3bsp has no lightmap updates, so the lightstylevalue that
8001                         // would normally be baked into the lightmap must be
8002                         // applied to the color
8003                         // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
8004                         if (model->type == mod_brushq3)
8005                                 colorscale *= r_refdef.scene.rtlightstylevalue[0];
8006                         colorscale *= r_refdef.lightmapintensity;
8007                         VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
8008                         VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
8009                         // basic lit geometry
8010                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
8011                         // add pants/shirt if needed
8012                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
8013                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2]  * t->lightmapcolor[2], t->lightmapcolor[3]);
8014                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
8015                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
8016                         // now add ambient passes if needed
8017                         if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
8018                         {
8019                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, ambientcolor[0], ambientcolor[1], ambientcolor[2], t->lightmapcolor[3]);
8020                                 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
8021                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * ambientcolor[0], rsurface.colormap_pantscolor[1] * ambientcolor[1], rsurface.colormap_pantscolor[2] * ambientcolor[2], t->lightmapcolor[3]);
8022                                 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
8023                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * ambientcolor[0], rsurface.colormap_shirtcolor[1] * ambientcolor[1], rsurface.colormap_shirtcolor[2] * ambientcolor[2], t->lightmapcolor[3]);
8024                         }
8025                 }
8026                 if (t->glowtexture != NULL && !gl_lightmaps.integer)
8027                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->glowtexture, &t->currenttexmatrix, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2], t->lightmapcolor[3]);
8028                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
8029                 {
8030                         // if this is opaque use alpha blend which will darken the earlier
8031                         // passes cheaply.
8032                         //
8033                         // if this is an alpha blended material, all the earlier passes
8034                         // were darkened by fog already, so we only need to add the fog
8035                         // color ontop through the fog mask texture
8036                         //
8037                         // if this is an additive blended material, all the earlier passes
8038                         // were darkened by fog already, and we should not add fog color
8039                         // (because the background was not darkened, there is no fog color
8040                         // that was lost behind it).
8041                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, (t->currentmaterialflags & MATERIALFLAG_BLENDED) ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA, TEXTURELAYERTYPE_FOG, t->fogtexture, &t->currenttexmatrix, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], t->lightmapcolor[3]);
8042                 }
8043         }
8044
8045         return t->currentframe;
8046 }
8047
8048 rsurfacestate_t rsurface;
8049
8050 void RSurf_ActiveWorldEntity(void)
8051 {
8052         dp_model_t *model = r_refdef.scene.worldmodel;
8053         //if (rsurface.entity == r_refdef.scene.worldentity)
8054         //      return;
8055         rsurface.entity = r_refdef.scene.worldentity;
8056         rsurface.skeleton = NULL;
8057         memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
8058         rsurface.ent_skinnum = 0;
8059         rsurface.ent_qwskin = -1;
8060         rsurface.ent_flags = r_refdef.scene.worldentity->flags;
8061         rsurface.shadertime = r_refdef.scene.time;
8062         rsurface.matrix = identitymatrix;
8063         rsurface.inversematrix = identitymatrix;
8064         rsurface.matrixscale = 1;
8065         rsurface.inversematrixscale = 1;
8066         R_EntityMatrix(&identitymatrix);
8067         VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
8068         Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
8069         rsurface.fograngerecip = r_refdef.fograngerecip;
8070         rsurface.fogheightfade = r_refdef.fogheightfade;
8071         rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
8072         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
8073         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
8074         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
8075         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
8076         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
8077         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
8078         VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
8079         rsurface.colormod[3] = 1;
8080         VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
8081         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
8082         rsurface.frameblend[0].lerp = 1;
8083         rsurface.ent_alttextures = false;
8084         rsurface.basepolygonfactor = r_refdef.polygonfactor;
8085         rsurface.basepolygonoffset = r_refdef.polygonoffset;
8086         rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
8087         rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8088         rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
8089         rsurface.modelsvector3f = model->surfmesh.data_svector3f;
8090         rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8091         rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
8092         rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
8093         rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8094         rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
8095         rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
8096         rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8097         rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
8098         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
8099         rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8100         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
8101         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
8102         rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8103         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
8104         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
8105         rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8106         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
8107         rsurface.modelelement3i = model->surfmesh.data_element3i;
8108         rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
8109         rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
8110         rsurface.modelelement3s = model->surfmesh.data_element3s;
8111         rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
8112         rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
8113         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
8114         rsurface.modelnumvertices = model->surfmesh.num_vertices;
8115         rsurface.modelnumtriangles = model->surfmesh.num_triangles;
8116         rsurface.modelsurfaces = model->data_surfaces;
8117         rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
8118         rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
8119         rsurface.modelvertex3fbuffer = model->surfmesh.vertex3fbuffer;
8120         rsurface.modelgeneratedvertex = false;
8121         rsurface.batchgeneratedvertex = false;
8122         rsurface.batchfirstvertex = 0;
8123         rsurface.batchnumvertices = 0;
8124         rsurface.batchfirsttriangle = 0;
8125         rsurface.batchnumtriangles = 0;
8126         rsurface.batchvertex3f  = NULL;
8127         rsurface.batchvertex3f_vertexbuffer = NULL;
8128         rsurface.batchvertex3f_bufferoffset = 0;
8129         rsurface.batchsvector3f = NULL;
8130         rsurface.batchsvector3f_vertexbuffer = NULL;
8131         rsurface.batchsvector3f_bufferoffset = 0;
8132         rsurface.batchtvector3f = NULL;
8133         rsurface.batchtvector3f_vertexbuffer = NULL;
8134         rsurface.batchtvector3f_bufferoffset = 0;
8135         rsurface.batchnormal3f  = NULL;
8136         rsurface.batchnormal3f_vertexbuffer = NULL;
8137         rsurface.batchnormal3f_bufferoffset = 0;
8138         rsurface.batchlightmapcolor4f = NULL;
8139         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
8140         rsurface.batchlightmapcolor4f_bufferoffset = 0;
8141         rsurface.batchtexcoordtexture2f = NULL;
8142         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
8143         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
8144         rsurface.batchtexcoordlightmap2f = NULL;
8145         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
8146         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
8147         rsurface.batchvertexmesh = NULL;
8148         rsurface.batchvertexmeshbuffer = NULL;
8149         rsurface.batchvertex3fbuffer = NULL;
8150         rsurface.batchelement3i = NULL;
8151         rsurface.batchelement3i_indexbuffer = NULL;
8152         rsurface.batchelement3i_bufferoffset = 0;
8153         rsurface.batchelement3s = NULL;
8154         rsurface.batchelement3s_indexbuffer = NULL;
8155         rsurface.batchelement3s_bufferoffset = 0;
8156         rsurface.passcolor4f = NULL;
8157         rsurface.passcolor4f_vertexbuffer = NULL;
8158         rsurface.passcolor4f_bufferoffset = 0;
8159 }
8160
8161 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
8162 {
8163         dp_model_t *model = ent->model;
8164         //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
8165         //      return;
8166         rsurface.entity = (entity_render_t *)ent;
8167         rsurface.skeleton = ent->skeleton;
8168         memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
8169         rsurface.ent_skinnum = ent->skinnum;
8170         rsurface.ent_qwskin = (ent->entitynumber <= cl.maxclients && ent->entitynumber >= 1 && cls.protocol == PROTOCOL_QUAKEWORLD && cl.scores[ent->entitynumber - 1].qw_skin[0] && !strcmp(ent->model->name, "progs/player.mdl")) ? (ent->entitynumber - 1) : -1;
8171         rsurface.ent_flags = ent->flags;
8172         rsurface.shadertime = r_refdef.scene.time - ent->shadertime;
8173         rsurface.matrix = ent->matrix;
8174         rsurface.inversematrix = ent->inversematrix;
8175         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
8176         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
8177         R_EntityMatrix(&rsurface.matrix);
8178         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
8179         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
8180         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
8181         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
8182         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
8183         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
8184         VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
8185         VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
8186         VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
8187         VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
8188         VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
8189         VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
8190         rsurface.colormod[3] = ent->alpha;
8191         VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
8192         memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
8193         rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
8194         rsurface.basepolygonfactor = r_refdef.polygonfactor;
8195         rsurface.basepolygonoffset = r_refdef.polygonoffset;
8196         if (ent->model->brush.submodel && !prepass)
8197         {
8198                 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
8199                 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
8200         }
8201         if (model->surfmesh.isanimated && model->AnimateVertices)
8202         {
8203                 if (ent->animcache_vertex3f)
8204                 {
8205                         rsurface.modelvertex3f = ent->animcache_vertex3f;
8206                         rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
8207                         rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
8208                         rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
8209                         rsurface.modelvertexmesh = ent->animcache_vertexmesh;
8210                         rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
8211                         rsurface.modelvertex3fbuffer = ent->animcache_vertex3fbuffer;
8212                 }
8213                 else if (wanttangents)
8214                 {
8215                         rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
8216                         rsurface.modelsvector3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
8217                         rsurface.modeltvector3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
8218                         rsurface.modelnormal3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
8219                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, rsurface.modelnormal3f, rsurface.modelsvector3f, rsurface.modeltvector3f);
8220                         rsurface.modelvertexmesh = NULL;
8221                         rsurface.modelvertexmeshbuffer = NULL;
8222                         rsurface.modelvertex3fbuffer = NULL;
8223                 }
8224                 else if (wantnormals)
8225                 {
8226                         rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
8227                         rsurface.modelsvector3f = NULL;
8228                         rsurface.modeltvector3f = NULL;
8229                         rsurface.modelnormal3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
8230                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, rsurface.modelnormal3f, NULL, NULL);
8231                         rsurface.modelvertexmesh = NULL;
8232                         rsurface.modelvertexmeshbuffer = NULL;
8233                         rsurface.modelvertex3fbuffer = NULL;
8234                 }
8235                 else
8236                 {
8237                         rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
8238                         rsurface.modelsvector3f = NULL;
8239                         rsurface.modeltvector3f = NULL;
8240                         rsurface.modelnormal3f = NULL;
8241                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, NULL, NULL, NULL);
8242                         rsurface.modelvertexmesh = NULL;
8243                         rsurface.modelvertexmeshbuffer = NULL;
8244                         rsurface.modelvertex3fbuffer = NULL;
8245                 }
8246                 rsurface.modelvertex3f_vertexbuffer = 0;
8247                 rsurface.modelvertex3f_bufferoffset = 0;
8248                 rsurface.modelsvector3f_vertexbuffer = 0;
8249                 rsurface.modelsvector3f_bufferoffset = 0;
8250                 rsurface.modeltvector3f_vertexbuffer = 0;
8251                 rsurface.modeltvector3f_bufferoffset = 0;
8252                 rsurface.modelnormal3f_vertexbuffer = 0;
8253                 rsurface.modelnormal3f_bufferoffset = 0;
8254                 rsurface.modelgeneratedvertex = true;
8255         }
8256         else
8257         {
8258                 rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
8259                 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8260                 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
8261                 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
8262                 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8263                 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
8264                 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
8265                 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8266                 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
8267                 rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
8268                 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8269                 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
8270                 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
8271                 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
8272                 rsurface.modelvertex3fbuffer = model->surfmesh.vertex3fbuffer;
8273                 rsurface.modelgeneratedvertex = false;
8274         }
8275         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
8276         rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8277         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
8278         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
8279         rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8280         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
8281         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
8282         rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
8283         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
8284         rsurface.modelelement3i = model->surfmesh.data_element3i;
8285         rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
8286         rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
8287         rsurface.modelelement3s = model->surfmesh.data_element3s;
8288         rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
8289         rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
8290         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
8291         rsurface.modelnumvertices = model->surfmesh.num_vertices;
8292         rsurface.modelnumtriangles = model->surfmesh.num_triangles;
8293         rsurface.modelsurfaces = model->data_surfaces;
8294         rsurface.batchgeneratedvertex = false;
8295         rsurface.batchfirstvertex = 0;
8296         rsurface.batchnumvertices = 0;
8297         rsurface.batchfirsttriangle = 0;
8298         rsurface.batchnumtriangles = 0;
8299         rsurface.batchvertex3f  = NULL;
8300         rsurface.batchvertex3f_vertexbuffer = NULL;
8301         rsurface.batchvertex3f_bufferoffset = 0;
8302         rsurface.batchsvector3f = NULL;
8303         rsurface.batchsvector3f_vertexbuffer = NULL;
8304         rsurface.batchsvector3f_bufferoffset = 0;
8305         rsurface.batchtvector3f = NULL;
8306         rsurface.batchtvector3f_vertexbuffer = NULL;
8307         rsurface.batchtvector3f_bufferoffset = 0;
8308         rsurface.batchnormal3f  = NULL;
8309         rsurface.batchnormal3f_vertexbuffer = NULL;
8310         rsurface.batchnormal3f_bufferoffset = 0;
8311         rsurface.batchlightmapcolor4f = NULL;
8312         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
8313         rsurface.batchlightmapcolor4f_bufferoffset = 0;
8314         rsurface.batchtexcoordtexture2f = NULL;
8315         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
8316         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
8317         rsurface.batchtexcoordlightmap2f = NULL;
8318         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
8319         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
8320         rsurface.batchvertexmesh = NULL;
8321         rsurface.batchvertexmeshbuffer = NULL;
8322         rsurface.batchvertex3fbuffer = NULL;
8323         rsurface.batchelement3i = NULL;
8324         rsurface.batchelement3i_indexbuffer = NULL;
8325         rsurface.batchelement3i_bufferoffset = 0;
8326         rsurface.batchelement3s = NULL;
8327         rsurface.batchelement3s_indexbuffer = NULL;
8328         rsurface.batchelement3s_bufferoffset = 0;
8329         rsurface.passcolor4f = NULL;
8330         rsurface.passcolor4f_vertexbuffer = NULL;
8331         rsurface.passcolor4f_bufferoffset = 0;
8332 }
8333
8334 void RSurf_ActiveCustomEntity(const matrix4x4_t *matrix, const matrix4x4_t *inversematrix, int entflags, double shadertime, float r, float g, float b, float a, int numvertices, const float *vertex3f, const float *texcoord2f, const float *normal3f, const float *svector3f, const float *tvector3f, const float *color4f, int numtriangles, const int *element3i, const unsigned short *element3s, qboolean wantnormals, qboolean wanttangents)
8335 {
8336         rsurface.entity = r_refdef.scene.worldentity;
8337         rsurface.skeleton = NULL;
8338         rsurface.ent_skinnum = 0;
8339         rsurface.ent_qwskin = -1;
8340         rsurface.ent_flags = entflags;
8341         rsurface.shadertime = r_refdef.scene.time - shadertime;
8342         rsurface.modelnumvertices = numvertices;
8343         rsurface.modelnumtriangles = numtriangles;
8344         rsurface.matrix = *matrix;
8345         rsurface.inversematrix = *inversematrix;
8346         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
8347         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
8348         R_EntityMatrix(&rsurface.matrix);
8349         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
8350         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
8351         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
8352         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
8353         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
8354         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
8355         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
8356         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
8357         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
8358         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
8359         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
8360         Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
8361         VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
8362         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
8363         rsurface.frameblend[0].lerp = 1;
8364         rsurface.ent_alttextures = false;
8365         rsurface.basepolygonfactor = r_refdef.polygonfactor;
8366         rsurface.basepolygonoffset = r_refdef.polygonoffset;
8367         if (wanttangents)
8368         {
8369                 rsurface.modelvertex3f = (float *)vertex3f;
8370                 rsurface.modelsvector3f = svector3f ? (float *)svector3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
8371                 rsurface.modeltvector3f = tvector3f ? (float *)tvector3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
8372                 rsurface.modelnormal3f = normal3f ? (float *)normal3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
8373         }
8374         else if (wantnormals)
8375         {
8376                 rsurface.modelvertex3f = (float *)vertex3f;
8377                 rsurface.modelsvector3f = NULL;
8378                 rsurface.modeltvector3f = NULL;
8379                 rsurface.modelnormal3f = normal3f ? (float *)normal3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
8380         }
8381         else
8382         {
8383                 rsurface.modelvertex3f = (float *)vertex3f;
8384                 rsurface.modelsvector3f = NULL;
8385                 rsurface.modeltvector3f = NULL;
8386                 rsurface.modelnormal3f = NULL;
8387         }
8388         rsurface.modelvertexmesh = NULL;
8389         rsurface.modelvertexmeshbuffer = NULL;
8390         rsurface.modelvertex3fbuffer = NULL;
8391         rsurface.modelvertex3f_vertexbuffer = 0;
8392         rsurface.modelvertex3f_bufferoffset = 0;
8393         rsurface.modelsvector3f_vertexbuffer = 0;
8394         rsurface.modelsvector3f_bufferoffset = 0;
8395         rsurface.modeltvector3f_vertexbuffer = 0;
8396         rsurface.modeltvector3f_bufferoffset = 0;
8397         rsurface.modelnormal3f_vertexbuffer = 0;
8398         rsurface.modelnormal3f_bufferoffset = 0;
8399         rsurface.modelgeneratedvertex = true;
8400         rsurface.modellightmapcolor4f  = (float *)color4f;
8401         rsurface.modellightmapcolor4f_vertexbuffer = 0;
8402         rsurface.modellightmapcolor4f_bufferoffset = 0;
8403         rsurface.modeltexcoordtexture2f  = (float *)texcoord2f;
8404         rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
8405         rsurface.modeltexcoordtexture2f_bufferoffset = 0;
8406         rsurface.modeltexcoordlightmap2f  = NULL;
8407         rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
8408         rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
8409         rsurface.modelelement3i = (int *)element3i;
8410         rsurface.modelelement3i_indexbuffer = NULL;
8411         rsurface.modelelement3i_bufferoffset = 0;
8412         rsurface.modelelement3s = (unsigned short *)element3s;
8413         rsurface.modelelement3s_indexbuffer = NULL;
8414         rsurface.modelelement3s_bufferoffset = 0;
8415         rsurface.modellightmapoffsets = NULL;
8416         rsurface.modelsurfaces = NULL;
8417         rsurface.batchgeneratedvertex = false;
8418         rsurface.batchfirstvertex = 0;
8419         rsurface.batchnumvertices = 0;
8420         rsurface.batchfirsttriangle = 0;
8421         rsurface.batchnumtriangles = 0;
8422         rsurface.batchvertex3f  = NULL;
8423         rsurface.batchvertex3f_vertexbuffer = NULL;
8424         rsurface.batchvertex3f_bufferoffset = 0;
8425         rsurface.batchsvector3f = NULL;
8426         rsurface.batchsvector3f_vertexbuffer = NULL;
8427         rsurface.batchsvector3f_bufferoffset = 0;
8428         rsurface.batchtvector3f = NULL;
8429         rsurface.batchtvector3f_vertexbuffer = NULL;
8430         rsurface.batchtvector3f_bufferoffset = 0;
8431         rsurface.batchnormal3f  = NULL;
8432         rsurface.batchnormal3f_vertexbuffer = NULL;
8433         rsurface.batchnormal3f_bufferoffset = 0;
8434         rsurface.batchlightmapcolor4f = NULL;
8435         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
8436         rsurface.batchlightmapcolor4f_bufferoffset = 0;
8437         rsurface.batchtexcoordtexture2f = NULL;
8438         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
8439         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
8440         rsurface.batchtexcoordlightmap2f = NULL;
8441         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
8442         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
8443         rsurface.batchvertexmesh = NULL;
8444         rsurface.batchvertexmeshbuffer = NULL;
8445         rsurface.batchvertex3fbuffer = NULL;
8446         rsurface.batchelement3i = NULL;
8447         rsurface.batchelement3i_indexbuffer = NULL;
8448         rsurface.batchelement3i_bufferoffset = 0;
8449         rsurface.batchelement3s = NULL;
8450         rsurface.batchelement3s_indexbuffer = NULL;
8451         rsurface.batchelement3s_bufferoffset = 0;
8452         rsurface.passcolor4f = NULL;
8453         rsurface.passcolor4f_vertexbuffer = NULL;
8454         rsurface.passcolor4f_bufferoffset = 0;
8455
8456         if (rsurface.modelnumvertices && rsurface.modelelement3i)
8457         {
8458                 if ((wantnormals || wanttangents) && !normal3f)
8459                 {
8460                         rsurface.modelnormal3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
8461                         Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
8462                 }
8463                 if (wanttangents && !svector3f)
8464                 {
8465                         rsurface.modelsvector3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
8466                         rsurface.modeltvector3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
8467                         Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.modelsvector3f, rsurface.modeltvector3f, r_smoothnormals_areaweighting.integer != 0);
8468                 }
8469         }
8470 }
8471
8472 float RSurf_FogPoint(const float *v)
8473 {
8474         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
8475         float FogPlaneViewDist = r_refdef.fogplaneviewdist;
8476         float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
8477         float FogHeightFade = r_refdef.fogheightfade;
8478         float fogfrac;
8479         unsigned int fogmasktableindex;
8480         if (r_refdef.fogplaneviewabove)
8481                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
8482         else
8483                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
8484         fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
8485         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
8486 }
8487
8488 float RSurf_FogVertex(const float *v)
8489 {
8490         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
8491         float FogPlaneViewDist = rsurface.fogplaneviewdist;
8492         float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
8493         float FogHeightFade = rsurface.fogheightfade;
8494         float fogfrac;
8495         unsigned int fogmasktableindex;
8496         if (r_refdef.fogplaneviewabove)
8497                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
8498         else
8499                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
8500         fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
8501         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
8502 }
8503
8504 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
8505 {
8506         int i;
8507         for (i = 0;i < numelements;i++)
8508                 outelement3i[i] = inelement3i[i] + adjust;
8509 }
8510
8511 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
8512 extern cvar_t gl_vbo;
8513 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
8514 {
8515         int deformindex;
8516         int firsttriangle;
8517         int numtriangles;
8518         int firstvertex;
8519         int endvertex;
8520         int numvertices;
8521         int surfacefirsttriangle;
8522         int surfacenumtriangles;
8523         int surfacefirstvertex;
8524         int surfaceendvertex;
8525         int surfacenumvertices;
8526         int batchnumvertices;
8527         int batchnumtriangles;
8528         int needsupdate;
8529         int i, j;
8530         qboolean gaps;
8531         qboolean dynamicvertex;
8532         float amplitude;
8533         float animpos;
8534         float scale;
8535         float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
8536         float waveparms[4];
8537         q3shaderinfo_deform_t *deform;
8538         const msurface_t *surface, *firstsurface;
8539         r_vertexmesh_t *vertexmesh;
8540         if (!texturenumsurfaces)
8541                 return;
8542         // find vertex range of this surface batch
8543         gaps = false;
8544         firstsurface = texturesurfacelist[0];
8545         firsttriangle = firstsurface->num_firsttriangle;
8546         batchnumvertices = 0;
8547         batchnumtriangles = 0;
8548         firstvertex = endvertex = firstsurface->num_firstvertex;
8549         for (i = 0;i < texturenumsurfaces;i++)
8550         {
8551                 surface = texturesurfacelist[i];
8552                 if (surface != firstsurface + i)
8553                         gaps = true;
8554                 surfacefirstvertex = surface->num_firstvertex;
8555                 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
8556                 surfacenumvertices = surface->num_vertices;
8557                 surfacenumtriangles = surface->num_triangles;
8558                 if (firstvertex > surfacefirstvertex)
8559                         firstvertex = surfacefirstvertex;
8560                 if (endvertex < surfaceendvertex)
8561                         endvertex = surfaceendvertex;
8562                 batchnumvertices += surfacenumvertices;
8563                 batchnumtriangles += surfacenumtriangles;
8564         }
8565
8566         // we now know the vertex range used, and if there are any gaps in it
8567         rsurface.batchfirstvertex = firstvertex;
8568         rsurface.batchnumvertices = endvertex - firstvertex;
8569         rsurface.batchfirsttriangle = firsttriangle;
8570         rsurface.batchnumtriangles = batchnumtriangles;
8571
8572         // this variable holds flags for which properties have been updated that
8573         // may require regenerating vertexmesh array...
8574         needsupdate = 0;
8575
8576         // check if any dynamic vertex processing must occur
8577         dynamicvertex = false;
8578
8579         // if there is a chance of animated vertex colors, it's a dynamic batch
8580         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
8581         {
8582                 dynamicvertex = true;
8583                 batchneed |= BATCHNEED_NOGAPS;
8584                 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR;
8585         }
8586
8587         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform && r_deformvertexes.integer;deformindex++, deform++)
8588         {
8589                 switch (deform->deform)
8590                 {
8591                 default:
8592                 case Q3DEFORM_PROJECTIONSHADOW:
8593                 case Q3DEFORM_TEXT0:
8594                 case Q3DEFORM_TEXT1:
8595                 case Q3DEFORM_TEXT2:
8596                 case Q3DEFORM_TEXT3:
8597                 case Q3DEFORM_TEXT4:
8598                 case Q3DEFORM_TEXT5:
8599                 case Q3DEFORM_TEXT6:
8600                 case Q3DEFORM_TEXT7:
8601                 case Q3DEFORM_NONE:
8602                         break;
8603                 case Q3DEFORM_AUTOSPRITE:
8604                         dynamicvertex = true;
8605                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
8606                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
8607                         break;
8608                 case Q3DEFORM_AUTOSPRITE2:
8609                         dynamicvertex = true;
8610                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
8611                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
8612                         break;
8613                 case Q3DEFORM_NORMAL:
8614                         dynamicvertex = true;
8615                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
8616                         needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
8617                         break;
8618                 case Q3DEFORM_WAVE:
8619                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
8620                                 break; // if wavefunc is a nop, ignore this transform
8621                         dynamicvertex = true;
8622                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
8623                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
8624                         break;
8625                 case Q3DEFORM_BULGE:
8626                         dynamicvertex = true;
8627                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
8628                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
8629                         break;
8630                 case Q3DEFORM_MOVE:
8631                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
8632                                 break; // if wavefunc is a nop, ignore this transform
8633                         dynamicvertex = true;
8634                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
8635                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX;
8636                         break;
8637                 }
8638         }
8639         switch(rsurface.texture->tcgen.tcgen)
8640         {
8641         default:
8642         case Q3TCGEN_TEXTURE:
8643                 break;
8644         case Q3TCGEN_LIGHTMAP:
8645                 dynamicvertex = true;
8646                 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
8647                 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
8648                 break;
8649         case Q3TCGEN_VECTOR:
8650                 dynamicvertex = true;
8651                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
8652                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
8653                 break;
8654         case Q3TCGEN_ENVIRONMENT:
8655                 dynamicvertex = true;
8656                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
8657                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
8658                 break;
8659         }
8660         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
8661         {
8662                 dynamicvertex = true;
8663                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
8664                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
8665         }
8666
8667         if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
8668         {
8669                 dynamicvertex = true;
8670                 batchneed |= BATCHNEED_NOGAPS;
8671                 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
8672         }
8673
8674         if (dynamicvertex || gaps || rsurface.batchfirstvertex)
8675         {
8676                 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
8677                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)      batchneed |= BATCHNEED_ARRAY_VERTEX;
8678                 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)      batchneed |= BATCHNEED_ARRAY_NORMAL;
8679                 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)      batchneed |= BATCHNEED_ARRAY_VECTOR;
8680                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
8681                 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)    batchneed |= BATCHNEED_ARRAY_TEXCOORD;
8682                 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP)    batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
8683         }
8684
8685         // when the model data has no vertex buffer (dynamic mesh), we need to
8686         // eliminate gaps
8687         if (vid.useinterleavedarrays ? !rsurface.modelvertexmeshbuffer : !rsurface.modelvertex3f_vertexbuffer)
8688                 batchneed |= BATCHNEED_NOGAPS;
8689
8690         // if needsupdate, we have to do a dynamic vertex batch for sure
8691         if (needsupdate & batchneed)
8692                 dynamicvertex = true;
8693
8694         // see if we need to build vertexmesh from arrays
8695         if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
8696                 dynamicvertex = true;
8697
8698         // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
8699         // also some drivers strongly dislike firstvertex
8700         if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
8701                 dynamicvertex = true;
8702
8703         rsurface.batchvertex3f = rsurface.modelvertex3f;
8704         rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
8705         rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
8706         rsurface.batchsvector3f = rsurface.modelsvector3f;
8707         rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
8708         rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
8709         rsurface.batchtvector3f = rsurface.modeltvector3f;
8710         rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
8711         rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
8712         rsurface.batchnormal3f = rsurface.modelnormal3f;
8713         rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
8714         rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
8715         rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
8716         rsurface.batchlightmapcolor4f_vertexbuffer  = rsurface.modellightmapcolor4f_vertexbuffer;
8717         rsurface.batchlightmapcolor4f_bufferoffset  = rsurface.modellightmapcolor4f_bufferoffset;
8718         rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
8719         rsurface.batchtexcoordtexture2f_vertexbuffer  = rsurface.modeltexcoordtexture2f_vertexbuffer;
8720         rsurface.batchtexcoordtexture2f_bufferoffset  = rsurface.modeltexcoordtexture2f_bufferoffset;
8721         rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
8722         rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
8723         rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
8724         rsurface.batchvertex3fbuffer = rsurface.modelvertex3fbuffer;
8725         rsurface.batchvertexmesh = rsurface.modelvertexmesh;
8726         rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
8727         rsurface.batchelement3i = rsurface.modelelement3i;
8728         rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
8729         rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
8730         rsurface.batchelement3s = rsurface.modelelement3s;
8731         rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
8732         rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
8733
8734         // if any dynamic vertex processing has to occur in software, we copy the
8735         // entire surface list together before processing to rebase the vertices
8736         // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
8737         //
8738         // if any gaps exist and we do not have a static vertex buffer, we have to
8739         // copy the surface list together to avoid wasting upload bandwidth on the
8740         // vertices in the gaps.
8741         //
8742         // if gaps exist and we have a static vertex buffer, we still have to
8743         // combine the index buffer ranges into one dynamic index buffer.
8744         //
8745         // in all cases we end up with data that can be drawn in one call.
8746
8747         if (!dynamicvertex)
8748         {
8749                 // static vertex data, just set pointers...
8750                 rsurface.batchgeneratedvertex = false;
8751                 // if there are gaps, we want to build a combined index buffer,
8752                 // otherwise use the original static buffer with an appropriate offset
8753                 if (gaps)
8754                 {
8755                         // build a new triangle elements array for this batch
8756                         rsurface.batchelement3i = (int *)R_FrameData_Alloc(batchnumtriangles * sizeof(int[3]));
8757                         rsurface.batchfirsttriangle = 0;
8758                         numtriangles = 0;
8759                         for (i = 0;i < texturenumsurfaces;i++)
8760                         {
8761                                 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
8762                                 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
8763                                 memcpy(rsurface.batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
8764                                 numtriangles += surfacenumtriangles;
8765                         }
8766                         rsurface.batchelement3i_indexbuffer = NULL;
8767                         rsurface.batchelement3i_bufferoffset = 0;
8768                         rsurface.batchelement3s = NULL;
8769                         rsurface.batchelement3s_indexbuffer = NULL;
8770                         rsurface.batchelement3s_bufferoffset = 0;
8771                         if (endvertex <= 65536)
8772                         {
8773                                 // make a 16bit (unsigned short) index array if possible
8774                                 rsurface.batchelement3s = (unsigned short *)R_FrameData_Alloc(batchnumtriangles * sizeof(unsigned short[3]));
8775                                 for (i = 0;i < numtriangles*3;i++)
8776                                         rsurface.batchelement3s[i] = rsurface.batchelement3i[i];
8777                         }
8778                 }
8779                 return;
8780         }
8781
8782         // something needs software processing, do it for real...
8783         // we only directly handle separate array data in this case and then
8784         // generate interleaved data if needed...
8785         rsurface.batchgeneratedvertex = true;
8786
8787         // now copy the vertex data into a combined array and make an index array
8788         // (this is what Quake3 does all the time)
8789         //if (gaps || rsurface.batchfirstvertex)
8790         {
8791                 rsurface.batchvertex3fbuffer = NULL;
8792                 rsurface.batchvertexmesh = NULL;
8793                 rsurface.batchvertexmeshbuffer = NULL;
8794                 rsurface.batchvertex3f = NULL;
8795                 rsurface.batchvertex3f_vertexbuffer = NULL;
8796                 rsurface.batchvertex3f_bufferoffset = 0;
8797                 rsurface.batchsvector3f = NULL;
8798                 rsurface.batchsvector3f_vertexbuffer = NULL;
8799                 rsurface.batchsvector3f_bufferoffset = 0;
8800                 rsurface.batchtvector3f = NULL;
8801                 rsurface.batchtvector3f_vertexbuffer = NULL;
8802                 rsurface.batchtvector3f_bufferoffset = 0;
8803                 rsurface.batchnormal3f = NULL;
8804                 rsurface.batchnormal3f_vertexbuffer = NULL;
8805                 rsurface.batchnormal3f_bufferoffset = 0;
8806                 rsurface.batchlightmapcolor4f = NULL;
8807                 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
8808                 rsurface.batchlightmapcolor4f_bufferoffset = 0;
8809                 rsurface.batchtexcoordtexture2f = NULL;
8810                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
8811                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
8812                 rsurface.batchtexcoordlightmap2f = NULL;
8813                 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
8814                 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
8815                 rsurface.batchelement3i = (int *)R_FrameData_Alloc(batchnumtriangles * sizeof(int[3]));
8816                 rsurface.batchelement3i_indexbuffer = NULL;
8817                 rsurface.batchelement3i_bufferoffset = 0;
8818                 rsurface.batchelement3s = NULL;
8819                 rsurface.batchelement3s_indexbuffer = NULL;
8820                 rsurface.batchelement3s_bufferoffset = 0;
8821                 // we'll only be setting up certain arrays as needed
8822                 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
8823                         rsurface.batchvertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(batchnumvertices * sizeof(r_vertexmesh_t));
8824                 if (batchneed & BATCHNEED_ARRAY_VERTEX)
8825                         rsurface.batchvertex3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
8826                 if (batchneed & BATCHNEED_ARRAY_NORMAL)
8827                         rsurface.batchnormal3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
8828                 if (batchneed & BATCHNEED_ARRAY_VECTOR)
8829                 {
8830                         rsurface.batchsvector3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
8831                         rsurface.batchtvector3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
8832                 }
8833                 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
8834                         rsurface.batchlightmapcolor4f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[4]));
8835                 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
8836                         rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
8837                 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
8838                         rsurface.batchtexcoordlightmap2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
8839                 numvertices = 0;
8840                 numtriangles = 0;
8841                 for (i = 0;i < texturenumsurfaces;i++)
8842                 {
8843                         surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
8844                         surfacenumvertices = texturesurfacelist[i]->num_vertices;
8845                         surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
8846                         surfacenumtriangles = texturesurfacelist[i]->num_triangles;
8847                         // copy only the data requested
8848                         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
8849                                 memcpy(rsurface.batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
8850                         if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
8851                         {
8852                                 if (batchneed & BATCHNEED_ARRAY_VERTEX)
8853                                 {
8854                                         if (rsurface.batchvertex3f)
8855                                                 memcpy(rsurface.batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
8856                                         else
8857                                                 memset(rsurface.batchvertex3f + 3*numvertices, 0, surfacenumvertices * sizeof(float[3]));
8858                                 }
8859                                 if (batchneed & BATCHNEED_ARRAY_NORMAL)
8860                                 {
8861                                         if (rsurface.modelnormal3f)
8862                                                 memcpy(rsurface.batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
8863                                         else
8864                                                 memset(rsurface.batchnormal3f + 3*numvertices, 0, surfacenumvertices * sizeof(float[3]));
8865                                 }
8866                                 if (batchneed & BATCHNEED_ARRAY_VECTOR)
8867                                 {
8868                                         if (rsurface.modelsvector3f)
8869                                         {
8870                                                 memcpy(rsurface.batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
8871                                                 memcpy(rsurface.batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
8872                                         }
8873                                         else
8874                                         {
8875                                                 memset(rsurface.batchsvector3f + 3*numvertices, 0, surfacenumvertices * sizeof(float[3]));
8876                                                 memset(rsurface.batchtvector3f + 3*numvertices, 0, surfacenumvertices * sizeof(float[3]));
8877                                         }
8878                                 }
8879                                 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
8880                                 {
8881                                         if (rsurface.modellightmapcolor4f)
8882                                                 memcpy(rsurface.batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
8883                                         else
8884                                                 memset(rsurface.batchlightmapcolor4f + 4*numvertices, 0, surfacenumvertices * sizeof(float[4]));
8885                                 }
8886                                 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
8887                                 {
8888                                         if (rsurface.modeltexcoordtexture2f)
8889                                                 memcpy(rsurface.batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
8890                                         else
8891                                                 memset(rsurface.batchtexcoordtexture2f + 2*numvertices, 0, surfacenumvertices * sizeof(float[2]));
8892                                 }
8893                                 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
8894                                 {
8895                                         if (rsurface.modeltexcoordlightmap2f)
8896                                                 memcpy(rsurface.batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
8897                                         else
8898                                                 memset(rsurface.batchtexcoordlightmap2f + 2*numvertices, 0, surfacenumvertices * sizeof(float[2]));
8899                                 }
8900                         }
8901                         RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
8902                         numvertices += surfacenumvertices;
8903                         numtriangles += surfacenumtriangles;
8904                 }
8905
8906                 // generate a 16bit index array as well if possible
8907                 // (in general, dynamic batches fit)
8908                 if (numvertices <= 65536)
8909                 {
8910                         rsurface.batchelement3s = (unsigned short *)R_FrameData_Alloc(batchnumtriangles * sizeof(unsigned short[3]));
8911                         for (i = 0;i < numtriangles*3;i++)
8912                                 rsurface.batchelement3s[i] = rsurface.batchelement3i[i];
8913                 }
8914
8915                 // since we've copied everything, the batch now starts at 0
8916                 rsurface.batchfirstvertex = 0;
8917                 rsurface.batchnumvertices = batchnumvertices;
8918                 rsurface.batchfirsttriangle = 0;
8919                 rsurface.batchnumtriangles = batchnumtriangles;
8920         }
8921
8922         // q1bsp surfaces rendered in vertex color mode have to have colors
8923         // calculated based on lightstyles
8924         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
8925         {
8926                 // generate color arrays for the surfaces in this list
8927                 int c[4];
8928                 int scale;
8929                 int size3;
8930                 const int *offsets;
8931                 const unsigned char *lm;
8932                 rsurface.batchlightmapcolor4f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[4]));
8933                 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
8934                 rsurface.batchlightmapcolor4f_bufferoffset = 0;
8935                 numvertices = 0;
8936                 for (i = 0;i < texturenumsurfaces;i++)
8937                 {
8938                         surface = texturesurfacelist[i];
8939                         offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
8940                         surfacenumvertices = surface->num_vertices;
8941                         if (surface->lightmapinfo->samples)
8942                         {
8943                                 for (j = 0;j < surfacenumvertices;j++)
8944                                 {
8945                                         lm = surface->lightmapinfo->samples + offsets[j];
8946                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
8947                                         VectorScale(lm, scale, c);
8948                                         if (surface->lightmapinfo->styles[1] != 255)
8949                                         {
8950                                                 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
8951                                                 lm += size3;
8952                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
8953                                                 VectorMA(c, scale, lm, c);
8954                                                 if (surface->lightmapinfo->styles[2] != 255)
8955                                                 {
8956                                                         lm += size3;
8957                                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
8958                                                         VectorMA(c, scale, lm, c);
8959                                                         if (surface->lightmapinfo->styles[3] != 255)
8960                                                         {
8961                                                                 lm += size3;
8962                                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
8963                                                                 VectorMA(c, scale, lm, c);
8964                                                         }
8965                                                 }
8966                                         }
8967                                         c[0] >>= 7;
8968                                         c[1] >>= 7;
8969                                         c[2] >>= 7;
8970                                         Vector4Set(rsurface.batchlightmapcolor4f + 4*numvertices, min(c[0], 255) * (1.0f / 255.0f), min(c[1], 255) * (1.0f / 255.0f), min(c[2], 255) * (1.0f / 255.0f), 1);
8971                                         numvertices++;
8972                                 }
8973                         }
8974                         else
8975                         {
8976                                 for (j = 0;j < surfacenumvertices;j++)
8977                                 {
8978                                         Vector4Set(rsurface.batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
8979                                         numvertices++;
8980                                 }
8981                         }
8982                 }
8983         }
8984
8985         // if vertices are deformed (sprite flares and things in maps, possibly
8986         // water waves, bulges and other deformations), modify the copied vertices
8987         // in place
8988         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform && r_deformvertexes.integer;deformindex++, deform++)
8989         {
8990                 switch (deform->deform)
8991                 {
8992                 default:
8993                 case Q3DEFORM_PROJECTIONSHADOW:
8994                 case Q3DEFORM_TEXT0:
8995                 case Q3DEFORM_TEXT1:
8996                 case Q3DEFORM_TEXT2:
8997                 case Q3DEFORM_TEXT3:
8998                 case Q3DEFORM_TEXT4:
8999                 case Q3DEFORM_TEXT5:
9000                 case Q3DEFORM_TEXT6:
9001                 case Q3DEFORM_TEXT7:
9002                 case Q3DEFORM_NONE:
9003                         break;
9004                 case Q3DEFORM_AUTOSPRITE:
9005                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
9006                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
9007                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
9008                         VectorNormalize(newforward);
9009                         VectorNormalize(newright);
9010                         VectorNormalize(newup);
9011 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
9012 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
9013 //                      rsurface.batchvertex3f_bufferoffset = 0;
9014 //                      rsurface.batchsvector3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchsvector3f);
9015 //                      rsurface.batchsvector3f_vertexbuffer = NULL;
9016 //                      rsurface.batchsvector3f_bufferoffset = 0;
9017 //                      rsurface.batchtvector3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchtvector3f);
9018 //                      rsurface.batchtvector3f_vertexbuffer = NULL;
9019 //                      rsurface.batchtvector3f_bufferoffset = 0;
9020 //                      rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
9021 //                      rsurface.batchnormal3f_vertexbuffer = NULL;
9022 //                      rsurface.batchnormal3f_bufferoffset = 0;
9023                         // sometimes we're on a renderpath that does not use vectors (GL11/GL13/GLES1)
9024                         if (!VectorLength2(rsurface.batchnormal3f + 3*rsurface.batchfirstvertex))
9025                                 Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
9026                         if (!VectorLength2(rsurface.batchsvector3f + 3*rsurface.batchfirstvertex))
9027                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
9028                         // a single autosprite surface can contain multiple sprites...
9029                         for (j = 0;j < batchnumvertices - 3;j += 4)
9030                         {
9031                                 VectorClear(center);
9032                                 for (i = 0;i < 4;i++)
9033                                         VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
9034                                 VectorScale(center, 0.25f, center);
9035                                 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
9036                                 VectorCopy(rsurface.batchsvector3f + 3*j, right);
9037                                 VectorCopy(rsurface.batchtvector3f + 3*j, up);
9038                                 for (i = 0;i < 4;i++)
9039                                 {
9040                                         VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
9041                                         VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.batchvertex3f + 3*(j+i));
9042                                 }
9043                         }
9044                         // if we get here, BATCHNEED_ARRAY_NORMAL and BATCHNEED_ARRAY_VECTOR are in batchneed, so no need to check
9045                         Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
9046                         Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
9047                         break;
9048                 case Q3DEFORM_AUTOSPRITE2:
9049                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
9050                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
9051                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
9052                         VectorNormalize(newforward);
9053                         VectorNormalize(newright);
9054                         VectorNormalize(newup);
9055 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
9056 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
9057 //                      rsurface.batchvertex3f_bufferoffset = 0;
9058                         {
9059                                 const float *v1, *v2;
9060                                 vec3_t start, end;
9061                                 float f, l;
9062                                 struct
9063                                 {
9064                                         float length2;
9065                                         const float *v1;
9066                                         const float *v2;
9067                                 }
9068                                 shortest[2];
9069                                 memset(shortest, 0, sizeof(shortest));
9070                                 // a single autosprite surface can contain multiple sprites...
9071                                 for (j = 0;j < batchnumvertices - 3;j += 4)
9072                                 {
9073                                         VectorClear(center);
9074                                         for (i = 0;i < 4;i++)
9075                                                 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
9076                                         VectorScale(center, 0.25f, center);
9077                                         // find the two shortest edges, then use them to define the
9078                                         // axis vectors for rotating around the central axis
9079                                         for (i = 0;i < 6;i++)
9080                                         {
9081                                                 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
9082                                                 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
9083                                                 l = VectorDistance2(v1, v2);
9084                                                 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
9085                                                 if (v1[2] != v2[2])
9086                                                         l += (1.0f / 1024.0f);
9087                                                 if (shortest[0].length2 > l || i == 0)
9088                                                 {
9089                                                         shortest[1] = shortest[0];
9090                                                         shortest[0].length2 = l;
9091                                                         shortest[0].v1 = v1;
9092                                                         shortest[0].v2 = v2;
9093                                                 }
9094                                                 else if (shortest[1].length2 > l || i == 1)
9095                                                 {
9096                                                         shortest[1].length2 = l;
9097                                                         shortest[1].v1 = v1;
9098                                                         shortest[1].v2 = v2;
9099                                                 }
9100                                         }
9101                                         VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
9102                                         VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
9103                                         // this calculates the right vector from the shortest edge
9104                                         // and the up vector from the edge midpoints
9105                                         VectorSubtract(shortest[0].v1, shortest[0].v2, right);
9106                                         VectorNormalize(right);
9107                                         VectorSubtract(end, start, up);
9108                                         VectorNormalize(up);
9109                                         // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
9110                                         VectorSubtract(rsurface.localvieworigin, center, forward);
9111                                         //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
9112                                         VectorNegate(forward, forward);
9113                                         VectorReflect(forward, 0, up, forward);
9114                                         VectorNormalize(forward);
9115                                         CrossProduct(up, forward, newright);
9116                                         VectorNormalize(newright);
9117                                         // rotate the quad around the up axis vector, this is made
9118                                         // especially easy by the fact we know the quad is flat,
9119                                         // so we only have to subtract the center position and
9120                                         // measure distance along the right vector, and then
9121                                         // multiply that by the newright vector and add back the
9122                                         // center position
9123                                         // we also need to subtract the old position to undo the
9124                                         // displacement from the center, which we do with a
9125                                         // DotProduct, the subtraction/addition of center is also
9126                                         // optimized into DotProducts here
9127                                         l = DotProduct(right, center);
9128                                         for (i = 0;i < 4;i++)
9129                                         {
9130                                                 v1 = rsurface.batchvertex3f + 3*(j+i);
9131                                                 f = DotProduct(right, v1) - l;
9132                                                 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.batchvertex3f + 3*(j+i));
9133                                         }
9134                                 }
9135                         }
9136                         if(batchneed & (BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR)) // otherwise these can stay NULL
9137                         {
9138 //                              rsurface.batchnormal3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9139 //                              rsurface.batchnormal3f_vertexbuffer = NULL;
9140 //                              rsurface.batchnormal3f_bufferoffset = 0;
9141                                 Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
9142                         }
9143                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
9144                         {
9145 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9146 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
9147 //                              rsurface.batchsvector3f_bufferoffset = 0;
9148 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9149 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
9150 //                              rsurface.batchtvector3f_bufferoffset = 0;
9151                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
9152                         }
9153                         break;
9154                 case Q3DEFORM_NORMAL:
9155                         // deform the normals to make reflections wavey
9156                         rsurface.batchnormal3f = (float *)R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
9157                         rsurface.batchnormal3f_vertexbuffer = NULL;
9158                         rsurface.batchnormal3f_bufferoffset = 0;
9159                         for (j = 0;j < batchnumvertices;j++)
9160                         {
9161                                 float vertex[3];
9162                                 float *normal = rsurface.batchnormal3f + 3*j;
9163                                 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
9164                                 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f(      vertex[0], vertex[1], vertex[2], rsurface.shadertime * deform->parms[1]);
9165                                 normal[1] = rsurface.batchnormal3f[j*3+1] + deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], rsurface.shadertime * deform->parms[1]);
9166                                 normal[2] = rsurface.batchnormal3f[j*3+2] + deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], rsurface.shadertime * deform->parms[1]);
9167                                 VectorNormalize(normal);
9168                         }
9169                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
9170                         {
9171 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9172 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
9173 //                              rsurface.batchsvector3f_bufferoffset = 0;
9174 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9175 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
9176 //                              rsurface.batchtvector3f_bufferoffset = 0;
9177                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
9178                         }
9179                         break;
9180                 case Q3DEFORM_WAVE:
9181                         // deform vertex array to make wavey water and flags and such
9182                         waveparms[0] = deform->waveparms[0];
9183                         waveparms[1] = deform->waveparms[1];
9184                         waveparms[2] = deform->waveparms[2];
9185                         waveparms[3] = deform->waveparms[3];
9186                         if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
9187                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
9188                         // this is how a divisor of vertex influence on deformation
9189                         animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
9190                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
9191 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
9192 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
9193 //                      rsurface.batchvertex3f_bufferoffset = 0;
9194 //                      rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
9195 //                      rsurface.batchnormal3f_vertexbuffer = NULL;
9196 //                      rsurface.batchnormal3f_bufferoffset = 0;
9197                         for (j = 0;j < batchnumvertices;j++)
9198                         {
9199                                 // if the wavefunc depends on time, evaluate it per-vertex
9200                                 if (waveparms[3])
9201                                 {
9202                                         waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
9203                                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
9204                                 }
9205                                 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.batchvertex3f + 3*j);
9206                         }
9207                         // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
9208                         Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
9209                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
9210                         {
9211 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9212 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
9213 //                              rsurface.batchsvector3f_bufferoffset = 0;
9214 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9215 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
9216 //                              rsurface.batchtvector3f_bufferoffset = 0;
9217                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
9218                         }
9219                         break;
9220                 case Q3DEFORM_BULGE:
9221                         // deform vertex array to make the surface have moving bulges
9222 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
9223 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
9224 //                      rsurface.batchvertex3f_bufferoffset = 0;
9225 //                      rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
9226 //                      rsurface.batchnormal3f_vertexbuffer = NULL;
9227 //                      rsurface.batchnormal3f_bufferoffset = 0;
9228                         for (j = 0;j < batchnumvertices;j++)
9229                         {
9230                                 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + rsurface.shadertime * deform->parms[2]) * deform->parms[1];
9231                                 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.batchvertex3f + 3*j);
9232                         }
9233                         // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
9234                         Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
9235                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
9236                         {
9237 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9238 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
9239 //                              rsurface.batchsvector3f_bufferoffset = 0;
9240 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
9241 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
9242 //                              rsurface.batchtvector3f_bufferoffset = 0;
9243                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
9244                         }
9245                         break;
9246                 case Q3DEFORM_MOVE:
9247                         // deform vertex array
9248                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
9249                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
9250                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
9251                         VectorScale(deform->parms, scale, waveparms);
9252 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
9253 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
9254 //                      rsurface.batchvertex3f_bufferoffset = 0;
9255                         for (j = 0;j < batchnumvertices;j++)
9256                                 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.batchvertex3f + 3*j);
9257                         break;
9258                 }
9259         }
9260
9261         // generate texcoords based on the chosen texcoord source
9262         switch(rsurface.texture->tcgen.tcgen)
9263         {
9264         default:
9265         case Q3TCGEN_TEXTURE:
9266                 break;
9267         case Q3TCGEN_LIGHTMAP:
9268 //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
9269 //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9270 //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9271                 if (rsurface.batchtexcoordlightmap2f)
9272                         memcpy(rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, batchnumvertices * sizeof(float[2]));
9273                 break;
9274         case Q3TCGEN_VECTOR:
9275 //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
9276 //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9277 //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9278                 for (j = 0;j < batchnumvertices;j++)
9279                 {
9280                         rsurface.batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
9281                         rsurface.batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
9282                 }
9283                 break;
9284         case Q3TCGEN_ENVIRONMENT:
9285                 // make environment reflections using a spheremap
9286                 rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
9287                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9288                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9289                 for (j = 0;j < batchnumvertices;j++)
9290                 {
9291                         // identical to Q3A's method, but executed in worldspace so
9292                         // carried models can be shiny too
9293
9294                         float viewer[3], d, reflected[3], worldreflected[3];
9295
9296                         VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
9297                         // VectorNormalize(viewer);
9298
9299                         d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
9300
9301                         reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
9302                         reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
9303                         reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
9304                         // note: this is proportinal to viewer, so we can normalize later
9305
9306                         Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
9307                         VectorNormalize(worldreflected);
9308
9309                         // note: this sphere map only uses world x and z!
9310                         // so positive and negative y will LOOK THE SAME.
9311                         rsurface.batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
9312                         rsurface.batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
9313                 }
9314                 break;
9315         }
9316         // the only tcmod that needs software vertex processing is turbulent, so
9317         // check for it here and apply the changes if needed
9318         // and we only support that as the first one
9319         // (handling a mixture of turbulent and other tcmods would be problematic
9320         //  without punting it entirely to a software path)
9321         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
9322         {
9323                 amplitude = rsurface.texture->tcmods[0].parms[1];
9324                 animpos = rsurface.texture->tcmods[0].parms[2] + rsurface.shadertime * rsurface.texture->tcmods[0].parms[3];
9325 //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
9326 //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9327 //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9328                 for (j = 0;j < batchnumvertices;j++)
9329                 {
9330                         rsurface.batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
9331                         rsurface.batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1]                                ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
9332                 }
9333         }
9334
9335         if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
9336         {
9337                 // convert the modified arrays to vertex structs
9338 //              rsurface.batchvertexmesh = R_FrameData_Alloc(batchnumvertices * sizeof(r_vertexmesh_t));
9339 //              rsurface.batchvertexmeshbuffer = NULL;
9340                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
9341                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
9342                                 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
9343                 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
9344                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
9345                                 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
9346                 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
9347                 {
9348                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
9349                         {
9350                                 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
9351                                 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
9352                         }
9353                 }
9354                 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
9355                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
9356                                 Vector4Copy(rsurface.batchlightmapcolor4f + 4*j, vertexmesh->color4f);
9357                 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
9358                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
9359                                 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
9360                 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
9361                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
9362                                 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
9363         }
9364 }
9365
9366 void RSurf_DrawBatch(void)
9367 {
9368         // sometimes a zero triangle surface (usually a degenerate patch) makes it
9369         // through the pipeline, killing it earlier in the pipeline would have
9370         // per-surface overhead rather than per-batch overhead, so it's best to
9371         // reject it here, before it hits glDraw.
9372         if (rsurface.batchnumtriangles == 0)
9373                 return;
9374 #if 0
9375         // batch debugging code
9376         if (r_test.integer && rsurface.entity == r_refdef.scene.worldentity && rsurface.batchvertex3f == r_refdef.scene.worldentity->model->surfmesh.data_vertex3f)
9377         {
9378                 int i;
9379                 int j;
9380                 int c;
9381                 const int *e;
9382                 e = rsurface.batchelement3i + rsurface.batchfirsttriangle*3;
9383                 for (i = 0;i < rsurface.batchnumtriangles*3;i++)
9384                 {
9385                         c = e[i];
9386                         for (j = 0;j < rsurface.entity->model->num_surfaces;j++)
9387                         {
9388                                 if (c >= rsurface.modelsurfaces[j].num_firstvertex && c < (rsurface.modelsurfaces[j].num_firstvertex + rsurface.modelsurfaces[j].num_vertices))
9389                                 {
9390                                         if (rsurface.modelsurfaces[j].texture != rsurface.texture)
9391                                                 Sys_Error("RSurf_DrawBatch: index %i uses different texture (%s) than surface %i which it belongs to (which uses %s)\n", c, rsurface.texture->name, j, rsurface.modelsurfaces[j].texture->name);
9392                                         break;
9393                                 }
9394                         }
9395                 }
9396         }
9397 #endif
9398         R_Mesh_Draw(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchfirsttriangle, rsurface.batchnumtriangles, rsurface.batchelement3i, rsurface.batchelement3i_indexbuffer, rsurface.batchelement3i_bufferoffset, rsurface.batchelement3s, rsurface.batchelement3s_indexbuffer, rsurface.batchelement3s_bufferoffset);
9399 }
9400
9401 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
9402 {
9403         // pick the closest matching water plane
9404         int planeindex, vertexindex, bestplaneindex = -1;
9405         float d, bestd;
9406         vec3_t vert;
9407         const float *v;
9408         r_waterstate_waterplane_t *p;
9409         qboolean prepared = false;
9410         bestd = 0;
9411         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
9412         {
9413                 if(p->camera_entity != rsurface.texture->camera_entity)
9414                         continue;
9415                 d = 0;
9416                 if(!prepared)
9417                 {
9418                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, 1, &surface);
9419                         prepared = true;
9420                         if(rsurface.batchnumvertices == 0)
9421                                 break;
9422                 }
9423                 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
9424                 {
9425                         Matrix4x4_Transform(&rsurface.matrix, v, vert);
9426                         d += fabs(PlaneDiff(vert, &p->plane));
9427                 }
9428                 if (bestd > d || bestplaneindex < 0)
9429                 {
9430                         bestd = d;
9431                         bestplaneindex = planeindex;
9432                 }
9433         }
9434         return bestplaneindex;
9435         // NOTE: this MAY return a totally unrelated water plane; we can ignore
9436         // this situation though, as it might be better to render single larger
9437         // batches with useless stuff (backface culled for example) than to
9438         // render multiple smaller batches
9439 }
9440
9441 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
9442 {
9443         int i;
9444         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9445         rsurface.passcolor4f_vertexbuffer = 0;
9446         rsurface.passcolor4f_bufferoffset = 0;
9447         for (i = 0;i < rsurface.batchnumvertices;i++)
9448                 Vector4Set(rsurface.passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
9449 }
9450
9451 static void RSurf_DrawBatch_GL11_ApplyFog(void)
9452 {
9453         int i;
9454         float f;
9455         const float *v;
9456         const float *c;
9457         float *c2;
9458         if (rsurface.passcolor4f)
9459         {
9460                 // generate color arrays
9461                 c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
9462                 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9463                 rsurface.passcolor4f_vertexbuffer = 0;
9464                 rsurface.passcolor4f_bufferoffset = 0;
9465                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
9466                 {
9467                         f = RSurf_FogVertex(v);
9468                         c2[0] = c[0] * f;
9469                         c2[1] = c[1] * f;
9470                         c2[2] = c[2] * f;
9471                         c2[3] = c[3];
9472                 }
9473         }
9474         else
9475         {
9476                 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9477                 rsurface.passcolor4f_vertexbuffer = 0;
9478                 rsurface.passcolor4f_bufferoffset = 0;
9479                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
9480                 {
9481                         f = RSurf_FogVertex(v);
9482                         c2[0] = f;
9483                         c2[1] = f;
9484                         c2[2] = f;
9485                         c2[3] = 1;
9486                 }
9487         }
9488 }
9489
9490 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
9491 {
9492         int i;
9493         float f;
9494         const float *v;
9495         const float *c;
9496         float *c2;
9497         if (!rsurface.passcolor4f)
9498                 return;
9499         c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
9500         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9501         rsurface.passcolor4f_vertexbuffer = 0;
9502         rsurface.passcolor4f_bufferoffset = 0;
9503         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
9504         {
9505                 f = RSurf_FogVertex(v);
9506                 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
9507                 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
9508                 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
9509                 c2[3] = c[3];
9510         }
9511 }
9512
9513 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
9514 {
9515         int i;
9516         const float *c;
9517         float *c2;
9518         if (!rsurface.passcolor4f)
9519                 return;
9520         c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
9521         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9522         rsurface.passcolor4f_vertexbuffer = 0;
9523         rsurface.passcolor4f_bufferoffset = 0;
9524         for (i = 0, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
9525         {
9526                 c2[0] = c[0] * r;
9527                 c2[1] = c[1] * g;
9528                 c2[2] = c[2] * b;
9529                 c2[3] = c[3] * a;
9530         }
9531 }
9532
9533 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
9534 {
9535         int i;
9536         const float *c;
9537         float *c2;
9538         if (!rsurface.passcolor4f)
9539                 return;
9540         c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
9541         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9542         rsurface.passcolor4f_vertexbuffer = 0;
9543         rsurface.passcolor4f_bufferoffset = 0;
9544         for (i = 0, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
9545         {
9546                 c2[0] = c[0] + r_refdef.scene.ambient;
9547                 c2[1] = c[1] + r_refdef.scene.ambient;
9548                 c2[2] = c[2] + r_refdef.scene.ambient;
9549                 c2[3] = c[3];
9550         }
9551 }
9552
9553 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
9554 {
9555         // TODO: optimize
9556         rsurface.passcolor4f = NULL;
9557         rsurface.passcolor4f_vertexbuffer = 0;
9558         rsurface.passcolor4f_bufferoffset = 0;
9559         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
9560         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
9561         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
9562         GL_Color(r, g, b, a);
9563         R_Mesh_TexBind(0, rsurface.lightmaptexture);
9564         RSurf_DrawBatch();
9565 }
9566
9567 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
9568 {
9569         // TODO: optimize applyfog && applycolor case
9570         // just apply fog if necessary, and tint the fog color array if necessary
9571         rsurface.passcolor4f = NULL;
9572         rsurface.passcolor4f_vertexbuffer = 0;
9573         rsurface.passcolor4f_bufferoffset = 0;
9574         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
9575         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
9576         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
9577         GL_Color(r, g, b, a);
9578         RSurf_DrawBatch();
9579 }
9580
9581 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
9582 {
9583         // TODO: optimize
9584         rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
9585         rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
9586         rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
9587         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
9588         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
9589         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
9590         GL_Color(r, g, b, a);
9591         RSurf_DrawBatch();
9592 }
9593
9594 static void RSurf_DrawBatch_GL11_ClampColor(void)
9595 {
9596         int i;
9597         const float *c1;
9598         float *c2;
9599         if (!rsurface.passcolor4f)
9600                 return;
9601         for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
9602         {
9603                 c2[0] = bound(0.0f, c1[0], 1.0f);
9604                 c2[1] = bound(0.0f, c1[1], 1.0f);
9605                 c2[2] = bound(0.0f, c1[2], 1.0f);
9606                 c2[3] = bound(0.0f, c1[3], 1.0f);
9607         }
9608 }
9609
9610 static void RSurf_DrawBatch_GL11_ApplyFakeLight(void)
9611 {
9612         int i;
9613         float f;
9614         const float *v;
9615         const float *n;
9616         float *c;
9617         //vec3_t eyedir;
9618
9619         // fake shading
9620         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9621         rsurface.passcolor4f_vertexbuffer = 0;
9622         rsurface.passcolor4f_bufferoffset = 0;
9623         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
9624         {
9625                 f = -DotProduct(r_refdef.view.forward, n);
9626                 f = max(0, f);
9627                 f = f * 0.85 + 0.15; // work around so stuff won't get black
9628                 f *= r_refdef.lightmapintensity;
9629                 Vector4Set(c, f, f, f, 1);
9630         }
9631 }
9632
9633 static void RSurf_DrawBatch_GL11_FakeLight(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
9634 {
9635         RSurf_DrawBatch_GL11_ApplyFakeLight();
9636         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
9637         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
9638         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
9639         GL_Color(r, g, b, a);
9640         RSurf_DrawBatch();
9641 }
9642
9643 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
9644 {
9645         int i;
9646         float f;
9647         float alpha;
9648         const float *v;
9649         const float *n;
9650         float *c;
9651         vec3_t ambientcolor;
9652         vec3_t diffusecolor;
9653         vec3_t lightdir;
9654         // TODO: optimize
9655         // model lighting
9656         VectorCopy(rsurface.modellight_lightdir, lightdir);
9657         f = 0.5f * r_refdef.lightmapintensity;
9658         ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
9659         ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
9660         ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
9661         diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
9662         diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
9663         diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
9664         alpha = *a;
9665         if (VectorLength2(diffusecolor) > 0)
9666         {
9667                 // q3-style directional shading
9668                 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9669                 rsurface.passcolor4f_vertexbuffer = 0;
9670                 rsurface.passcolor4f_bufferoffset = 0;
9671                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
9672                 {
9673                         if ((f = DotProduct(n, lightdir)) > 0)
9674                                 VectorMA(ambientcolor, f, diffusecolor, c);
9675                         else
9676                                 VectorCopy(ambientcolor, c);
9677                         c[3] = alpha;
9678                 }
9679                 *r = 1;
9680                 *g = 1;
9681                 *b = 1;
9682                 *a = 1;
9683                 *applycolor = false;
9684         }
9685         else
9686         {
9687                 *r = ambientcolor[0];
9688                 *g = ambientcolor[1];
9689                 *b = ambientcolor[2];
9690                 rsurface.passcolor4f = NULL;
9691                 rsurface.passcolor4f_vertexbuffer = 0;
9692                 rsurface.passcolor4f_bufferoffset = 0;
9693         }
9694 }
9695
9696 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
9697 {
9698         RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
9699         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
9700         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
9701         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
9702         GL_Color(r, g, b, a);
9703         RSurf_DrawBatch();
9704 }
9705
9706 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
9707 {
9708         int i;
9709         float f;
9710         const float *v;
9711         float *c;
9712
9713         // fake shading
9714         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
9715         rsurface.passcolor4f_vertexbuffer = 0;
9716         rsurface.passcolor4f_bufferoffset = 0;
9717
9718         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
9719         {
9720                 f = 1 - RSurf_FogVertex(v);
9721                 c[0] = r;
9722                 c[1] = g;
9723                 c[2] = b;
9724                 c[3] = f * a;
9725         }
9726 }
9727
9728 void RSurf_SetupDepthAndCulling(void)
9729 {
9730         // submodels are biased to avoid z-fighting with world surfaces that they
9731         // may be exactly overlapping (avoids z-fighting artifacts on certain
9732         // doors and things in Quake maps)
9733         GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
9734         GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
9735         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
9736         GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
9737 }
9738
9739 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
9740 {
9741         // transparent sky would be ridiculous
9742         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
9743                 return;
9744         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
9745         skyrenderlater = true;
9746         RSurf_SetupDepthAndCulling();
9747         GL_DepthMask(true);
9748         // LordHavoc: HalfLife maps have freaky skypolys so don't use
9749         // skymasking on them, and Quake3 never did sky masking (unlike
9750         // software Quake and software Quake2), so disable the sky masking
9751         // in Quake3 maps as it causes problems with q3map2 sky tricks,
9752         // and skymasking also looks very bad when noclipping outside the
9753         // level, so don't use it then either.
9754         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis && !r_trippy.integer)
9755         {
9756                 R_Mesh_ResetTextureState();
9757                 if (skyrendermasked)
9758                 {
9759                         R_SetupShader_DepthOrShadow(false);
9760                         // depth-only (masking)
9761                         GL_ColorMask(0,0,0,0);
9762                         // just to make sure that braindead drivers don't draw
9763                         // anything despite that colormask...
9764                         GL_BlendFunc(GL_ZERO, GL_ONE);
9765                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
9766                         if (rsurface.batchvertex3fbuffer)
9767                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
9768                         else
9769                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
9770                 }
9771                 else
9772                 {
9773                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
9774                         // fog sky
9775                         GL_BlendFunc(GL_ONE, GL_ZERO);
9776                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
9777                         GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
9778                         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
9779                 }
9780                 RSurf_DrawBatch();
9781                 if (skyrendermasked)
9782                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
9783         }
9784         R_Mesh_ResetTextureState();
9785         GL_Color(1, 1, 1, 1);
9786 }
9787
9788 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
9789 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
9790 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
9791 {
9792         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
9793                 return;
9794         if (prepass)
9795         {
9796                 // render screenspace normalmap to texture
9797                 GL_DepthMask(true);
9798                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist, NULL, false);
9799                 RSurf_DrawBatch();
9800         }
9801
9802         // bind lightmap texture
9803
9804         // water/refraction/reflection/camera surfaces have to be handled specially
9805         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)))
9806         {
9807                 int start, end, startplaneindex;
9808                 for (start = 0;start < texturenumsurfaces;start = end)
9809                 {
9810                         startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
9811                         if(startplaneindex < 0)
9812                         {
9813                                 // this happens if the plane e.g. got backface culled and thus didn't get a water plane. We can just ignore this.
9814                                 // Con_Printf("No matching water plane for surface with material flags 0x%08x - PLEASE DEBUG THIS\n", rsurface.texture->currentmaterialflags);
9815                                 end = start + 1;
9816                                 continue;
9817                         }
9818                         for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
9819                                 ;
9820                         // now that we have a batch using the same planeindex, render it
9821                         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)))
9822                         {
9823                                 // render water or distortion background
9824                                 GL_DepthMask(true);
9825                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex), false);
9826                                 RSurf_DrawBatch();
9827                                 // blend surface on top
9828                                 GL_DepthMask(false);
9829                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, NULL, false);
9830                                 RSurf_DrawBatch();
9831                         }
9832                         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION))
9833                         {
9834                                 // render surface with reflection texture as input
9835                                 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
9836                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex), false);
9837                                 RSurf_DrawBatch();
9838                         }
9839                 }
9840                 return;
9841         }
9842
9843         // render surface batch normally
9844         GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
9845         R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist, NULL, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) != 0);
9846         RSurf_DrawBatch();
9847 }
9848
9849 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
9850 {
9851         // OpenGL 1.3 path - anything not completely ancient
9852         qboolean applycolor;
9853         qboolean applyfog;
9854         int layerindex;
9855         const texturelayer_t *layer;
9856         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
9857         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
9858
9859         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
9860         {
9861                 vec4_t layercolor;
9862                 int layertexrgbscale;
9863                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
9864                 {
9865                         if (layerindex == 0)
9866                                 GL_AlphaTest(true);
9867                         else
9868                         {
9869                                 GL_AlphaTest(false);
9870                                 GL_DepthFunc(GL_EQUAL);
9871                         }
9872                 }
9873                 GL_DepthMask(layer->depthmask && writedepth);
9874                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
9875                 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
9876                 {
9877                         layertexrgbscale = 4;
9878                         VectorScale(layer->color, 0.25f, layercolor);
9879                 }
9880                 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
9881                 {
9882                         layertexrgbscale = 2;
9883                         VectorScale(layer->color, 0.5f, layercolor);
9884                 }
9885                 else
9886                 {
9887                         layertexrgbscale = 1;
9888                         VectorScale(layer->color, 1.0f, layercolor);
9889                 }
9890                 layercolor[3] = layer->color[3];
9891                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
9892                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
9893                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
9894                 switch (layer->type)
9895                 {
9896                 case TEXTURELAYERTYPE_LITTEXTURE:
9897                         // single-pass lightmapped texture with 2x rgbscale
9898                         R_Mesh_TexBind(0, r_texture_white);
9899                         R_Mesh_TexMatrix(0, NULL);
9900                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
9901                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
9902                         R_Mesh_TexBind(1, layer->texture);
9903                         R_Mesh_TexMatrix(1, &layer->texmatrix);
9904                         R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
9905                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
9906                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
9907                                 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
9908                         else if (FAKELIGHT_ENABLED)
9909                                 RSurf_DrawBatch_GL11_FakeLight(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
9910                         else if (rsurface.uselightmaptexture)
9911                                 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
9912                         else
9913                                 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
9914                         break;
9915                 case TEXTURELAYERTYPE_TEXTURE:
9916                         // singletexture unlit texture with transparency support
9917                         R_Mesh_TexBind(0, layer->texture);
9918                         R_Mesh_TexMatrix(0, &layer->texmatrix);
9919                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
9920                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
9921                         R_Mesh_TexBind(1, 0);
9922                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
9923                         RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
9924                         break;
9925                 case TEXTURELAYERTYPE_FOG:
9926                         // singletexture fogging
9927                         if (layer->texture)
9928                         {
9929                                 R_Mesh_TexBind(0, layer->texture);
9930                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
9931                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
9932                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
9933                         }
9934                         else
9935                         {
9936                                 R_Mesh_TexBind(0, 0);
9937                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
9938                         }
9939                         R_Mesh_TexBind(1, 0);
9940                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
9941                         // generate a color array for the fog pass
9942                         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
9943                         RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
9944                         RSurf_DrawBatch();
9945                         break;
9946                 default:
9947                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
9948                 }
9949         }
9950         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
9951         {
9952                 GL_DepthFunc(GL_LEQUAL);
9953                 GL_AlphaTest(false);
9954         }
9955 }
9956
9957 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
9958 {
9959         // OpenGL 1.1 - crusty old voodoo path
9960         qboolean applyfog;
9961         int layerindex;
9962         const texturelayer_t *layer;
9963         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
9964         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
9965
9966         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
9967         {
9968                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
9969                 {
9970                         if (layerindex == 0)
9971                                 GL_AlphaTest(true);
9972                         else
9973                         {
9974                                 GL_AlphaTest(false);
9975                                 GL_DepthFunc(GL_EQUAL);
9976                         }
9977                 }
9978                 GL_DepthMask(layer->depthmask && writedepth);
9979                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
9980                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
9981                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
9982                 switch (layer->type)
9983                 {
9984                 case TEXTURELAYERTYPE_LITTEXTURE:
9985                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
9986                         {
9987                                 // two-pass lit texture with 2x rgbscale
9988                                 // first the lightmap pass
9989                                 R_Mesh_TexBind(0, r_texture_white);
9990                                 R_Mesh_TexMatrix(0, NULL);
9991                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
9992                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
9993                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
9994                                         RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
9995                                 else if (FAKELIGHT_ENABLED)
9996                                         RSurf_DrawBatch_GL11_FakeLight(1, 1, 1, 1, false, false);
9997                                 else if (rsurface.uselightmaptexture)
9998                                         RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
9999                                 else
10000                                         RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
10001                                 // then apply the texture to it
10002                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
10003                                 R_Mesh_TexBind(0, layer->texture);
10004                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
10005                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
10006                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
10007                                 RSurf_DrawBatch_GL11_Unlit(layer->color[0] * 0.5f, layer->color[1] * 0.5f, layer->color[2] * 0.5f, layer->color[3], layer->color[0] != 2 || layer->color[1] != 2 || layer->color[2] != 2 || layer->color[3] != 1, false);
10008                         }
10009                         else
10010                         {
10011                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
10012                                 R_Mesh_TexBind(0, layer->texture);
10013                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
10014                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
10015                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
10016                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
10017                                         RSurf_DrawBatch_GL11_VertexShade(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);
10018                                 else
10019                                         RSurf_DrawBatch_GL11_VertexColor(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);
10020                         }
10021                         break;
10022                 case TEXTURELAYERTYPE_TEXTURE:
10023                         // singletexture unlit texture with transparency support
10024                         R_Mesh_TexBind(0, layer->texture);
10025                         R_Mesh_TexMatrix(0, &layer->texmatrix);
10026                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
10027                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
10028                         RSurf_DrawBatch_GL11_Unlit(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);
10029                         break;
10030                 case TEXTURELAYERTYPE_FOG:
10031                         // singletexture fogging
10032                         if (layer->texture)
10033                         {
10034                                 R_Mesh_TexBind(0, layer->texture);
10035                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
10036                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
10037                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
10038                         }
10039                         else
10040                         {
10041                                 R_Mesh_TexBind(0, 0);
10042                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
10043                         }
10044                         // generate a color array for the fog pass
10045                         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
10046                         RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
10047                         RSurf_DrawBatch();
10048                         break;
10049                 default:
10050                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
10051                 }
10052         }
10053         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
10054         {
10055                 GL_DepthFunc(GL_LEQUAL);
10056                 GL_AlphaTest(false);
10057         }
10058 }
10059
10060 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
10061 {
10062         int vi;
10063         int j;
10064         r_vertexgeneric_t *batchvertex;
10065         float c[4];
10066
10067 //      R_Mesh_ResetTextureState();
10068         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
10069
10070         if(rsurface.texture && rsurface.texture->currentskinframe)
10071         {
10072                 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
10073                 c[3] *= rsurface.texture->currentalpha;
10074         }
10075         else
10076         {
10077                 c[0] = 1;
10078                 c[1] = 0;
10079                 c[2] = 1;
10080                 c[3] = 1;
10081         }
10082
10083         if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
10084         {
10085                 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
10086                 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
10087                 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
10088         }
10089
10090         // brighten it up (as texture value 127 means "unlit")
10091         c[0] *= 2 * r_refdef.view.colorscale;
10092         c[1] *= 2 * r_refdef.view.colorscale;
10093         c[2] *= 2 * r_refdef.view.colorscale;
10094
10095         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
10096                 c[3] *= r_wateralpha.value;
10097
10098         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
10099         {
10100                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
10101                 GL_DepthMask(false);
10102         }
10103         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
10104         {
10105                 GL_BlendFunc(GL_ONE, GL_ONE);
10106                 GL_DepthMask(false);
10107         }
10108         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
10109         {
10110                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
10111                 GL_DepthMask(false);
10112         }
10113         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
10114         {
10115                 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
10116                 GL_DepthMask(false);
10117         }
10118         else
10119         {
10120                 GL_BlendFunc(GL_ONE, GL_ZERO);
10121                 GL_DepthMask(writedepth);
10122         }
10123
10124         if (r_showsurfaces.integer == 3)
10125         {
10126                 rsurface.passcolor4f = NULL;
10127
10128                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
10129                 {
10130                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10131
10132                         rsurface.passcolor4f = NULL;
10133                         rsurface.passcolor4f_vertexbuffer = 0;
10134                         rsurface.passcolor4f_bufferoffset = 0;
10135                 }
10136                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
10137                 {
10138                         qboolean applycolor = true;
10139                         float one = 1.0;
10140
10141                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10142
10143                         r_refdef.lightmapintensity = 1;
10144                         RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
10145                         r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
10146                 }
10147                 else if (FAKELIGHT_ENABLED)
10148                 {
10149                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10150
10151                         r_refdef.lightmapintensity = r_fakelight_intensity.value;
10152                         RSurf_DrawBatch_GL11_ApplyFakeLight();
10153                         r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
10154                 }
10155                 else
10156                 {
10157                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10158
10159                         rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
10160                         rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
10161                         rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
10162                 }
10163
10164                 if(!rsurface.passcolor4f)
10165                         RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
10166
10167                 RSurf_DrawBatch_GL11_ApplyAmbient();
10168                 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
10169                 if(r_refdef.fogenabled)
10170                         RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
10171                 RSurf_DrawBatch_GL11_ClampColor();
10172
10173                 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
10174                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
10175                 RSurf_DrawBatch();
10176         }
10177         else if (!r_refdef.view.showdebug)
10178         {
10179                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10180                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
10181                 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
10182                 {
10183                         VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
10184                         Vector4Set(batchvertex[vi].color4f, 0, 0, 0, 1);
10185                 }
10186                 R_Mesh_PrepareVertices_Generic_Unlock();
10187                 RSurf_DrawBatch();
10188         }
10189         else if (r_showsurfaces.integer == 4)
10190         {
10191                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10192                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
10193                 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
10194                 {
10195                         unsigned char c = (vi << 3) * (1.0f / 256.0f);
10196                         VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
10197                         Vector4Set(batchvertex[vi].color4f, c, c, c, 1);
10198                 }
10199                 R_Mesh_PrepareVertices_Generic_Unlock();
10200                 RSurf_DrawBatch();
10201         }
10202         else if (r_showsurfaces.integer == 2)
10203         {
10204                 const int *e;
10205                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10206                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
10207                 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
10208                 {
10209                         unsigned char c = ((j + rsurface.batchfirsttriangle) << 3) * (1.0f / 256.0f);
10210                         VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
10211                         VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
10212                         VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
10213                         Vector4Set(batchvertex[j*3+0].color4f, c, c, c, 1);
10214                         Vector4Set(batchvertex[j*3+1].color4f, c, c, c, 1);
10215                         Vector4Set(batchvertex[j*3+2].color4f, c, c, c, 1);
10216                 }
10217                 R_Mesh_PrepareVertices_Generic_Unlock();
10218                 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
10219         }
10220         else
10221         {
10222                 int texturesurfaceindex;
10223                 int k;
10224                 const msurface_t *surface;
10225                 float surfacecolor4f[4];
10226                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
10227                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
10228                 vi = 0;
10229                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10230                 {
10231                         surface = texturesurfacelist[texturesurfaceindex];
10232                         k = (int)(((size_t)surface) / sizeof(msurface_t));
10233                         Vector4Set(surfacecolor4f, (k & 0xF) * (1.0f / 16.0f), (k & 0xF0) * (1.0f / 256.0f), (k & 0xF00) * (1.0f / 4096.0f), 1);
10234                         for (j = 0;j < surface->num_vertices;j++)
10235                         {
10236                                 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
10237                                 Vector4Copy(surfacecolor4f, batchvertex[vi].color4f);
10238                                 vi++;
10239                         }
10240                 }
10241                 R_Mesh_PrepareVertices_Generic_Unlock();
10242                 RSurf_DrawBatch();
10243         }
10244 }
10245
10246 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
10247 {
10248         CHECKGLERROR
10249         RSurf_SetupDepthAndCulling();
10250         if (r_showsurfaces.integer)
10251         {
10252                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
10253                 return;
10254         }
10255         switch (vid.renderpath)
10256         {
10257         case RENDERPATH_GL20:
10258         case RENDERPATH_D3D9:
10259         case RENDERPATH_D3D10:
10260         case RENDERPATH_D3D11:
10261         case RENDERPATH_SOFT:
10262         case RENDERPATH_GLES2:
10263                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
10264                 break;
10265         case RENDERPATH_GL13:
10266         case RENDERPATH_GLES1:
10267                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
10268                 break;
10269         case RENDERPATH_GL11:
10270                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
10271                 break;
10272         }
10273         CHECKGLERROR
10274 }
10275
10276 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
10277 {
10278         CHECKGLERROR
10279         RSurf_SetupDepthAndCulling();
10280         if (r_showsurfaces.integer)
10281         {
10282                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
10283                 return;
10284         }
10285         switch (vid.renderpath)
10286         {
10287         case RENDERPATH_GL20:
10288         case RENDERPATH_D3D9:
10289         case RENDERPATH_D3D10:
10290         case RENDERPATH_D3D11:
10291         case RENDERPATH_SOFT:
10292         case RENDERPATH_GLES2:
10293                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
10294                 break;
10295         case RENDERPATH_GL13:
10296         case RENDERPATH_GLES1:
10297                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
10298                 break;
10299         case RENDERPATH_GL11:
10300                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
10301                 break;
10302         }
10303         CHECKGLERROR
10304 }
10305
10306 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
10307 {
10308         int i, j;
10309         int texturenumsurfaces, endsurface;
10310         texture_t *texture;
10311         const msurface_t *surface;
10312         const msurface_t *texturesurfacelist[MESHQUEUE_TRANSPARENT_BATCHSIZE];
10313
10314         // if the model is static it doesn't matter what value we give for
10315         // wantnormals and wanttangents, so this logic uses only rules applicable
10316         // to a model, knowing that they are meaningless otherwise
10317         if (ent == r_refdef.scene.worldentity)
10318                 RSurf_ActiveWorldEntity();
10319         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
10320                 RSurf_ActiveModelEntity(ent, false, false, false);
10321         else
10322         {
10323                 switch (vid.renderpath)
10324                 {
10325                 case RENDERPATH_GL20:
10326                 case RENDERPATH_D3D9:
10327                 case RENDERPATH_D3D10:
10328                 case RENDERPATH_D3D11:
10329                 case RENDERPATH_SOFT:
10330                 case RENDERPATH_GLES2:
10331                         RSurf_ActiveModelEntity(ent, true, true, false);
10332                         break;
10333                 case RENDERPATH_GL11:
10334                 case RENDERPATH_GL13:
10335                 case RENDERPATH_GLES1:
10336                         RSurf_ActiveModelEntity(ent, true, false, false);
10337                         break;
10338                 }
10339         }
10340
10341         if (r_transparentdepthmasking.integer)
10342         {
10343                 qboolean setup = false;
10344                 for (i = 0;i < numsurfaces;i = j)
10345                 {
10346                         j = i + 1;
10347                         surface = rsurface.modelsurfaces + surfacelist[i];
10348                         texture = surface->texture;
10349                         rsurface.texture = R_GetCurrentTexture(texture);
10350                         rsurface.lightmaptexture = NULL;
10351                         rsurface.deluxemaptexture = NULL;
10352                         rsurface.uselightmaptexture = false;
10353                         // scan ahead until we find a different texture
10354                         endsurface = min(i + 1024, numsurfaces);
10355                         texturenumsurfaces = 0;
10356                         texturesurfacelist[texturenumsurfaces++] = surface;
10357                         for (;j < endsurface;j++)
10358                         {
10359                                 surface = rsurface.modelsurfaces + surfacelist[j];
10360                                 if (texture != surface->texture)
10361                                         break;
10362                                 texturesurfacelist[texturenumsurfaces++] = surface;
10363                         }
10364                         if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
10365                                 continue;
10366                         // render the range of surfaces as depth
10367                         if (!setup)
10368                         {
10369                                 setup = true;
10370                                 GL_ColorMask(0,0,0,0);
10371                                 GL_Color(1,1,1,1);
10372                                 GL_DepthTest(true);
10373                                 GL_BlendFunc(GL_ONE, GL_ZERO);
10374                                 GL_DepthMask(true);
10375 //                              R_Mesh_ResetTextureState();
10376                                 R_SetupShader_DepthOrShadow(false);
10377                         }
10378                         RSurf_SetupDepthAndCulling();
10379                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
10380                         if (rsurface.batchvertex3fbuffer)
10381                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
10382                         else
10383                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
10384                         RSurf_DrawBatch();
10385                 }
10386                 if (setup)
10387                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
10388         }
10389
10390         for (i = 0;i < numsurfaces;i = j)
10391         {
10392                 j = i + 1;
10393                 surface = rsurface.modelsurfaces + surfacelist[i];
10394                 texture = surface->texture;
10395                 rsurface.texture = R_GetCurrentTexture(texture);
10396                 // scan ahead until we find a different texture
10397                 endsurface = min(i + MESHQUEUE_TRANSPARENT_BATCHSIZE, numsurfaces);
10398                 texturenumsurfaces = 0;
10399                 texturesurfacelist[texturenumsurfaces++] = surface;
10400                 if(FAKELIGHT_ENABLED)
10401                 {
10402                         rsurface.lightmaptexture = NULL;
10403                         rsurface.deluxemaptexture = NULL;
10404                         rsurface.uselightmaptexture = false;
10405                         for (;j < endsurface;j++)
10406                         {
10407                                 surface = rsurface.modelsurfaces + surfacelist[j];
10408                                 if (texture != surface->texture)
10409                                         break;
10410                                 texturesurfacelist[texturenumsurfaces++] = surface;
10411                         }
10412                 }
10413                 else
10414                 {
10415                         rsurface.lightmaptexture = surface->lightmaptexture;
10416                         rsurface.deluxemaptexture = surface->deluxemaptexture;
10417                         rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
10418                         for (;j < endsurface;j++)
10419                         {
10420                                 surface = rsurface.modelsurfaces + surfacelist[j];
10421                                 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
10422                                         break;
10423                                 texturesurfacelist[texturenumsurfaces++] = surface;
10424                         }
10425                 }
10426                 // render the range of surfaces
10427                 if (ent == r_refdef.scene.worldentity)
10428                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
10429                 else
10430                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
10431         }
10432         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
10433 }
10434
10435 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
10436 {
10437         // transparent surfaces get pushed off into the transparent queue
10438         int surfacelistindex;
10439         const msurface_t *surface;
10440         vec3_t tempcenter, center;
10441         for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
10442         {
10443                 surface = texturesurfacelist[surfacelistindex];
10444                 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
10445                 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
10446                 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
10447                 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
10448                 if (queueentity->transparent_offset) // transparent offset
10449                 {
10450                         center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
10451                         center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
10452                         center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
10453                 }
10454                 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
10455         }
10456 }
10457
10458 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10459 {
10460         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
10461                 return;
10462         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
10463                 return;
10464         RSurf_SetupDepthAndCulling();
10465         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
10466         if (rsurface.batchvertex3fbuffer)
10467                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
10468         else
10469                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
10470         RSurf_DrawBatch();
10471 }
10472
10473 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
10474 {
10475         const entity_render_t *queueentity = r_refdef.scene.worldentity;
10476         CHECKGLERROR
10477         if (depthonly)
10478                 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
10479         else if (prepass)
10480         {
10481                 if (!rsurface.texture->currentnumlayers)
10482                         return;
10483                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
10484                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
10485                 else
10486                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
10487         }
10488         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && (!r_showsurfaces.integer || r_showsurfaces.integer == 3))
10489                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
10490         else if (!rsurface.texture->currentnumlayers)
10491                 return;
10492         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
10493         {
10494                 // in the deferred case, transparent surfaces were queued during prepass
10495                 if (!r_shadow_usingdeferredprepass)
10496                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
10497         }
10498         else
10499         {
10500                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
10501                 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
10502         }
10503         CHECKGLERROR
10504 }
10505
10506 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
10507 {
10508         int i, j;
10509         texture_t *texture;
10510         R_FrameData_SetMark();
10511         // break the surface list down into batches by texture and use of lightmapping
10512         for (i = 0;i < numsurfaces;i = j)
10513         {
10514                 j = i + 1;
10515                 // texture is the base texture pointer, rsurface.texture is the
10516                 // current frame/skin the texture is directing us to use (for example
10517                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
10518                 // use skin 1 instead)
10519                 texture = surfacelist[i]->texture;
10520                 rsurface.texture = R_GetCurrentTexture(texture);
10521                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
10522                 {
10523                         // if this texture is not the kind we want, skip ahead to the next one
10524                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
10525                                 ;
10526                         continue;
10527                 }
10528                 if(FAKELIGHT_ENABLED || depthonly || prepass)
10529                 {
10530                         rsurface.lightmaptexture = NULL;
10531                         rsurface.deluxemaptexture = NULL;
10532                         rsurface.uselightmaptexture = false;
10533                         // simply scan ahead until we find a different texture or lightmap state
10534                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
10535                                 ;
10536                 }
10537                 else
10538                 {
10539                         rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
10540                         rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
10541                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
10542                         // simply scan ahead until we find a different texture or lightmap state
10543                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
10544                                 ;
10545                 }
10546                 // render the range of surfaces
10547                 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
10548         }
10549         R_FrameData_ReturnToMark();
10550 }
10551
10552 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
10553 {
10554         CHECKGLERROR
10555         if (depthonly)
10556                 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
10557         else if (prepass)
10558         {
10559                 if (!rsurface.texture->currentnumlayers)
10560                         return;
10561                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
10562                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
10563                 else
10564                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
10565         }
10566         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && (!r_showsurfaces.integer || r_showsurfaces.integer == 3))
10567                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
10568         else if (!rsurface.texture->currentnumlayers)
10569                 return;
10570         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
10571         {
10572                 // in the deferred case, transparent surfaces were queued during prepass
10573                 if (!r_shadow_usingdeferredprepass)
10574                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
10575         }
10576         else
10577         {
10578                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
10579                 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
10580         }
10581         CHECKGLERROR
10582 }
10583
10584 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
10585 {
10586         int i, j;
10587         texture_t *texture;
10588         R_FrameData_SetMark();
10589         // break the surface list down into batches by texture and use of lightmapping
10590         for (i = 0;i < numsurfaces;i = j)
10591         {
10592                 j = i + 1;
10593                 // texture is the base texture pointer, rsurface.texture is the
10594                 // current frame/skin the texture is directing us to use (for example
10595                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
10596                 // use skin 1 instead)
10597                 texture = surfacelist[i]->texture;
10598                 rsurface.texture = R_GetCurrentTexture(texture);
10599                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
10600                 {
10601                         // if this texture is not the kind we want, skip ahead to the next one
10602                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
10603                                 ;
10604                         continue;
10605                 }
10606                 if(FAKELIGHT_ENABLED || depthonly || prepass)
10607                 {
10608                         rsurface.lightmaptexture = NULL;
10609                         rsurface.deluxemaptexture = NULL;
10610                         rsurface.uselightmaptexture = false;
10611                         // simply scan ahead until we find a different texture or lightmap state
10612                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
10613                                 ;
10614                 }
10615                 else
10616                 {
10617                         rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
10618                         rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
10619                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
10620                         // simply scan ahead until we find a different texture or lightmap state
10621                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
10622                                 ;
10623                 }
10624                 // render the range of surfaces
10625                 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
10626         }
10627         R_FrameData_ReturnToMark();
10628 }
10629
10630 float locboxvertex3f[6*4*3] =
10631 {
10632         1,0,1, 1,0,0, 1,1,0, 1,1,1,
10633         0,1,1, 0,1,0, 0,0,0, 0,0,1,
10634         1,1,1, 1,1,0, 0,1,0, 0,1,1,
10635         0,0,1, 0,0,0, 1,0,0, 1,0,1,
10636         0,0,1, 1,0,1, 1,1,1, 0,1,1,
10637         1,0,0, 0,0,0, 0,1,0, 1,1,0
10638 };
10639
10640 unsigned short locboxelements[6*2*3] =
10641 {
10642          0, 1, 2, 0, 2, 3,
10643          4, 5, 6, 4, 6, 7,
10644          8, 9,10, 8,10,11,
10645         12,13,14, 12,14,15,
10646         16,17,18, 16,18,19,
10647         20,21,22, 20,22,23
10648 };
10649
10650 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
10651 {
10652         int i, j;
10653         cl_locnode_t *loc = (cl_locnode_t *)ent;
10654         vec3_t mins, size;
10655         float vertex3f[6*4*3];
10656         CHECKGLERROR
10657         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
10658         GL_DepthMask(false);
10659         GL_DepthRange(0, 1);
10660         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
10661         GL_DepthTest(true);
10662         GL_CullFace(GL_NONE);
10663         R_EntityMatrix(&identitymatrix);
10664
10665 //      R_Mesh_ResetTextureState();
10666
10667         i = surfacelist[0];
10668         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
10669                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
10670                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
10671                         surfacelist[0] < 0 ? 0.5f : 0.125f);
10672
10673         if (VectorCompare(loc->mins, loc->maxs))
10674         {
10675                 VectorSet(size, 2, 2, 2);
10676                 VectorMA(loc->mins, -0.5f, size, mins);
10677         }
10678         else
10679         {
10680                 VectorCopy(loc->mins, mins);
10681                 VectorSubtract(loc->maxs, loc->mins, size);
10682         }
10683
10684         for (i = 0;i < 6*4*3;)
10685                 for (j = 0;j < 3;j++, i++)
10686                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
10687
10688         R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
10689         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
10690         R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
10691 }
10692
10693 void R_DrawLocs(void)
10694 {
10695         int index;
10696         cl_locnode_t *loc, *nearestloc;
10697         vec3_t center;
10698         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
10699         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
10700         {
10701                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
10702                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
10703         }
10704 }
10705
10706 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
10707 {
10708         if (decalsystem->decals)
10709                 Mem_Free(decalsystem->decals);
10710         memset(decalsystem, 0, sizeof(*decalsystem));
10711 }
10712
10713 static void R_DecalSystem_SpawnTriangle(decalsystem_t *decalsystem, const float *v0, const float *v1, const float *v2, const float *t0, const float *t1, const float *t2, const float *c0, const float *c1, const float *c2, int triangleindex, int surfaceindex, int decalsequence)
10714 {
10715         tridecal_t *decal;
10716         tridecal_t *decals;
10717         int i;
10718
10719         // expand or initialize the system
10720         if (decalsystem->maxdecals <= decalsystem->numdecals)
10721         {
10722                 decalsystem_t old = *decalsystem;
10723                 qboolean useshortelements;
10724                 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
10725                 useshortelements = decalsystem->maxdecals * 3 <= 65536;
10726                 decalsystem->decals = (tridecal_t *)Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
10727                 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
10728                 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
10729                 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
10730                 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
10731                 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
10732                 if (decalsystem->numdecals)
10733                         memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
10734                 if (old.decals)
10735                         Mem_Free(old.decals);
10736                 for (i = 0;i < decalsystem->maxdecals*3;i++)
10737                         decalsystem->element3i[i] = i;
10738                 if (useshortelements)
10739                         for (i = 0;i < decalsystem->maxdecals*3;i++)
10740                                 decalsystem->element3s[i] = i;
10741         }
10742
10743         // grab a decal and search for another free slot for the next one
10744         decals = decalsystem->decals;
10745         decal = decalsystem->decals + (i = decalsystem->freedecal++);
10746         for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4f[0][3];i++)
10747                 ;
10748         decalsystem->freedecal = i;
10749         if (decalsystem->numdecals <= i)
10750                 decalsystem->numdecals = i + 1;
10751
10752         // initialize the decal
10753         decal->lived = 0;
10754         decal->triangleindex = triangleindex;
10755         decal->surfaceindex = surfaceindex;
10756         decal->decalsequence = decalsequence;
10757         decal->color4f[0][0] = c0[0];
10758         decal->color4f[0][1] = c0[1];
10759         decal->color4f[0][2] = c0[2];
10760         decal->color4f[0][3] = 1;
10761         decal->color4f[1][0] = c1[0];
10762         decal->color4f[1][1] = c1[1];
10763         decal->color4f[1][2] = c1[2];
10764         decal->color4f[1][3] = 1;
10765         decal->color4f[2][0] = c2[0];
10766         decal->color4f[2][1] = c2[1];
10767         decal->color4f[2][2] = c2[2];
10768         decal->color4f[2][3] = 1;
10769         decal->vertex3f[0][0] = v0[0];
10770         decal->vertex3f[0][1] = v0[1];
10771         decal->vertex3f[0][2] = v0[2];
10772         decal->vertex3f[1][0] = v1[0];
10773         decal->vertex3f[1][1] = v1[1];
10774         decal->vertex3f[1][2] = v1[2];
10775         decal->vertex3f[2][0] = v2[0];
10776         decal->vertex3f[2][1] = v2[1];
10777         decal->vertex3f[2][2] = v2[2];
10778         decal->texcoord2f[0][0] = t0[0];
10779         decal->texcoord2f[0][1] = t0[1];
10780         decal->texcoord2f[1][0] = t1[0];
10781         decal->texcoord2f[1][1] = t1[1];
10782         decal->texcoord2f[2][0] = t2[0];
10783         decal->texcoord2f[2][1] = t2[1];
10784         TriangleNormal(v0, v1, v2, decal->plane);
10785         VectorNormalize(decal->plane);
10786         decal->plane[3] = DotProduct(v0, decal->plane);
10787 }
10788
10789 extern cvar_t cl_decals_bias;
10790 extern cvar_t cl_decals_models;
10791 extern cvar_t cl_decals_newsystem_intensitymultiplier;
10792 // baseparms, parms, temps
10793 static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
10794 {
10795         int cornerindex;
10796         int index;
10797         float v[9][3];
10798         const float *vertex3f;
10799         const float *normal3f;
10800         int numpoints;
10801         float points[2][9][3];
10802         float temp[3];
10803         float tc[9][2];
10804         float f;
10805         float c[9][4];
10806         const int *e;
10807
10808         e = rsurface.modelelement3i + 3*triangleindex;
10809
10810         vertex3f = rsurface.modelvertex3f;
10811         normal3f = rsurface.modelnormal3f;
10812
10813         if (normal3f)
10814         {
10815                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
10816                 {
10817                         index = 3*e[cornerindex];
10818                         VectorMA(vertex3f + index, cl_decals_bias.value, normal3f + index, v[cornerindex]);
10819                 }
10820         }
10821         else
10822         {
10823                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
10824                 {
10825                         index = 3*e[cornerindex];
10826                         VectorCopy(vertex3f + index, v[cornerindex]);
10827                 }
10828         }
10829
10830         // cull backfaces
10831         //TriangleNormal(v[0], v[1], v[2], normal);
10832         //if (DotProduct(normal, localnormal) < 0.0f)
10833         //      continue;
10834         // clip by each of the box planes formed from the projection matrix
10835         // if anything survives, we emit the decal
10836         numpoints = PolygonF_Clip(3        , v[0]        , planes[0][0], planes[0][1], planes[0][2], planes[0][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
10837         if (numpoints < 3)
10838                 return;
10839         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[1][0], planes[1][1], planes[1][2], planes[1][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
10840         if (numpoints < 3)
10841                 return;
10842         numpoints = PolygonF_Clip(numpoints, points[0][0], planes[2][0], planes[2][1], planes[2][2], planes[2][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
10843         if (numpoints < 3)
10844                 return;
10845         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[3][0], planes[3][1], planes[3][2], planes[3][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
10846         if (numpoints < 3)
10847                 return;
10848         numpoints = PolygonF_Clip(numpoints, points[0][0], planes[4][0], planes[4][1], planes[4][2], planes[4][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
10849         if (numpoints < 3)
10850                 return;
10851         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[5][0], planes[5][1], planes[5][2], planes[5][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), v[0]);
10852         if (numpoints < 3)
10853                 return;
10854         // some part of the triangle survived, so we have to accept it...
10855         if (dynamic)
10856         {
10857                 // dynamic always uses the original triangle
10858                 numpoints = 3;
10859                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
10860                 {
10861                         index = 3*e[cornerindex];
10862                         VectorCopy(vertex3f + index, v[cornerindex]);
10863                 }
10864         }
10865         for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
10866         {
10867                 // convert vertex positions to texcoords
10868                 Matrix4x4_Transform(projection, v[cornerindex], temp);
10869                 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
10870                 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
10871                 // calculate distance fade from the projection origin
10872                 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
10873                 f = bound(0.0f, f, 1.0f);
10874                 c[cornerindex][0] = r * f;
10875                 c[cornerindex][1] = g * f;
10876                 c[cornerindex][2] = b * f;
10877                 c[cornerindex][3] = 1.0f;
10878                 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
10879         }
10880         if (dynamic)
10881                 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex, surfaceindex, decalsequence);
10882         else
10883                 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
10884                         R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[cornerindex+1], v[cornerindex+2], tc[0], tc[cornerindex+1], tc[cornerindex+2], c[0], c[cornerindex+1], c[cornerindex+2], -1, surfaceindex, decalsequence);
10885 }
10886 static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
10887 {
10888         matrix4x4_t projection;
10889         decalsystem_t *decalsystem;
10890         qboolean dynamic;
10891         dp_model_t *model;
10892         const msurface_t *surface;
10893         const msurface_t *surfaces;
10894         const int *surfacelist;
10895         const texture_t *texture;
10896         int numtriangles;
10897         int numsurfacelist;
10898         int surfacelistindex;
10899         int surfaceindex;
10900         int triangleindex;
10901         float localorigin[3];
10902         float localnormal[3];
10903         float localmins[3];
10904         float localmaxs[3];
10905         float localsize;
10906         //float normal[3];
10907         float planes[6][4];
10908         float angles[3];
10909         bih_t *bih;
10910         int bih_triangles_count;
10911         int bih_triangles[256];
10912         int bih_surfaces[256];
10913
10914         decalsystem = &ent->decalsystem;
10915         model = ent->model;
10916         if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
10917         {
10918                 R_DecalSystem_Reset(&ent->decalsystem);
10919                 return;
10920         }
10921
10922         if (!model->brush.data_leafs && !cl_decals_models.integer)
10923         {
10924                 if (decalsystem->model)
10925                         R_DecalSystem_Reset(decalsystem);
10926                 return;
10927         }
10928
10929         if (decalsystem->model != model)
10930                 R_DecalSystem_Reset(decalsystem);
10931         decalsystem->model = model;
10932
10933         RSurf_ActiveModelEntity(ent, true, false, false);
10934
10935         Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
10936         Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
10937         VectorNormalize(localnormal);
10938         localsize = worldsize*rsurface.inversematrixscale;
10939         localmins[0] = localorigin[0] - localsize;
10940         localmins[1] = localorigin[1] - localsize;
10941         localmins[2] = localorigin[2] - localsize;
10942         localmaxs[0] = localorigin[0] + localsize;
10943         localmaxs[1] = localorigin[1] + localsize;
10944         localmaxs[2] = localorigin[2] + localsize;
10945
10946         //VectorCopy(localnormal, planes[4]);
10947         //VectorVectors(planes[4], planes[2], planes[0]);
10948         AnglesFromVectors(angles, localnormal, NULL, false);
10949         AngleVectors(angles, planes[0], planes[2], planes[4]);
10950         VectorNegate(planes[0], planes[1]);
10951         VectorNegate(planes[2], planes[3]);
10952         VectorNegate(planes[4], planes[5]);
10953         planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
10954         planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
10955         planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
10956         planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
10957         planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
10958         planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
10959
10960 #if 1
10961 // works
10962 {
10963         matrix4x4_t forwardprojection;
10964         Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
10965         Matrix4x4_Invert_Simple(&projection, &forwardprojection);
10966 }
10967 #else
10968 // broken
10969 {
10970         float projectionvector[4][3];
10971         VectorScale(planes[0], ilocalsize, projectionvector[0]);
10972         VectorScale(planes[2], ilocalsize, projectionvector[1]);
10973         VectorScale(planes[4], ilocalsize, projectionvector[2]);
10974         projectionvector[0][0] = planes[0][0] * ilocalsize;
10975         projectionvector[0][1] = planes[1][0] * ilocalsize;
10976         projectionvector[0][2] = planes[2][0] * ilocalsize;
10977         projectionvector[1][0] = planes[0][1] * ilocalsize;
10978         projectionvector[1][1] = planes[1][1] * ilocalsize;
10979         projectionvector[1][2] = planes[2][1] * ilocalsize;
10980         projectionvector[2][0] = planes[0][2] * ilocalsize;
10981         projectionvector[2][1] = planes[1][2] * ilocalsize;
10982         projectionvector[2][2] = planes[2][2] * ilocalsize;
10983         projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
10984         projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
10985         projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
10986         Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
10987 }
10988 #endif
10989
10990         dynamic = model->surfmesh.isanimated;
10991         numsurfacelist = model->nummodelsurfaces;
10992         surfacelist = model->sortedmodelsurfaces;
10993         surfaces = model->data_surfaces;
10994
10995         bih = NULL;
10996         bih_triangles_count = -1;
10997         if(!dynamic)
10998         {
10999                 if(model->render_bih.numleafs)
11000                         bih = &model->render_bih;
11001                 else if(model->collision_bih.numleafs)
11002                         bih = &model->collision_bih;
11003         }
11004         if(bih)
11005                 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
11006         if(bih_triangles_count == 0)
11007                 return;
11008         if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
11009                 return;
11010         if(bih_triangles_count > 0)
11011         {
11012                 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
11013                 {
11014                         surfaceindex = bih_surfaces[triangleindex];
11015                         surface = surfaces + surfaceindex;
11016                         texture = surface->texture;
11017                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
11018                                 continue;
11019                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
11020                                 continue;
11021                         R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
11022                 }
11023         }
11024         else
11025         {
11026                 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
11027                 {
11028                         surfaceindex = surfacelist[surfacelistindex];
11029                         surface = surfaces + surfaceindex;
11030                         // check cull box first because it rejects more than any other check
11031                         if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
11032                                 continue;
11033                         // skip transparent surfaces
11034                         texture = surface->texture;
11035                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
11036                                 continue;
11037                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
11038                                 continue;
11039                         numtriangles = surface->num_triangles;
11040                         for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
11041                                 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
11042                 }
11043         }
11044 }
11045
11046 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
11047 static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
11048 {
11049         int renderentityindex;
11050         float worldmins[3];
11051         float worldmaxs[3];
11052         entity_render_t *ent;
11053
11054         if (!cl_decals_newsystem.integer)
11055                 return;
11056
11057         worldmins[0] = worldorigin[0] - worldsize;
11058         worldmins[1] = worldorigin[1] - worldsize;
11059         worldmins[2] = worldorigin[2] - worldsize;
11060         worldmaxs[0] = worldorigin[0] + worldsize;
11061         worldmaxs[1] = worldorigin[1] + worldsize;
11062         worldmaxs[2] = worldorigin[2] + worldsize;
11063
11064         R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
11065
11066         for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
11067         {
11068                 ent = r_refdef.scene.entities[renderentityindex];
11069                 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
11070                         continue;
11071
11072                 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
11073         }
11074 }
11075
11076 typedef struct r_decalsystem_splatqueue_s
11077 {
11078         vec3_t worldorigin;
11079         vec3_t worldnormal;
11080         float color[4];
11081         float tcrange[4];
11082         float worldsize;
11083         int decalsequence;
11084 }
11085 r_decalsystem_splatqueue_t;
11086
11087 int r_decalsystem_numqueued = 0;
11088 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
11089
11090 void R_DecalSystem_SplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize)
11091 {
11092         r_decalsystem_splatqueue_t *queue;
11093
11094         if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
11095                 return;
11096
11097         queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
11098         VectorCopy(worldorigin, queue->worldorigin);
11099         VectorCopy(worldnormal, queue->worldnormal);
11100         Vector4Set(queue->color, r, g, b, a);
11101         Vector4Set(queue->tcrange, s1, t1, s2, t2);
11102         queue->worldsize = worldsize;
11103         queue->decalsequence = cl.decalsequence++;
11104 }
11105
11106 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
11107 {
11108         int i;
11109         r_decalsystem_splatqueue_t *queue;
11110
11111         for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
11112                 R_DecalSystem_ApplySplatEntities(queue->worldorigin, queue->worldnormal, queue->color[0], queue->color[1], queue->color[2], queue->color[3], queue->tcrange[0], queue->tcrange[1], queue->tcrange[2], queue->tcrange[3], queue->worldsize, queue->decalsequence);
11113         r_decalsystem_numqueued = 0;
11114 }
11115
11116 extern cvar_t cl_decals_max;
11117 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
11118 {
11119         int i;
11120         decalsystem_t *decalsystem = &ent->decalsystem;
11121         int numdecals;
11122         int killsequence;
11123         tridecal_t *decal;
11124         float frametime;
11125         float lifetime;
11126
11127         if (!decalsystem->numdecals)
11128                 return;
11129
11130         if (r_showsurfaces.integer)
11131                 return;
11132
11133         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
11134         {
11135                 R_DecalSystem_Reset(decalsystem);
11136                 return;
11137         }
11138
11139         killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
11140         lifetime = cl_decals_time.value + cl_decals_fadetime.value;
11141
11142         if (decalsystem->lastupdatetime)
11143                 frametime = (r_refdef.scene.time - decalsystem->lastupdatetime);
11144         else
11145                 frametime = 0;
11146         decalsystem->lastupdatetime = r_refdef.scene.time;
11147         decal = decalsystem->decals;
11148         numdecals = decalsystem->numdecals;
11149
11150         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
11151         {
11152                 if (decal->color4f[0][3])
11153                 {
11154                         decal->lived += frametime;
11155                         if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
11156                         {
11157                                 memset(decal, 0, sizeof(*decal));
11158                                 if (decalsystem->freedecal > i)
11159                                         decalsystem->freedecal = i;
11160                         }
11161                 }
11162         }
11163         decal = decalsystem->decals;
11164         while (numdecals > 0 && !decal[numdecals-1].color4f[0][3])
11165                 numdecals--;
11166
11167         // collapse the array by shuffling the tail decals into the gaps
11168         for (;;)
11169         {
11170                 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4f[0][3])
11171                         decalsystem->freedecal++;
11172                 if (decalsystem->freedecal == numdecals)
11173                         break;
11174                 decal[decalsystem->freedecal] = decal[--numdecals];
11175         }
11176
11177         decalsystem->numdecals = numdecals;
11178
11179         if (numdecals <= 0)
11180         {
11181                 // if there are no decals left, reset decalsystem
11182                 R_DecalSystem_Reset(decalsystem);
11183         }
11184 }
11185
11186 extern skinframe_t *decalskinframe;
11187 static void R_DrawModelDecals_Entity(entity_render_t *ent)
11188 {
11189         int i;
11190         decalsystem_t *decalsystem = &ent->decalsystem;
11191         int numdecals;
11192         tridecal_t *decal;
11193         float faderate;
11194         float alpha;
11195         float *v3f;
11196         float *c4f;
11197         float *t2f;
11198         const int *e;
11199         const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
11200         int numtris = 0;
11201
11202         numdecals = decalsystem->numdecals;
11203         if (!numdecals)
11204                 return;
11205
11206         if (r_showsurfaces.integer)
11207                 return;
11208
11209         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
11210         {
11211                 R_DecalSystem_Reset(decalsystem);
11212                 return;
11213         }
11214
11215         // if the model is static it doesn't matter what value we give for
11216         // wantnormals and wanttangents, so this logic uses only rules applicable
11217         // to a model, knowing that they are meaningless otherwise
11218         if (ent == r_refdef.scene.worldentity)
11219                 RSurf_ActiveWorldEntity();
11220         else
11221                 RSurf_ActiveModelEntity(ent, false, false, false);
11222
11223         decalsystem->lastupdatetime = r_refdef.scene.time;
11224         decal = decalsystem->decals;
11225
11226         faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
11227
11228         // update vertex positions for animated models
11229         v3f = decalsystem->vertex3f;
11230         c4f = decalsystem->color4f;
11231         t2f = decalsystem->texcoord2f;
11232         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
11233         {
11234                 if (!decal->color4f[0][3])
11235                         continue;
11236
11237                 if (surfacevisible && !surfacevisible[decal->surfaceindex])
11238                         continue;
11239
11240                 // skip backfaces
11241                 if (decal->triangleindex < 0 && DotProduct(r_refdef.view.origin, decal->plane) < decal->plane[3])
11242                         continue;
11243
11244                 // update color values for fading decals
11245                 if (decal->lived >= cl_decals_time.value)
11246                         alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
11247                 else
11248                         alpha = 1.0f;
11249
11250                 c4f[ 0] = decal->color4f[0][0] * alpha;
11251                 c4f[ 1] = decal->color4f[0][1] * alpha;
11252                 c4f[ 2] = decal->color4f[0][2] * alpha;
11253                 c4f[ 3] = 1;
11254                 c4f[ 4] = decal->color4f[1][0] * alpha;
11255                 c4f[ 5] = decal->color4f[1][1] * alpha;
11256                 c4f[ 6] = decal->color4f[1][2] * alpha;
11257                 c4f[ 7] = 1;
11258                 c4f[ 8] = decal->color4f[2][0] * alpha;
11259                 c4f[ 9] = decal->color4f[2][1] * alpha;
11260                 c4f[10] = decal->color4f[2][2] * alpha;
11261                 c4f[11] = 1;
11262
11263                 t2f[0] = decal->texcoord2f[0][0];
11264                 t2f[1] = decal->texcoord2f[0][1];
11265                 t2f[2] = decal->texcoord2f[1][0];
11266                 t2f[3] = decal->texcoord2f[1][1];
11267                 t2f[4] = decal->texcoord2f[2][0];
11268                 t2f[5] = decal->texcoord2f[2][1];
11269
11270                 // update vertex positions for animated models
11271                 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
11272                 {
11273                         e = rsurface.modelelement3i + 3*decal->triangleindex;
11274                         VectorCopy(rsurface.modelvertex3f + 3*e[0], v3f);
11275                         VectorCopy(rsurface.modelvertex3f + 3*e[1], v3f + 3);
11276                         VectorCopy(rsurface.modelvertex3f + 3*e[2], v3f + 6);
11277                 }
11278                 else
11279                 {
11280                         VectorCopy(decal->vertex3f[0], v3f);
11281                         VectorCopy(decal->vertex3f[1], v3f + 3);
11282                         VectorCopy(decal->vertex3f[2], v3f + 6);
11283                 }
11284
11285                 if (r_refdef.fogenabled)
11286                 {
11287                         alpha = RSurf_FogVertex(v3f);
11288                         VectorScale(c4f, alpha, c4f);
11289                         alpha = RSurf_FogVertex(v3f + 3);
11290                         VectorScale(c4f + 4, alpha, c4f + 4);
11291                         alpha = RSurf_FogVertex(v3f + 6);
11292                         VectorScale(c4f + 8, alpha, c4f + 8);
11293                 }
11294
11295                 v3f += 9;
11296                 c4f += 12;
11297                 t2f += 6;
11298                 numtris++;
11299         }
11300
11301         if (numtris > 0)
11302         {
11303                 r_refdef.stats.drawndecals += numtris;
11304
11305                 // now render the decals all at once
11306                 // (this assumes they all use one particle font texture!)
11307                 RSurf_ActiveCustomEntity(&rsurface.matrix, &rsurface.inversematrix, rsurface.ent_flags, ent->shadertime, 1, 1, 1, 1, numdecals*3, decalsystem->vertex3f, decalsystem->texcoord2f, NULL, NULL, NULL, decalsystem->color4f, numtris, decalsystem->element3i, decalsystem->element3s, false, false);
11308 //              R_Mesh_ResetTextureState();
11309                 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
11310                 GL_DepthMask(false);
11311                 GL_DepthRange(0, 1);
11312                 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
11313                 GL_DepthTest(true);
11314                 GL_CullFace(GL_NONE);
11315                 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
11316                 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1, false, false);
11317                 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
11318         }
11319 }
11320
11321 static void R_DrawModelDecals(void)
11322 {
11323         int i, numdecals;
11324
11325         // fade faster when there are too many decals
11326         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
11327         for (i = 0;i < r_refdef.scene.numentities;i++)
11328                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
11329
11330         R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
11331         for (i = 0;i < r_refdef.scene.numentities;i++)
11332                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
11333                         R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
11334
11335         R_DecalSystem_ApplySplatEntitiesQueue();
11336
11337         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
11338         for (i = 0;i < r_refdef.scene.numentities;i++)
11339                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
11340
11341         r_refdef.stats.totaldecals += numdecals;
11342
11343         if (r_showsurfaces.integer)
11344                 return;
11345
11346         R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
11347
11348         for (i = 0;i < r_refdef.scene.numentities;i++)
11349         {
11350                 if (!r_refdef.viewcache.entityvisible[i])
11351                         continue;
11352                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
11353                         R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
11354         }
11355 }
11356
11357 extern cvar_t mod_collision_bih;
11358 void R_DrawDebugModel(void)
11359 {
11360         entity_render_t *ent = rsurface.entity;
11361         int i, j, k, l, flagsmask;
11362         const msurface_t *surface;
11363         dp_model_t *model = ent->model;
11364         vec3_t v;
11365
11366         if (!sv.active  && !cls.demoplayback && ent != r_refdef.scene.worldentity)
11367                 return;
11368
11369         if (r_showoverdraw.value > 0)
11370         {
11371                 float c = r_refdef.view.colorscale * r_showoverdraw.value * 0.125f;
11372                 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
11373                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
11374                 GL_DepthTest(false);
11375                 GL_DepthMask(false);
11376                 GL_DepthRange(0, 1);
11377                 GL_BlendFunc(GL_ONE, GL_ONE);
11378                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
11379                 {
11380                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
11381                                 continue;
11382                         rsurface.texture = R_GetCurrentTexture(surface->texture);
11383                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
11384                         {
11385                                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, 1, &surface);
11386                                 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
11387                                 if (!rsurface.texture->currentlayers->depthmask)
11388                                         GL_Color(c, 0, 0, 1.0f);
11389                                 else if (ent == r_refdef.scene.worldentity)
11390                                         GL_Color(c, c, c, 1.0f);
11391                                 else
11392                                         GL_Color(0, c, 0, 1.0f);
11393                                 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
11394                                 RSurf_DrawBatch();
11395                         }
11396                 }
11397                 rsurface.texture = NULL;
11398         }
11399
11400         flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
11401
11402 //      R_Mesh_ResetTextureState();
11403         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
11404         GL_DepthRange(0, 1);
11405         GL_DepthTest(!r_showdisabledepthtest.integer);
11406         GL_DepthMask(false);
11407         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11408
11409         if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
11410         {
11411                 int triangleindex;
11412                 int bihleafindex;
11413                 qboolean cullbox = ent == r_refdef.scene.worldentity;
11414                 const q3mbrush_t *brush;
11415                 const bih_t *bih = &model->collision_bih;
11416                 const bih_leaf_t *bihleaf;
11417                 float vertex3f[3][3];
11418                 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
11419                 cullbox = false;
11420                 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
11421                 {
11422                         if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
11423                                 continue;
11424                         switch (bihleaf->type)
11425                         {
11426                         case BIH_BRUSH:
11427                                 brush = model->brush.data_brushes + bihleaf->itemindex;
11428                                 if (brush->colbrushf && brush->colbrushf->numtriangles)
11429                                 {
11430                                         GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
11431                                         R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
11432                                         R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
11433                                 }
11434                                 break;
11435                         case BIH_COLLISIONTRIANGLE:
11436                                 triangleindex = bihleaf->itemindex;
11437                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
11438                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
11439                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
11440                                 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
11441                                 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
11442                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
11443                                 break;
11444                         case BIH_RENDERTRIANGLE:
11445                                 triangleindex = bihleaf->itemindex;
11446                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
11447                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
11448                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
11449                                 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
11450                                 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
11451                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
11452                                 break;
11453                         }
11454                 }
11455         }
11456
11457         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
11458
11459 #ifndef USE_GLES2
11460         if (r_showtris.integer && qglPolygonMode)
11461         {
11462                 if (r_showdisabledepthtest.integer)
11463                 {
11464                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11465                         GL_DepthMask(false);
11466                 }
11467                 else
11468                 {
11469                         GL_BlendFunc(GL_ONE, GL_ZERO);
11470                         GL_DepthMask(true);
11471                 }
11472                 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);CHECKGLERROR
11473                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
11474                 {
11475                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
11476                                 continue;
11477                         rsurface.texture = R_GetCurrentTexture(surface->texture);
11478                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
11479                         {
11480                                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
11481                                 if (!rsurface.texture->currentlayers->depthmask)
11482                                         GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
11483                                 else if (ent == r_refdef.scene.worldentity)
11484                                         GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
11485                                 else
11486                                         GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
11487                                 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
11488                                 RSurf_DrawBatch();
11489                         }
11490                 }
11491                 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);CHECKGLERROR
11492                 rsurface.texture = NULL;
11493         }
11494
11495         if (r_shownormals.value != 0 && qglBegin)
11496         {
11497                 if (r_showdisabledepthtest.integer)
11498                 {
11499                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11500                         GL_DepthMask(false);
11501                 }
11502                 else
11503                 {
11504                         GL_BlendFunc(GL_ONE, GL_ZERO);
11505                         GL_DepthMask(true);
11506                 }
11507                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
11508                 {
11509                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
11510                                 continue;
11511                         rsurface.texture = R_GetCurrentTexture(surface->texture);
11512                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
11513                         {
11514                                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
11515                                 qglBegin(GL_LINES);
11516                                 if (r_shownormals.value < 0 && rsurface.batchnormal3f)
11517                                 {
11518                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
11519                                         {
11520                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
11521                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
11522                                                 qglVertex3f(v[0], v[1], v[2]);
11523                                                 VectorMA(v, -r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
11524                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
11525                                                 qglVertex3f(v[0], v[1], v[2]);
11526                                         }
11527                                 }
11528                                 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
11529                                 {
11530                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
11531                                         {
11532                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
11533                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
11534                                                 qglVertex3f(v[0], v[1], v[2]);
11535                                                 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
11536                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
11537                                                 qglVertex3f(v[0], v[1], v[2]);
11538                                         }
11539                                 }
11540                                 if (r_shownormals.value > 0 && rsurface.batchtvector3f)
11541                                 {
11542                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
11543                                         {
11544                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
11545                                                 GL_Color(0, r_refdef.view.colorscale, 0, 1);
11546                                                 qglVertex3f(v[0], v[1], v[2]);
11547                                                 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
11548                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
11549                                                 qglVertex3f(v[0], v[1], v[2]);
11550                                         }
11551                                 }
11552                                 if (r_shownormals.value > 0 && rsurface.batchnormal3f)
11553                                 {
11554                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
11555                                         {
11556                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
11557                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
11558                                                 qglVertex3f(v[0], v[1], v[2]);
11559                                                 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
11560                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
11561                                                 qglVertex3f(v[0], v[1], v[2]);
11562                                         }
11563                                 }
11564                                 qglEnd();
11565                                 CHECKGLERROR
11566                         }
11567                 }
11568                 rsurface.texture = NULL;
11569         }
11570 #endif
11571 }
11572
11573 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
11574 int r_maxsurfacelist = 0;
11575 const msurface_t **r_surfacelist = NULL;
11576 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
11577 {
11578         int i, j, endj, flagsmask;
11579         dp_model_t *model = r_refdef.scene.worldmodel;
11580         msurface_t *surfaces;
11581         unsigned char *update;
11582         int numsurfacelist = 0;
11583         if (model == NULL)
11584                 return;
11585
11586         if (r_maxsurfacelist < model->num_surfaces)
11587         {
11588                 r_maxsurfacelist = model->num_surfaces;
11589                 if (r_surfacelist)
11590                         Mem_Free((msurface_t**)r_surfacelist);
11591                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
11592         }
11593
11594         RSurf_ActiveWorldEntity();
11595
11596         surfaces = model->data_surfaces;
11597         update = model->brushq1.lightmapupdateflags;
11598
11599         // update light styles on this submodel
11600         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
11601         {
11602                 model_brush_lightstyleinfo_t *style;
11603                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
11604                 {
11605                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
11606                         {
11607                                 int *list = style->surfacelist;
11608                                 style->value = r_refdef.scene.lightstylevalue[style->style];
11609                                 for (j = 0;j < style->numsurfaces;j++)
11610                                         update[list[j]] = true;
11611                         }
11612                 }
11613         }
11614
11615         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
11616
11617         if (debug)
11618         {
11619                 R_DrawDebugModel();
11620                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11621                 return;
11622         }
11623
11624         rsurface.lightmaptexture = NULL;
11625         rsurface.deluxemaptexture = NULL;
11626         rsurface.uselightmaptexture = false;
11627         rsurface.texture = NULL;
11628         rsurface.rtlight = NULL;
11629         numsurfacelist = 0;
11630         // add visible surfaces to draw list
11631         for (i = 0;i < model->nummodelsurfaces;i++)
11632         {
11633                 j = model->sortedmodelsurfaces[i];
11634                 if (r_refdef.viewcache.world_surfacevisible[j])
11635                         r_surfacelist[numsurfacelist++] = surfaces + j;
11636         }
11637         // update lightmaps if needed
11638         if (model->brushq1.firstrender)
11639         {
11640                 model->brushq1.firstrender = false;
11641                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
11642                         if (update[j])
11643                                 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
11644         }
11645         else if (update)
11646         {
11647                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
11648                         if (r_refdef.viewcache.world_surfacevisible[j])
11649                                 if (update[j])
11650                                         R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
11651         }
11652         // don't do anything if there were no surfaces
11653         if (!numsurfacelist)
11654         {
11655                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11656                 return;
11657         }
11658         R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
11659
11660         // add to stats if desired
11661         if (r_speeds.integer && !skysurfaces && !depthonly)
11662         {
11663                 r_refdef.stats.world_surfaces += numsurfacelist;
11664                 for (j = 0;j < numsurfacelist;j++)
11665                         r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
11666         }
11667
11668         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11669 }
11670
11671 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
11672 {
11673         int i, j, endj, flagsmask;
11674         dp_model_t *model = ent->model;
11675         msurface_t *surfaces;
11676         unsigned char *update;
11677         int numsurfacelist = 0;
11678         if (model == NULL)
11679                 return;
11680
11681         if (r_maxsurfacelist < model->num_surfaces)
11682         {
11683                 r_maxsurfacelist = model->num_surfaces;
11684                 if (r_surfacelist)
11685                         Mem_Free((msurface_t **)r_surfacelist);
11686                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
11687         }
11688
11689         // if the model is static it doesn't matter what value we give for
11690         // wantnormals and wanttangents, so this logic uses only rules applicable
11691         // to a model, knowing that they are meaningless otherwise
11692         if (ent == r_refdef.scene.worldentity)
11693                 RSurf_ActiveWorldEntity();
11694         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
11695                 RSurf_ActiveModelEntity(ent, false, false, false);
11696         else if (prepass)
11697                 RSurf_ActiveModelEntity(ent, true, true, true);
11698         else if (depthonly)
11699         {
11700                 switch (vid.renderpath)
11701                 {
11702                 case RENDERPATH_GL20:
11703                 case RENDERPATH_D3D9:
11704                 case RENDERPATH_D3D10:
11705                 case RENDERPATH_D3D11:
11706                 case RENDERPATH_SOFT:
11707                 case RENDERPATH_GLES2:
11708                         RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
11709                         break;
11710                 case RENDERPATH_GL11:
11711                 case RENDERPATH_GL13:
11712                 case RENDERPATH_GLES1:
11713                         RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
11714                         break;
11715                 }
11716         }
11717         else
11718         {
11719                 switch (vid.renderpath)
11720                 {
11721                 case RENDERPATH_GL20:
11722                 case RENDERPATH_D3D9:
11723                 case RENDERPATH_D3D10:
11724                 case RENDERPATH_D3D11:
11725                 case RENDERPATH_SOFT:
11726                 case RENDERPATH_GLES2:
11727                         RSurf_ActiveModelEntity(ent, true, true, false);
11728                         break;
11729                 case RENDERPATH_GL11:
11730                 case RENDERPATH_GL13:
11731                 case RENDERPATH_GLES1:
11732                         RSurf_ActiveModelEntity(ent, true, false, false);
11733                         break;
11734                 }
11735         }
11736
11737         surfaces = model->data_surfaces;
11738         update = model->brushq1.lightmapupdateflags;
11739
11740         // update light styles
11741         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
11742         {
11743                 model_brush_lightstyleinfo_t *style;
11744                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
11745                 {
11746                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
11747                         {
11748                                 int *list = style->surfacelist;
11749                                 style->value = r_refdef.scene.lightstylevalue[style->style];
11750                                 for (j = 0;j < style->numsurfaces;j++)
11751                                         update[list[j]] = true;
11752                         }
11753                 }
11754         }
11755
11756         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
11757
11758         if (debug)
11759         {
11760                 R_DrawDebugModel();
11761                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11762                 return;
11763         }
11764
11765         rsurface.lightmaptexture = NULL;
11766         rsurface.deluxemaptexture = NULL;
11767         rsurface.uselightmaptexture = false;
11768         rsurface.texture = NULL;
11769         rsurface.rtlight = NULL;
11770         numsurfacelist = 0;
11771         // add visible surfaces to draw list
11772         for (i = 0;i < model->nummodelsurfaces;i++)
11773                 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
11774         // don't do anything if there were no surfaces
11775         if (!numsurfacelist)
11776         {
11777                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11778                 return;
11779         }
11780         // update lightmaps if needed
11781         if (update)
11782         {
11783                 int updated = 0;
11784                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
11785                 {
11786                         if (update[j])
11787                         {
11788                                 updated++;
11789                                 R_BuildLightMap(ent, surfaces + j);
11790                         }
11791                 }
11792         }
11793         if (update)
11794                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
11795                         if (update[j])
11796                                 R_BuildLightMap(ent, surfaces + j);
11797         R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
11798
11799         // add to stats if desired
11800         if (r_speeds.integer && !skysurfaces && !depthonly)
11801         {
11802                 r_refdef.stats.entities_surfaces += numsurfacelist;
11803                 for (j = 0;j < numsurfacelist;j++)
11804                         r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
11805         }
11806
11807         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11808 }
11809
11810 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
11811 {
11812         static texture_t texture;
11813         static msurface_t surface;
11814         const msurface_t *surfacelist = &surface;
11815
11816         // fake enough texture and surface state to render this geometry
11817
11818         texture.update_lastrenderframe = -1; // regenerate this texture
11819         texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
11820         texture.currentskinframe = skinframe;
11821         texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
11822         texture.offsetmapping = OFFSETMAPPING_OFF;
11823         texture.offsetscale = 1;
11824         texture.specularscalemod = 1;
11825         texture.specularpowermod = 1;
11826
11827         surface.texture = &texture;
11828         surface.num_triangles = numtriangles;
11829         surface.num_firsttriangle = firsttriangle;
11830         surface.num_vertices = numvertices;
11831         surface.num_firstvertex = firstvertex;
11832
11833         // now render it
11834         rsurface.texture = R_GetCurrentTexture(surface.texture);
11835         rsurface.lightmaptexture = NULL;
11836         rsurface.deluxemaptexture = NULL;
11837         rsurface.uselightmaptexture = false;
11838         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
11839 }
11840
11841 void R_DrawCustomSurface_Texture(texture_t *texture, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
11842 {
11843         static msurface_t surface;
11844         const msurface_t *surfacelist = &surface;
11845
11846         // fake enough texture and surface state to render this geometry
11847         surface.texture = texture;
11848         surface.num_triangles = numtriangles;
11849         surface.num_firsttriangle = firsttriangle;
11850         surface.num_vertices = numvertices;
11851         surface.num_firstvertex = firstvertex;
11852
11853         // now render it
11854         rsurface.texture = R_GetCurrentTexture(surface.texture);
11855         rsurface.lightmaptexture = NULL;
11856         rsurface.deluxemaptexture = NULL;
11857         rsurface.uselightmaptexture = false;
11858         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
11859 }