fix r_drawviewmodel
[divverent/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
29 mempool_t *r_main_mempool;
30 rtexturepool_t *r_main_texturepool;
31
32 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
33
34 static qboolean r_loadnormalmap;
35 static qboolean r_loadgloss;
36 qboolean r_loadfog;
37 static qboolean r_loaddds;
38 static qboolean r_savedds;
39
40 //
41 // screen size info
42 //
43 r_refdef_t r_refdef;
44
45 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
46 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
47 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
48 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
49 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
50 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
51 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
52 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
53
54 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
55 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"};
56 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
57 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)"};
58 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
59
60 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"};
61 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
62 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
63 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
64 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
65 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
66 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)"};
67 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
68 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
69 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"};
70 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"};
71 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
72 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"};
73 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"};
74 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"};
75 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
76 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
77 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
78 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
79 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)"};
80 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)"};
81 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
82 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
83 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
84 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
85 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
86 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
87 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
88 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."};
89 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
90 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
91 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
92 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."};
93 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
94 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
95 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"};
96 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"};
97 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
98 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
99 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
100 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
101 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"};
102
103 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
104 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
105 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
106 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
107 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
108 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
109 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
110 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
111
112 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)"};
113 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"};
114
115 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
116 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
117 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
118
119 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)"};
120 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
121 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
122 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
123 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
124 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)"};
125 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)"};
126 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)"};
127 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)"};
128
129 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)"};
130 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
131 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"};
132 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
133 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
134
135 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
136 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
137 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
138 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
139
140 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
141 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
142 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
143 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
144 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
145 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
146 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
147
148 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
149 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
150 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
151 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivilant to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
152
153 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"};
154
155 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"};
156
157 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
158
159 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
160 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
161 cvar_t r_track_sprites = {CVAR_SAVE, "r_track_sprites", "1", "track SPR_LABEL* sprites by putting them as indicator at the screen border to rotate to"};
162 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
163 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
164 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
165 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
166 cvar_t r_overheadsprites_pushback = {CVAR_SAVE, "r_overheadsprites_pushback", "16", "how far to pull the SPR_OVERHEAD sprites toward the eye (used to avoid intersections with 3D models)"};
167
168 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
169
170 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "1", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
171
172 extern cvar_t v_glslgamma;
173
174 extern qboolean v_flipped_state;
175
176 static struct r_bloomstate_s
177 {
178         qboolean enabled;
179         qboolean hdr;
180
181         int bloomwidth, bloomheight;
182
183         int screentexturewidth, screentextureheight;
184         rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
185
186         int bloomtexturewidth, bloomtextureheight;
187         rtexture_t *texture_bloom;
188
189         // arrays for rendering the screen passes
190         float screentexcoord2f[8];
191         float bloomtexcoord2f[8];
192         float offsettexcoord2f[8];
193
194         r_viewport_t viewport;
195 }
196 r_bloomstate;
197
198 r_waterstate_t r_waterstate;
199
200 /// shadow volume bsp struct with automatically growing nodes buffer
201 svbsp_t r_svbsp;
202
203 rtexture_t *r_texture_blanknormalmap;
204 rtexture_t *r_texture_white;
205 rtexture_t *r_texture_grey128;
206 rtexture_t *r_texture_black;
207 rtexture_t *r_texture_notexture;
208 rtexture_t *r_texture_whitecube;
209 rtexture_t *r_texture_normalizationcube;
210 rtexture_t *r_texture_fogattenuation;
211 rtexture_t *r_texture_gammaramps;
212 unsigned int r_texture_gammaramps_serial;
213 //rtexture_t *r_texture_fogintensity;
214 rtexture_t *r_texture_reflectcube;
215
216 // TODO: hash lookups?
217 typedef struct cubemapinfo_s
218 {
219         char basename[64];
220         rtexture_t *texture;
221 }
222 cubemapinfo_t;
223
224 int r_texture_numcubemaps;
225 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
226
227 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
228 unsigned int r_numqueries;
229 unsigned int r_maxqueries;
230
231 typedef struct r_qwskincache_s
232 {
233         char name[MAX_QPATH];
234         skinframe_t *skinframe;
235 }
236 r_qwskincache_t;
237
238 static r_qwskincache_t *r_qwskincache;
239 static int r_qwskincache_size;
240
241 /// vertex coordinates for a quad that covers the screen exactly
242 const float r_screenvertex3f[12] =
243 {
244         0, 0, 0,
245         1, 0, 0,
246         1, 1, 0,
247         0, 1, 0
248 };
249
250 extern void R_DrawModelShadows(void);
251
252 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
253 {
254         int i;
255         for (i = 0;i < verts;i++)
256         {
257                 out[0] = in[0] * r;
258                 out[1] = in[1] * g;
259                 out[2] = in[2] * b;
260                 out[3] = in[3];
261                 in += 4;
262                 out += 4;
263         }
264 }
265
266 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
267 {
268         int i;
269         for (i = 0;i < verts;i++)
270         {
271                 out[0] = r;
272                 out[1] = g;
273                 out[2] = b;
274                 out[3] = a;
275                 out += 4;
276         }
277 }
278
279 // FIXME: move this to client?
280 void FOG_clear(void)
281 {
282         if (gamemode == GAME_NEHAHRA)
283         {
284                 Cvar_Set("gl_fogenable", "0");
285                 Cvar_Set("gl_fogdensity", "0.2");
286                 Cvar_Set("gl_fogred", "0.3");
287                 Cvar_Set("gl_foggreen", "0.3");
288                 Cvar_Set("gl_fogblue", "0.3");
289         }
290         r_refdef.fog_density = 0;
291         r_refdef.fog_red = 0;
292         r_refdef.fog_green = 0;
293         r_refdef.fog_blue = 0;
294         r_refdef.fog_alpha = 1;
295         r_refdef.fog_start = 0;
296         r_refdef.fog_end = 16384;
297         r_refdef.fog_height = 1<<30;
298         r_refdef.fog_fadedepth = 128;
299 }
300
301 static void R_BuildBlankTextures(void)
302 {
303         unsigned char data[4];
304         data[2] = 128; // normal X
305         data[1] = 128; // normal Y
306         data[0] = 255; // normal Z
307         data[3] = 128; // height
308         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
309         data[0] = 255;
310         data[1] = 255;
311         data[2] = 255;
312         data[3] = 255;
313         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
314         data[0] = 128;
315         data[1] = 128;
316         data[2] = 128;
317         data[3] = 255;
318         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
319         data[0] = 0;
320         data[1] = 0;
321         data[2] = 0;
322         data[3] = 255;
323         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
324 }
325
326 static void R_BuildNoTexture(void)
327 {
328         int x, y;
329         unsigned char pix[16][16][4];
330         // this makes a light grey/dark grey checkerboard texture
331         for (y = 0;y < 16;y++)
332         {
333                 for (x = 0;x < 16;x++)
334                 {
335                         if ((y < 8) ^ (x < 8))
336                         {
337                                 pix[y][x][0] = 128;
338                                 pix[y][x][1] = 128;
339                                 pix[y][x][2] = 128;
340                                 pix[y][x][3] = 255;
341                         }
342                         else
343                         {
344                                 pix[y][x][0] = 64;
345                                 pix[y][x][1] = 64;
346                                 pix[y][x][2] = 64;
347                                 pix[y][x][3] = 255;
348                         }
349                 }
350         }
351         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, NULL);
352 }
353
354 static void R_BuildWhiteCube(void)
355 {
356         unsigned char data[6*1*1*4];
357         memset(data, 255, sizeof(data));
358         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, NULL);
359 }
360
361 static void R_BuildNormalizationCube(void)
362 {
363         int x, y, side;
364         vec3_t v;
365         vec_t s, t, intensity;
366 #define NORMSIZE 64
367         unsigned char *data;
368         data = Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
369         for (side = 0;side < 6;side++)
370         {
371                 for (y = 0;y < NORMSIZE;y++)
372                 {
373                         for (x = 0;x < NORMSIZE;x++)
374                         {
375                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
376                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
377                                 switch(side)
378                                 {
379                                 default:
380                                 case 0:
381                                         v[0] = 1;
382                                         v[1] = -t;
383                                         v[2] = -s;
384                                         break;
385                                 case 1:
386                                         v[0] = -1;
387                                         v[1] = -t;
388                                         v[2] = s;
389                                         break;
390                                 case 2:
391                                         v[0] = s;
392                                         v[1] = 1;
393                                         v[2] = t;
394                                         break;
395                                 case 3:
396                                         v[0] = s;
397                                         v[1] = -1;
398                                         v[2] = -t;
399                                         break;
400                                 case 4:
401                                         v[0] = s;
402                                         v[1] = -t;
403                                         v[2] = 1;
404                                         break;
405                                 case 5:
406                                         v[0] = -s;
407                                         v[1] = -t;
408                                         v[2] = -1;
409                                         break;
410                                 }
411                                 intensity = 127.0f / sqrt(DotProduct(v, v));
412                                 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
413                                 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
414                                 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
415                                 data[((side*64+y)*64+x)*4+3] = 255;
416                         }
417                 }
418         }
419         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, NULL);
420         Mem_Free(data);
421 }
422
423 static void R_BuildFogTexture(void)
424 {
425         int x, b;
426 #define FOGWIDTH 256
427         unsigned char data1[FOGWIDTH][4];
428         //unsigned char data2[FOGWIDTH][4];
429         double d, r, alpha;
430
431         r_refdef.fogmasktable_start = r_refdef.fog_start;
432         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
433         r_refdef.fogmasktable_range = r_refdef.fogrange;
434         r_refdef.fogmasktable_density = r_refdef.fog_density;
435
436         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
437         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
438         {
439                 d = (x * r - r_refdef.fogmasktable_start);
440                 if(developer_extra.integer)
441                         Con_DPrintf("%f ", d);
442                 d = max(0, d);
443                 if (r_fog_exp2.integer)
444                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
445                 else
446                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
447                 if(developer_extra.integer)
448                         Con_DPrintf(" : %f ", alpha);
449                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
450                 if(developer_extra.integer)
451                         Con_DPrintf(" = %f\n", alpha);
452                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
453         }
454
455         for (x = 0;x < FOGWIDTH;x++)
456         {
457                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
458                 data1[x][0] = b;
459                 data1[x][1] = b;
460                 data1[x][2] = b;
461                 data1[x][3] = 255;
462                 //data2[x][0] = 255 - b;
463                 //data2[x][1] = 255 - b;
464                 //data2[x][2] = 255 - b;
465                 //data2[x][3] = 255;
466         }
467         if (r_texture_fogattenuation)
468         {
469                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
470                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
471         }
472         else
473         {
474                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, NULL);
475                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALLOWUPDATES, NULL);
476         }
477 }
478
479 //=======================================================================================================================================================
480
481 static const char *builtinshaderstring =
482 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
483 "// written by Forest 'LordHavoc' Hale\n"
484 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
485 "\n"
486 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE)\n"
487 "# define USEFOG\n"
488 "#endif\n"
489 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
490 "#define USELIGHTMAP\n"
491 "#endif\n"
492 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
493 "#define USEEYEVECTOR\n"
494 "#endif\n"
495 "\n"
496 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
497 "# extension GL_ARB_texture_rectangle : enable\n"
498 "#endif\n"
499 "\n"
500 "#ifdef USESHADOWMAP2D\n"
501 "# ifdef GL_EXT_gpu_shader4\n"
502 "#   extension GL_EXT_gpu_shader4 : enable\n"
503 "# endif\n"
504 "# ifdef GL_ARB_texture_gather\n"
505 "#   extension GL_ARB_texture_gather : enable\n"
506 "# else\n"
507 "#   ifdef GL_AMD_texture_texture4\n"
508 "#     extension GL_AMD_texture_texture4 : enable\n"
509 "#   endif\n"
510 "# endif\n"
511 "#endif\n"
512 "\n"
513 "#ifdef USESHADOWMAPCUBE\n"
514 "# extension GL_EXT_gpu_shader4 : enable\n"
515 "#endif\n"
516 "\n"
517 "//#ifdef USESHADOWSAMPLER\n"
518 "//# extension GL_ARB_shadow : enable\n"
519 "//#endif\n"
520 "\n"
521 "//#ifdef __GLSL_CG_DATA_TYPES\n"
522 "//# define myhalf half\n"
523 "//# define myhalf2 half2\n"
524 "//# define myhalf3 half3\n"
525 "//# define myhalf4 half4\n"
526 "//#else\n"
527 "# define myhalf float\n"
528 "# define myhalf2 vec2\n"
529 "# define myhalf3 vec3\n"
530 "# define myhalf4 vec4\n"
531 "//#endif\n"
532 "\n"
533 "#ifdef VERTEX_SHADER\n"
534 "uniform mat4 ModelViewProjectionMatrix;\n"
535 "#endif\n"
536 "\n"
537 "#ifdef MODE_DEPTH_OR_SHADOW\n"
538 "#ifdef VERTEX_SHADER\n"
539 "void main(void)\n"
540 "{\n"
541 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
542 "}\n"
543 "#endif\n"
544 "#else // !MODE_DEPTH_ORSHADOW\n"
545 "\n"
546 "\n"
547 "\n"
548 "\n"
549 "#ifdef MODE_SHOWDEPTH\n"
550 "#ifdef VERTEX_SHADER\n"
551 "void main(void)\n"
552 "{\n"
553 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
554 "       gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
555 "}\n"
556 "#endif\n"
557 "\n"
558 "#ifdef FRAGMENT_SHADER\n"
559 "void main(void)\n"
560 "{\n"
561 "       gl_FragColor = gl_Color;\n"
562 "}\n"
563 "#endif\n"
564 "#else // !MODE_SHOWDEPTH\n"
565 "\n"
566 "\n"
567 "\n"
568 "\n"
569 "#ifdef MODE_POSTPROCESS\n"
570 "varying vec2 TexCoord1;\n"
571 "varying vec2 TexCoord2;\n"
572 "\n"
573 "#ifdef VERTEX_SHADER\n"
574 "void main(void)\n"
575 "{\n"
576 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
577 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
578 "#ifdef USEBLOOM\n"
579 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
580 "#endif\n"
581 "}\n"
582 "#endif\n"
583 "\n"
584 "#ifdef FRAGMENT_SHADER\n"
585 "uniform sampler2D Texture_First;\n"
586 "#ifdef USEBLOOM\n"
587 "uniform sampler2D Texture_Second;\n"
588 "#endif\n"
589 "#ifdef USEGAMMARAMPS\n"
590 "uniform sampler2D Texture_GammaRamps;\n"
591 "#endif\n"
592 "#ifdef USESATURATION\n"
593 "uniform float Saturation;\n"
594 "#endif\n"
595 "#ifdef USEVIEWTINT\n"
596 "uniform vec4 ViewTintColor;\n"
597 "#endif\n"
598 "//uncomment these if you want to use them:\n"
599 "uniform vec4 UserVec1;\n"
600 "// uniform vec4 UserVec2;\n"
601 "// uniform vec4 UserVec3;\n"
602 "// uniform vec4 UserVec4;\n"
603 "// uniform float ClientTime;\n"
604 "uniform vec2 PixelSize;\n"
605 "void main(void)\n"
606 "{\n"
607 "       gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
608 "#ifdef USEBLOOM\n"
609 "       gl_FragColor += texture2D(Texture_Second, TexCoord2);\n"
610 "#endif\n"
611 "#ifdef USEVIEWTINT\n"
612 "       gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
613 "#endif\n"
614 "\n"
615 "#ifdef USEPOSTPROCESSING\n"
616 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
617 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
618 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
619 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
620 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
621 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107,  0.707107)) * UserVec1.y;\n"
622 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990,  0.891007)) * UserVec1.y;\n"
623 "       gl_FragColor /= (1 + 5 * UserVec1.y);\n"
624 "#endif\n"
625 "\n"
626 "#ifdef USESATURATION\n"
627 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
628 "       float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
629 "       //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
630 "       gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
631 "#endif\n"
632 "\n"
633 "#ifdef USEGAMMARAMPS\n"
634 "       gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
635 "       gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
636 "       gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
637 "#endif\n"
638 "}\n"
639 "#endif\n"
640 "#else // !MODE_POSTPROCESS\n"
641 "\n"
642 "\n"
643 "\n"
644 "\n"
645 "#ifdef MODE_GENERIC\n"
646 "#ifdef USEDIFFUSE\n"
647 "varying vec2 TexCoord1;\n"
648 "#endif\n"
649 "#ifdef USESPECULAR\n"
650 "varying vec2 TexCoord2;\n"
651 "#endif\n"
652 "#ifdef VERTEX_SHADER\n"
653 "void main(void)\n"
654 "{\n"
655 "       gl_FrontColor = gl_Color;\n"
656 "#ifdef USEDIFFUSE\n"
657 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
658 "#endif\n"
659 "#ifdef USESPECULAR\n"
660 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
661 "#endif\n"
662 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
663 "}\n"
664 "#endif\n"
665 "\n"
666 "#ifdef FRAGMENT_SHADER\n"
667 "#ifdef USEDIFFUSE\n"
668 "uniform sampler2D Texture_First;\n"
669 "#endif\n"
670 "#ifdef USESPECULAR\n"
671 "uniform sampler2D Texture_Second;\n"
672 "#endif\n"
673 "\n"
674 "void main(void)\n"
675 "{\n"
676 "       gl_FragColor = gl_Color;\n"
677 "#ifdef USEDIFFUSE\n"
678 "       gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
679 "#endif\n"
680 "\n"
681 "#ifdef USESPECULAR\n"
682 "       vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
683 "# ifdef USECOLORMAPPING\n"
684 "       gl_FragColor *= tex2;\n"
685 "# endif\n"
686 "# ifdef USEGLOW\n"
687 "       gl_FragColor += tex2;\n"
688 "# endif\n"
689 "# ifdef USEVERTEXTEXTUREBLEND\n"
690 "       gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
691 "# endif\n"
692 "#endif\n"
693 "}\n"
694 "#endif\n"
695 "#else // !MODE_GENERIC\n"
696 "\n"
697 "\n"
698 "\n"
699 "\n"
700 "#ifdef MODE_BLOOMBLUR\n"
701 "varying TexCoord;\n"
702 "#ifdef VERTEX_SHADER\n"
703 "void main(void)\n"
704 "{\n"
705 "       gl_FrontColor = gl_Color;\n"
706 "       TexCoord = gl_MultiTexCoord0.xy;\n"
707 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
708 "}\n"
709 "#endif\n"
710 "\n"
711 "#ifdef FRAGMENT_SHADER\n"
712 "uniform sampler2D Texture_First;\n"
713 "uniform vec4 BloomBlur_Parameters;\n"
714 "\n"
715 "void main(void)\n"
716 "{\n"
717 "       int i;\n"
718 "       vec2 tc = TexCoord;\n"
719 "       vec3 color = texture2D(Texture_First, tc).rgb;\n"
720 "       tc += BloomBlur_Parameters.xy;\n"
721 "       for (i = 1;i < SAMPLES;i++)\n"
722 "       {\n"
723 "               color += texture2D(Texture_First, tc).rgb;\n"
724 "               tc += BloomBlur_Parameters.xy;\n"
725 "       }\n"
726 "       gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
727 "}\n"
728 "#endif\n"
729 "#else // !MODE_BLOOMBLUR\n"
730 "#ifdef MODE_REFRACTION\n"
731 "varying vec2 TexCoord;\n"
732 "varying vec4 ModelViewProjectionPosition;\n"
733 "uniform mat4 TexMatrix;\n"
734 "#ifdef VERTEX_SHADER\n"
735 "\n"
736 "void main(void)\n"
737 "{\n"
738 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
739 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
740 "       ModelViewProjectionPosition = gl_Position;\n"
741 "}\n"
742 "#endif\n"
743 "\n"
744 "#ifdef FRAGMENT_SHADER\n"
745 "uniform sampler2D Texture_Normal;\n"
746 "uniform sampler2D Texture_Refraction;\n"
747 "uniform sampler2D Texture_Reflection;\n"
748 "\n"
749 "uniform vec4 DistortScaleRefractReflect;\n"
750 "uniform vec4 ScreenScaleRefractReflect;\n"
751 "uniform vec4 ScreenCenterRefractReflect;\n"
752 "uniform vec4 RefractColor;\n"
753 "uniform vec4 ReflectColor;\n"
754 "uniform float ReflectFactor;\n"
755 "uniform float ReflectOffset;\n"
756 "\n"
757 "void main(void)\n"
758 "{\n"
759 "       vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
760 "       //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
761 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
762 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
763 "       // FIXME temporary hack to detect the case that the reflection\n"
764 "       // gets blackened at edges due to leaving the area that contains actual\n"
765 "       // content.\n"
766 "       // Remove this 'ack once we have a better way to stop this thing from\n"
767 "       // 'appening.\n"
768 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
769 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
770 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
771 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
772 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
773 "       gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
774 "}\n"
775 "#endif\n"
776 "#else // !MODE_REFRACTION\n"
777 "\n"
778 "\n"
779 "\n"
780 "\n"
781 "#ifdef MODE_WATER\n"
782 "varying vec2 TexCoord;\n"
783 "varying vec3 EyeVector;\n"
784 "varying vec4 ModelViewProjectionPosition;\n"
785 "#ifdef VERTEX_SHADER\n"
786 "uniform vec3 EyePosition;\n"
787 "uniform mat4 TexMatrix;\n"
788 "\n"
789 "void main(void)\n"
790 "{\n"
791 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
792 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
793 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
794 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
795 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
796 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
797 "       ModelViewProjectionPosition = gl_Position;\n"
798 "}\n"
799 "#endif\n"
800 "\n"
801 "#ifdef FRAGMENT_SHADER\n"
802 "uniform sampler2D Texture_Normal;\n"
803 "uniform sampler2D Texture_Refraction;\n"
804 "uniform sampler2D Texture_Reflection;\n"
805 "\n"
806 "uniform vec4 DistortScaleRefractReflect;\n"
807 "uniform vec4 ScreenScaleRefractReflect;\n"
808 "uniform vec4 ScreenCenterRefractReflect;\n"
809 "uniform vec4 RefractColor;\n"
810 "uniform vec4 ReflectColor;\n"
811 "uniform float ReflectFactor;\n"
812 "uniform float ReflectOffset;\n"
813 "\n"
814 "void main(void)\n"
815 "{\n"
816 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
817 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
818 "       vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
819 "       //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
820 "       vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
821 "       // FIXME temporary hack to detect the case that the reflection\n"
822 "       // gets blackened at edges due to leaving the area that contains actual\n"
823 "       // content.\n"
824 "       // Remove this 'ack once we have a better way to stop this thing from\n"
825 "       // 'appening.\n"
826 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
827 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
828 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
829 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
830 "       ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
831 "       f       = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
832 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
833 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
834 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
835 "       ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
836 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
837 "       gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
838 "}\n"
839 "#endif\n"
840 "#else // !MODE_WATER\n"
841 "\n"
842 "\n"
843 "\n"
844 "\n"
845 "// common definitions between vertex shader and fragment shader:\n"
846 "\n"
847 "varying vec2 TexCoord;\n"
848 "#ifdef USEVERTEXTEXTUREBLEND\n"
849 "varying vec2 TexCoord2;\n"
850 "#endif\n"
851 "#ifdef USELIGHTMAP\n"
852 "varying vec2 TexCoordLightmap;\n"
853 "#endif\n"
854 "\n"
855 "#ifdef MODE_LIGHTSOURCE\n"
856 "varying vec3 CubeVector;\n"
857 "#endif\n"
858 "\n"
859 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
860 "varying vec3 LightVector;\n"
861 "#endif\n"
862 "\n"
863 "#ifdef USEEYEVECTOR\n"
864 "varying vec3 EyeVector;\n"
865 "#endif\n"
866 "#ifdef USEFOG\n"
867 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
868 "#endif\n"
869 "\n"
870 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
871 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
872 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
873 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
874 "#endif\n"
875 "\n"
876 "#ifdef USEREFLECTION\n"
877 "varying vec4 ModelViewProjectionPosition;\n"
878 "#endif\n"
879 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
880 "uniform vec3 LightPosition;\n"
881 "varying vec4 ModelViewPosition;\n"
882 "#endif\n"
883 "\n"
884 "#ifdef MODE_LIGHTSOURCE\n"
885 "uniform vec3 LightPosition;\n"
886 "#endif\n"
887 "uniform vec3 EyePosition;\n"
888 "#ifdef MODE_LIGHTDIRECTION\n"
889 "uniform vec3 LightDir;\n"
890 "#endif\n"
891 "uniform vec4 FogPlane;\n"
892 "\n"
893 "\n"
894 "\n"
895 "\n"
896 "\n"
897 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
898 "\n"
899 "// fragment shader specific:\n"
900 "#ifdef FRAGMENT_SHADER\n"
901 "\n"
902 "uniform sampler2D Texture_Normal;\n"
903 "uniform sampler2D Texture_Color;\n"
904 "uniform sampler2D Texture_Gloss;\n"
905 "#ifdef USEGLOW\n"
906 "uniform sampler2D Texture_Glow;\n"
907 "#endif\n"
908 "#ifdef USEVERTEXTEXTUREBLEND\n"
909 "uniform sampler2D Texture_SecondaryNormal;\n"
910 "uniform sampler2D Texture_SecondaryColor;\n"
911 "uniform sampler2D Texture_SecondaryGloss;\n"
912 "#ifdef USEGLOW\n"
913 "uniform sampler2D Texture_SecondaryGlow;\n"
914 "#endif\n"
915 "#endif\n"
916 "#ifdef USECOLORMAPPING\n"
917 "uniform sampler2D Texture_Pants;\n"
918 "uniform sampler2D Texture_Shirt;\n"
919 "#endif\n"
920 "#ifdef USEFOG\n"
921 "uniform sampler2D Texture_FogMask;\n"
922 "#endif\n"
923 "#ifdef USELIGHTMAP\n"
924 "uniform sampler2D Texture_Lightmap;\n"
925 "#endif\n"
926 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
927 "uniform sampler2D Texture_Deluxemap;\n"
928 "#endif\n"
929 "#ifdef USEREFLECTION\n"
930 "uniform sampler2D Texture_Reflection;\n"
931 "#endif\n"
932 "\n"
933 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
934 "uniform sampler2D Texture_ScreenDepth;\n"
935 "uniform sampler2D Texture_ScreenNormalMap;\n"
936 "#endif\n"
937 "#ifdef USEDEFERREDLIGHTMAP\n"
938 "uniform sampler2D Texture_ScreenDiffuse;\n"
939 "uniform sampler2D Texture_ScreenSpecular;\n"
940 "#endif\n"
941 "\n"
942 "uniform myhalf3 Color_Pants;\n"
943 "uniform myhalf3 Color_Shirt;\n"
944 "uniform myhalf3 FogColor;\n"
945 "\n"
946 "#ifdef USEFOG\n"
947 "uniform float FogRangeRecip;\n"
948 "uniform float FogPlaneViewDist;\n"
949 "uniform float FogHeightFade;\n"
950 "float FogVertex(void)\n"
951 "{\n"
952 "       vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
953 "       float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
954 "       float fogfrac;\n"
955 "#ifdef USEFOGOUTSIDE\n"
956 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
957 "#else\n"
958 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
959 "#endif\n"
960 "       return float(texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)));\n"
961 "}\n"
962 "#endif\n"
963 "\n"
964 "#ifdef USEOFFSETMAPPING\n"
965 "uniform float OffsetMapping_Scale;\n"
966 "vec2 OffsetMapping(vec2 TexCoord)\n"
967 "{\n"
968 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
969 "       // 14 sample relief mapping: linear search and then binary search\n"
970 "       // this basically steps forward a small amount repeatedly until it finds\n"
971 "       // itself inside solid, then jitters forward and back using decreasing\n"
972 "       // amounts to find the impact\n"
973 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
974 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
975 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
976 "       vec3 RT = vec3(TexCoord, 1);\n"
977 "       OffsetVector *= 0.1;\n"
978 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
979 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
980 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
981 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
982 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
983 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
984 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
985 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
986 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
987 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
988 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
989 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
990 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
991 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
992 "       return RT.xy;\n"
993 "#else\n"
994 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
995 "       // this basically moves forward the full distance, and then backs up based\n"
996 "       // on height of samples\n"
997 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
998 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
999 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1000 "       TexCoord += OffsetVector;\n"
1001 "       OffsetVector *= 0.333;\n"
1002 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1003 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1004 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1005 "       return TexCoord;\n"
1006 "#endif\n"
1007 "}\n"
1008 "#endif // USEOFFSETMAPPING\n"
1009 "\n"
1010 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1011 "uniform sampler2D Texture_Attenuation;\n"
1012 "uniform samplerCube Texture_Cube;\n"
1013 "\n"
1014 "#ifdef USESHADOWMAPRECT\n"
1015 "# ifdef USESHADOWSAMPLER\n"
1016 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1017 "# else\n"
1018 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1019 "# endif\n"
1020 "#endif\n"
1021 "\n"
1022 "#ifdef USESHADOWMAP2D\n"
1023 "# ifdef USESHADOWSAMPLER\n"
1024 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1025 "# else\n"
1026 "uniform sampler2D Texture_ShadowMap2D;\n"
1027 "# endif\n"
1028 "#endif\n"
1029 "\n"
1030 "#ifdef USESHADOWMAPVSDCT\n"
1031 "uniform samplerCube Texture_CubeProjection;\n"
1032 "#endif\n"
1033 "\n"
1034 "#ifdef USESHADOWMAPCUBE\n"
1035 "# ifdef USESHADOWSAMPLER\n"
1036 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1037 "# else\n"
1038 "uniform samplerCube Texture_ShadowMapCube;\n"
1039 "# endif\n"
1040 "#endif\n"
1041 "\n"
1042 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1043 "uniform vec2 ShadowMap_TextureScale;\n"
1044 "uniform vec4 ShadowMap_Parameters;\n"
1045 "#endif\n"
1046 "\n"
1047 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1048 "# ifndef USESHADOWMAPVSDCT\n"
1049 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1050 "{\n"
1051 "       vec3 adir = abs(dir);\n"
1052 "       vec2 tc;\n"
1053 "       vec2 offset;\n"
1054 "       float ma;\n"
1055 "       if (adir.x > adir.y)\n"
1056 "       {\n"
1057 "               if (adir.x > adir.z) // X\n"
1058 "               {\n"
1059 "                       ma = adir.x;\n"
1060 "                       tc = dir.zy;\n"
1061 "                       offset = vec2(mix(0.5, 1.5, dir.x < 0.0), 0.5);\n"
1062 "               }\n"
1063 "               else // Z\n"
1064 "               {\n"
1065 "                       ma = adir.z;\n"
1066 "                       tc = dir.xy;\n"
1067 "                       offset = vec2(mix(0.5, 1.5, dir.z < 0.0), 2.5);\n"
1068 "               }\n"
1069 "       }\n"
1070 "       else\n"
1071 "       {\n"
1072 "               if (adir.y > adir.z) // Y\n"
1073 "               {\n"
1074 "                       ma = adir.y;\n"
1075 "                       tc = dir.xz;\n"
1076 "                       offset = vec2(mix(0.5, 1.5, dir.y < 0.0), 1.5);\n"
1077 "               }\n"
1078 "               else // Z\n"
1079 "               {\n"
1080 "                       ma = adir.z;\n"
1081 "                       tc = dir.xy;\n"
1082 "                       offset = vec2(mix(0.5, 1.5, dir.z < 0.0), 2.5);\n"
1083 "               }\n"
1084 "       }\n"
1085 "\n"
1086 "       vec3 stc = vec3(tc * ShadowMap_Parameters.x, ShadowMap_Parameters.w) / ma;\n"
1087 "       stc.xy += offset * ShadowMap_Parameters.y;\n"
1088 "       stc.z += ShadowMap_Parameters.z;\n"
1089 "       return stc;\n"
1090 "}\n"
1091 "# else\n"
1092 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1093 "{\n"
1094 "       vec3 adir = abs(dir);\n"
1095 "       vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1096 "       float ma = max(max(adir.x, adir.y), adir.z);\n"
1097 "       vec3 stc = vec3(mix(dir.xy, dir.zz, proj.xy) * ShadowMap_Parameters.x, ShadowMap_Parameters.w) / ma;\n"
1098 "       stc.xy += proj.zw * ShadowMap_Parameters.y;\n"
1099 "       stc.z += ShadowMap_Parameters.z;\n"
1100 "       return stc;\n"
1101 "}\n"
1102 "# endif\n"
1103 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1104 "\n"
1105 "#ifdef USESHADOWMAPCUBE\n"
1106 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1107 "{\n"
1108 "       vec3 adir = abs(dir);\n"
1109 "       return vec4(dir, ShadowMap_Parameters.z + ShadowMap_Parameters.w / max(max(adir.x, adir.y), adir.z));\n"
1110 "}\n"
1111 "#endif\n"
1112 "\n"
1113 "# ifdef USESHADOWMAPRECT\n"
1114 "float ShadowMapCompare(vec3 dir)\n"
1115 "{\n"
1116 "       vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1117 "       float f;\n"
1118 "#  ifdef USESHADOWSAMPLER\n"
1119 "\n"
1120 "#    ifdef USESHADOWMAPPCF\n"
1121 "#      define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1122 "       f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1123 "#    else\n"
1124 "       f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1125 "#    endif\n"
1126 "\n"
1127 "#  else\n"
1128 "\n"
1129 "#    ifdef USESHADOWMAPPCF\n"
1130 "#      if USESHADOWMAPPCF > 1\n"
1131 "#        define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1132 "       vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1133 "       vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1134 "       vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
1135 "       vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
1136 "       vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
1137 "       vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1138 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1139 "#      else\n"
1140 "#        define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1141 "       vec2 offset = fract(shadowmaptc.xy);\n"
1142 "       vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1143 "       vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1144 "       vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1145 "       vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1146 "       f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1147 "#      endif\n"
1148 "#    else\n"
1149 "       f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1150 "#    endif\n"
1151 "\n"
1152 "#  endif\n"
1153 "       return f;\n"
1154 "}\n"
1155 "# endif\n"
1156 "\n"
1157 "# ifdef USESHADOWMAP2D\n"
1158 "float ShadowMapCompare(vec3 dir)\n"
1159 "{\n"
1160 "       vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1161 "       float f;\n"
1162 "\n"
1163 "#  ifdef USESHADOWSAMPLER\n"
1164 "#    ifdef USESHADOWMAPPCF\n"
1165 "#      define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r  \n"
1166 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1167 "       f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1168 "#    else\n"
1169 "       f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1170 "#    endif\n"
1171 "#  else\n"
1172 "#    ifdef USESHADOWMAPPCF\n"
1173 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1174 "#      ifdef GL_ARB_texture_gather\n"
1175 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1176 "#      else\n"
1177 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1178 "#      endif\n"
1179 "       vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1180 "       center *= ShadowMap_TextureScale;\n"
1181 "       vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1182 "       vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1183 "       vec4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
1184 "       vec4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
1185 "       vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1186 "                               mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1187 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1188 "#     else\n"
1189 "#      ifdef GL_EXT_gpu_shader4\n"
1190 "#        define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1191 "#      else\n"
1192 "#        define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r  \n"
1193 "#      endif\n"
1194 "#      if USESHADOWMAPPCF > 1\n"
1195 "       vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1196 "       center *= ShadowMap_TextureScale;\n"
1197 "       vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1198 "       vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
1199 "       vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
1200 "       vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
1201 "       vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1202 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1203 "#      else\n"
1204 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1205 "       vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1206 "       vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1207 "       vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1208 "       vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1209 "       f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1210 "#      endif\n"
1211 "#     endif\n"
1212 "#    else\n"
1213 "       f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1214 "#    endif\n"
1215 "#  endif\n"
1216 "       return f;\n"
1217 "}\n"
1218 "# endif\n"
1219 "\n"
1220 "# ifdef USESHADOWMAPCUBE\n"
1221 "float ShadowMapCompare(vec3 dir)\n"
1222 "{\n"
1223 "       // apply depth texture cubemap as light filter\n"
1224 "       vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1225 "       float f;\n"
1226 "#  ifdef USESHADOWSAMPLER\n"
1227 "       f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1228 "#  else\n"
1229 "       f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1230 "#  endif\n"
1231 "       return f;\n"
1232 "}\n"
1233 "# endif\n"
1234 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
1235 "#endif // FRAGMENT_SHADER\n"
1236 "\n"
1237 "\n"
1238 "\n"
1239 "\n"
1240 "#ifdef MODE_DEFERREDGEOMETRY\n"
1241 "#ifdef VERTEX_SHADER\n"
1242 "uniform mat4 TexMatrix;\n"
1243 "#ifdef USEVERTEXTEXTUREBLEND\n"
1244 "uniform mat4 BackgroundTexMatrix;\n"
1245 "#endif\n"
1246 "uniform mat4 ModelViewMatrix;\n"
1247 "void main(void)\n"
1248 "{\n"
1249 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1250 "#ifdef USEVERTEXTEXTUREBLEND\n"
1251 "       gl_FrontColor = gl_Color;\n"
1252 "       TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1253 "#endif\n"
1254 "\n"
1255 "       // transform unnormalized eye direction into tangent space\n"
1256 "#ifdef USEOFFSETMAPPING\n"
1257 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1258 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1259 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1260 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1261 "#endif\n"
1262 "\n"
1263 "       VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1264 "       VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1265 "       VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1266 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1267 "}\n"
1268 "#endif // VERTEX_SHADER\n"
1269 "\n"
1270 "#ifdef FRAGMENT_SHADER\n"
1271 "void main(void)\n"
1272 "{\n"
1273 "#ifdef USEOFFSETMAPPING\n"
1274 "       // apply offsetmapping\n"
1275 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1276 "#define TexCoord TexCoordOffset\n"
1277 "#endif\n"
1278 "\n"
1279 "#ifdef USEALPHAKILL\n"
1280 "       if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1281 "               discard;\n"
1282 "#endif\n"
1283 "\n"
1284 "#ifdef USEVERTEXTEXTUREBLEND\n"
1285 "       float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1286 "       float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1287 "       //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1288 "       //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1289 "#endif\n"
1290 "\n"
1291 "#ifdef USEVERTEXTEXTUREBLEND\n"
1292 "       vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1293 "       float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1294 "#else\n"
1295 "       vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1296 "       float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1297 "#endif\n"
1298 "\n"
1299 "       gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1300 "}\n"
1301 "#endif // FRAGMENT_SHADER\n"
1302 "#else // !MODE_DEFERREDGEOMETRY\n"
1303 "\n"
1304 "\n"
1305 "\n"
1306 "\n"
1307 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1308 "#ifdef VERTEX_SHADER\n"
1309 "uniform mat4 ModelViewMatrix;\n"
1310 "void main(void)\n"
1311 "{\n"
1312 "       ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1313 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1314 "}\n"
1315 "#endif // VERTEX_SHADER\n"
1316 "\n"
1317 "#ifdef FRAGMENT_SHADER\n"
1318 "uniform mat4 ViewToLight;\n"
1319 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1320 "uniform vec2 ScreenToDepth;\n"
1321 "uniform myhalf3 DeferredColor_Ambient;\n"
1322 "uniform myhalf3 DeferredColor_Diffuse;\n"
1323 "#ifdef USESPECULAR\n"
1324 "uniform myhalf3 DeferredColor_Specular;\n"
1325 "uniform myhalf SpecularPower;\n"
1326 "#endif\n"
1327 "uniform myhalf2 PixelToScreenTexCoord;\n"
1328 "void main(void)\n"
1329 "{\n"
1330 "       // calculate viewspace pixel position\n"
1331 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1332 "       vec3 position;\n"
1333 "       position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1334 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1335 "       // decode viewspace pixel normal\n"
1336 "       myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1337 "       myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1338 "       // surfacenormal = pixel normal in viewspace\n"
1339 "       // LightVector = pixel to light in viewspace\n"
1340 "       // CubeVector = position in lightspace\n"
1341 "       // eyevector = pixel to view in viewspace\n"
1342 "       vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1343 "       myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1344 "#ifdef USEDIFFUSE\n"
1345 "       // calculate diffuse shading\n"
1346 "       myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1347 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1348 "#endif\n"
1349 "#ifdef USESPECULAR\n"
1350 "       // calculate directional shading\n"
1351 "       vec3 eyevector = position * -1.0;\n"
1352 "#  ifdef USEEXACTSPECULARMATH\n"
1353 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1354 "#  else\n"
1355 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1356 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1357 "#  endif\n"
1358 "#endif\n"
1359 "\n"
1360 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1361 "       fade *= ShadowMapCompare(CubeVector);\n"
1362 "#endif\n"
1363 "\n"
1364 "#ifdef USEDIFFUSE\n"
1365 "       gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1366 "#else\n"
1367 "       gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1368 "#endif\n"
1369 "#ifdef USESPECULAR\n"
1370 "       gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1371 "#else\n"
1372 "       gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1373 "#endif\n"
1374 "\n"
1375 "# ifdef USECUBEFILTER\n"
1376 "       vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1377 "       gl_FragData[0].rgb *= cubecolor;\n"
1378 "       gl_FragData[1].rgb *= cubecolor;\n"
1379 "# endif\n"
1380 "}\n"
1381 "#endif // FRAGMENT_SHADER\n"
1382 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1383 "\n"
1384 "\n"
1385 "\n"
1386 "\n"
1387 "#ifdef VERTEX_SHADER\n"
1388 "uniform mat4 TexMatrix;\n"
1389 "#ifdef USEVERTEXTEXTUREBLEND\n"
1390 "uniform mat4 BackgroundTexMatrix;\n"
1391 "#endif\n"
1392 "#ifdef MODE_LIGHTSOURCE\n"
1393 "uniform mat4 ModelToLight;\n"
1394 "#endif\n"
1395 "void main(void)\n"
1396 "{\n"
1397 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1398 "       gl_FrontColor = gl_Color;\n"
1399 "#endif\n"
1400 "       // copy the surface texcoord\n"
1401 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1402 "#ifdef USEVERTEXTEXTUREBLEND\n"
1403 "       TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1404 "#endif\n"
1405 "#ifdef USELIGHTMAP\n"
1406 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1407 "#endif\n"
1408 "\n"
1409 "#ifdef MODE_LIGHTSOURCE\n"
1410 "       // transform vertex position into light attenuation/cubemap space\n"
1411 "       // (-1 to +1 across the light box)\n"
1412 "       CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1413 "\n"
1414 "# ifdef USEDIFFUSE\n"
1415 "       // transform unnormalized light direction into tangent space\n"
1416 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
1417 "       //  normalize it per pixel)\n"
1418 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1419 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1420 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1421 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1422 "# endif\n"
1423 "#endif\n"
1424 "\n"
1425 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1426 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1427 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1428 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1429 "#endif\n"
1430 "\n"
1431 "       // transform unnormalized eye direction into tangent space\n"
1432 "#ifdef USEEYEVECTOR\n"
1433 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1434 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1435 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1436 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1437 "#endif\n"
1438 "\n"
1439 "#ifdef USEFOG\n"
1440 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1441 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1442 "#endif\n"
1443 "\n"
1444 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1445 "       VectorS = gl_MultiTexCoord1.xyz;\n"
1446 "       VectorT = gl_MultiTexCoord2.xyz;\n"
1447 "       VectorR = gl_MultiTexCoord3.xyz;\n"
1448 "#endif\n"
1449 "\n"
1450 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1451 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1452 "\n"
1453 "#ifdef USEREFLECTION\n"
1454 "       ModelViewProjectionPosition = gl_Position;\n"
1455 "#endif\n"
1456 "}\n"
1457 "#endif // VERTEX_SHADER\n"
1458 "\n"
1459 "\n"
1460 "\n"
1461 "\n"
1462 "#ifdef FRAGMENT_SHADER\n"
1463 "#ifdef USEDEFERREDLIGHTMAP\n"
1464 "uniform myhalf2 PixelToScreenTexCoord;\n"
1465 "uniform myhalf3 DeferredMod_Diffuse;\n"
1466 "uniform myhalf3 DeferredMod_Specular;\n"
1467 "#endif\n"
1468 "uniform myhalf3 Color_Ambient;\n"
1469 "uniform myhalf3 Color_Diffuse;\n"
1470 "uniform myhalf3 Color_Specular;\n"
1471 "uniform myhalf SpecularPower;\n"
1472 "#ifdef USEGLOW\n"
1473 "uniform myhalf3 Color_Glow;\n"
1474 "#endif\n"
1475 "uniform myhalf Alpha;\n"
1476 "#ifdef USEREFLECTION\n"
1477 "uniform vec4 DistortScaleRefractReflect;\n"
1478 "uniform vec4 ScreenScaleRefractReflect;\n"
1479 "uniform vec4 ScreenCenterRefractReflect;\n"
1480 "uniform myhalf4 ReflectColor;\n"
1481 "#endif\n"
1482 "#ifdef USEREFLECTCUBE\n"
1483 "uniform mat4 ModelToReflectCube;\n"
1484 "uniform sampler2D Texture_ReflectMask;\n"
1485 "uniform samplerCube Texture_ReflectCube;\n"
1486 "#endif\n"
1487 "#ifdef MODE_LIGHTDIRECTION\n"
1488 "uniform myhalf3 LightColor;\n"
1489 "#endif\n"
1490 "#ifdef MODE_LIGHTSOURCE\n"
1491 "uniform myhalf3 LightColor;\n"
1492 "#endif\n"
1493 "void main(void)\n"
1494 "{\n"
1495 "#ifdef USEOFFSETMAPPING\n"
1496 "       // apply offsetmapping\n"
1497 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1498 "#define TexCoord TexCoordOffset\n"
1499 "#endif\n"
1500 "\n"
1501 "       // combine the diffuse textures (base, pants, shirt)\n"
1502 "       myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1503 "#ifdef USEALPHAKILL\n"
1504 "       if (color.a < 0.5)\n"
1505 "               discard;\n"
1506 "#endif\n"
1507 "       color.a *= Alpha;\n"
1508 "#ifdef USECOLORMAPPING\n"
1509 "       color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1510 "#endif\n"
1511 "#ifdef USEVERTEXTEXTUREBLEND\n"
1512 "       myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1513 "       //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1514 "       //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1515 "       color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1516 "       color.a = 1.0;\n"
1517 "       //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1518 "#endif\n"
1519 "\n"
1520 "       // get the surface normal\n"
1521 "#ifdef USEVERTEXTEXTUREBLEND\n"
1522 "       myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1523 "#else\n"
1524 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1525 "#endif\n"
1526 "\n"
1527 "       // get the material colors\n"
1528 "       myhalf3 diffusetex = color.rgb;\n"
1529 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1530 "# ifdef USEVERTEXTEXTUREBLEND\n"
1531 "       myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1532 "# else\n"
1533 "       myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1534 "# endif\n"
1535 "#endif\n"
1536 "\n"
1537 "#ifdef USEREFLECTCUBE\n"
1538 "       vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1539 "       vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1540 "       vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1541 "       diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1542 "#endif\n"
1543 "\n"
1544 "\n"
1545 "\n"
1546 "\n"
1547 "#ifdef MODE_LIGHTSOURCE\n"
1548 "       // light source\n"
1549 "#ifdef USEDIFFUSE\n"
1550 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1551 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1552 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1553 "#ifdef USESPECULAR\n"
1554 "#ifdef USEEXACTSPECULARMATH\n"
1555 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1556 "#else\n"
1557 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1558 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1559 "#endif\n"
1560 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1561 "#endif\n"
1562 "#else\n"
1563 "       color.rgb = diffusetex * Color_Ambient;\n"
1564 "#endif\n"
1565 "       color.rgb *= LightColor;\n"
1566 "       color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1567 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1568 "       color.rgb *= ShadowMapCompare(CubeVector);\n"
1569 "#endif\n"
1570 "# ifdef USECUBEFILTER\n"
1571 "       color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1572 "# endif\n"
1573 "#endif // MODE_LIGHTSOURCE\n"
1574 "\n"
1575 "\n"
1576 "\n"
1577 "\n"
1578 "#ifdef MODE_LIGHTDIRECTION\n"
1579 "#define SHADING\n"
1580 "#ifdef USEDIFFUSE\n"
1581 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1582 "#endif\n"
1583 "#define lightcolor LightColor\n"
1584 "#endif // MODE_LIGHTDIRECTION\n"
1585 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1586 "#define SHADING\n"
1587 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1588 "       myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1589 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1590 "       // convert modelspace light vector to tangentspace\n"
1591 "       myhalf3 lightnormal;\n"
1592 "       lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1593 "       lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1594 "       lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1595 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1596 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1597 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1598 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1599 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1600 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1601 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1602 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1603 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1604 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1605 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1606 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1607 "#define SHADING\n"
1608 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1609 "       myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1610 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1611 "#endif\n"
1612 "\n"
1613 "\n"
1614 "\n"
1615 "\n"
1616 "#ifdef MODE_LIGHTMAP\n"
1617 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1618 "#endif // MODE_LIGHTMAP\n"
1619 "#ifdef MODE_VERTEXCOLOR\n"
1620 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1621 "#endif // MODE_VERTEXCOLOR\n"
1622 "#ifdef MODE_FLATCOLOR\n"
1623 "       color.rgb = diffusetex * Color_Ambient;\n"
1624 "#endif // MODE_FLATCOLOR\n"
1625 "\n"
1626 "\n"
1627 "\n"
1628 "\n"
1629 "#ifdef SHADING\n"
1630 "# ifdef USEDIFFUSE\n"
1631 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1632 "#  ifdef USESPECULAR\n"
1633 "#   ifdef USEEXACTSPECULARMATH\n"
1634 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1635 "#   else\n"
1636 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1637 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1638 "#   endif\n"
1639 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1640 "#  else\n"
1641 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1642 "#  endif\n"
1643 "# else\n"
1644 "       color.rgb = diffusetex * Color_Ambient;\n"
1645 "# endif\n"
1646 "#endif\n"
1647 "\n"
1648 "#ifdef USEDEFERREDLIGHTMAP\n"
1649 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1650 "       color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1651 "       color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1652 "#endif\n"
1653 "\n"
1654 "#ifdef USEGLOW\n"
1655 "#ifdef USEVERTEXTEXTUREBLEND\n"
1656 "       color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1657 "#else\n"
1658 "       color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1659 "#endif\n"
1660 "#endif\n"
1661 "\n"
1662 "#ifdef USEFOG\n"
1663 "#ifdef MODE_LIGHTSOURCE\n"
1664 "       color.rgb *= myhalf(FogVertex());\n"
1665 "#else\n"
1666 "       color.rgb = mix(FogColor, color.rgb, FogVertex());\n"
1667 "#endif\n"
1668 "#endif\n"
1669 "\n"
1670 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
1671 "#ifdef USEREFLECTION\n"
1672 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1673 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1674 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1675 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1676 "       // FIXME temporary hack to detect the case that the reflection\n"
1677 "       // gets blackened at edges due to leaving the area that contains actual\n"
1678 "       // content.\n"
1679 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1680 "       // 'appening.\n"
1681 "       float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1682 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1683 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1684 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1685 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1686 "       color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1687 "#endif\n"
1688 "\n"
1689 "       gl_FragColor = vec4(color);\n"
1690 "}\n"
1691 "#endif // FRAGMENT_SHADER\n"
1692 "\n"
1693 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1694 "#endif // !MODE_DEFERREDGEOMETRY\n"
1695 "#endif // !MODE_WATER\n"
1696 "#endif // !MODE_REFRACTION\n"
1697 "#endif // !MODE_BLOOMBLUR\n"
1698 "#endif // !MODE_GENERIC\n"
1699 "#endif // !MODE_POSTPROCESS\n"
1700 "#endif // !MODE_SHOWDEPTH\n"
1701 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1702 ;
1703
1704 /*
1705 =========================================================================================================================================================
1706
1707
1708
1709 =========================================================================================================================================================
1710
1711
1712
1713 =========================================================================================================================================================
1714
1715
1716
1717 =========================================================================================================================================================
1718
1719
1720
1721 =========================================================================================================================================================
1722
1723
1724
1725 =========================================================================================================================================================
1726
1727
1728
1729 =========================================================================================================================================================
1730 */
1731
1732 const char *builtincgshaderstring =
1733 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1734 "// written by Forest 'LordHavoc' Hale\n"
1735 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1736 "\n"
1737 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE)\n"
1738 "# define USEFOG\n"
1739 "#endif\n"
1740 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1741 "#define USELIGHTMAP\n"
1742 "#endif\n"
1743 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
1744 "#define USEEYEVECTOR\n"
1745 "#endif\n"
1746 "\n"
1747 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1748 "#ifdef VERTEX_SHADER\n"
1749 "void main\n"
1750 "(\n"
1751 "float4 gl_Vertex : POSITION,\n"
1752 "uniform float4x4 ModelViewProjectionMatrix,\n"
1753 "out float4 gl_Position : POSITION\n"
1754 ")\n"
1755 "{\n"
1756 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1757 "}\n"
1758 "#endif\n"
1759 "#else // !MODE_DEPTH_ORSHADOW\n"
1760 "\n"
1761 "\n"
1762 "\n"
1763 "\n"
1764 "#ifdef MODE_SHOWDEPTH\n"
1765 "#ifdef VERTEX_SHADER\n"
1766 "void main\n"
1767 "(\n"
1768 "float4 gl_Vertex : POSITION,\n"
1769 "uniform float4x4 ModelViewProjectionMatrix,\n"
1770 "out float4 gl_Position : POSITION,\n"
1771 "out float4 gl_FrontColor : COLOR0\n"
1772 ")\n"
1773 "{\n"
1774 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1775 "       gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1776 "}\n"
1777 "#endif\n"
1778 "\n"
1779 "#ifdef FRAGMENT_SHADER\n"
1780 "void main\n"
1781 "(\n"
1782 "float4 gl_FrontColor : COLOR0,\n"
1783 "out float4 gl_FragColor : COLOR\n"
1784 ")\n"
1785 "{\n"
1786 "       gl_FragColor = gl_FrontColor;\n"
1787 "}\n"
1788 "#endif\n"
1789 "#else // !MODE_SHOWDEPTH\n"
1790 "\n"
1791 "\n"
1792 "\n"
1793 "\n"
1794 "#ifdef MODE_POSTPROCESS\n"
1795 "\n"
1796 "#ifdef VERTEX_SHADER\n"
1797 "void main\n"
1798 "(\n"
1799 "float4 gl_Vertex : POSITION,\n"
1800 "uniform float4x4 ModelViewProjectionMatrix,\n"
1801 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1802 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
1803 "out float4 gl_Position : POSITION,\n"
1804 "out float2 TexCoord1 : TEXCOORD0,\n"
1805 "out float2 TexCoord2 : TEXCOORD1\n"
1806 ")\n"
1807 "{\n"
1808 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1809 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
1810 "#ifdef USEBLOOM\n"
1811 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
1812 "#endif\n"
1813 "}\n"
1814 "#endif\n"
1815 "\n"
1816 "#ifdef FRAGMENT_SHADER\n"
1817 "void main\n"
1818 "(\n"
1819 "float2 TexCoord1 : TEXCOORD0,\n"
1820 "float2 TexCoord2 : TEXCOORD1,\n"
1821 "uniform sampler2D Texture_First,\n"
1822 "#ifdef USEBLOOM\n"
1823 "uniform sampler2D Texture_Second,\n"
1824 "#endif\n"
1825 "#ifdef USEGAMMARAMPS\n"
1826 "uniform sampler2D Texture_GammaRamps,\n"
1827 "#endif\n"
1828 "#ifdef USESATURATION\n"
1829 "uniform float Saturation,\n"
1830 "#endif\n"
1831 "#ifdef USEVIEWTINT\n"
1832 "uniform float4 ViewTintColor,\n"
1833 "#endif\n"
1834 "uniform float4 UserVec1,\n"
1835 "uniform float4 UserVec2,\n"
1836 "uniform float4 UserVec3,\n"
1837 "uniform float4 UserVec4,\n"
1838 "uniform float ClientTime,\n"
1839 "uniform float2 PixelSize,\n"
1840 "out float4 gl_FragColor : COLOR\n"
1841 ")\n"
1842 "{\n"
1843 "       gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
1844 "#ifdef USEBLOOM\n"
1845 "       gl_FragColor += tex2D(Texture_Second, TexCoord2);\n"
1846 "#endif\n"
1847 "#ifdef USEVIEWTINT\n"
1848 "       gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
1849 "#endif\n"
1850 "\n"
1851 "#ifdef USEPOSTPROCESSING\n"
1852 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
1853 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
1854 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
1855 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
1856 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
1857 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107,  0.707107)) * UserVec1.y;\n"
1858 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990,  0.891007)) * UserVec1.y;\n"
1859 "       gl_FragColor /= (1 + 5 * UserVec1.y);\n"
1860 "#endif\n"
1861 "\n"
1862 "#ifdef USESATURATION\n"
1863 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
1864 "       float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
1865 "       //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
1866 "       gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
1867 "#endif\n"
1868 "\n"
1869 "#ifdef USEGAMMARAMPS\n"
1870 "       gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
1871 "       gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
1872 "       gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
1873 "#endif\n"
1874 "}\n"
1875 "#endif\n"
1876 "#else // !MODE_POSTPROCESS\n"
1877 "\n"
1878 "\n"
1879 "\n"
1880 "\n"
1881 "#ifdef MODE_GENERIC\n"
1882 "#ifdef VERTEX_SHADER\n"
1883 "void main\n"
1884 "(\n"
1885 "float4 gl_Vertex : POSITION,\n"
1886 "uniform float4x4 ModelViewProjectionMatrix,\n"
1887 "float4 gl_Color : COLOR0,\n"
1888 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1889 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
1890 "out float4 gl_Position : POSITION,\n"
1891 "out float4 gl_FrontColor : COLOR,\n"
1892 "out float2 TexCoord1 : TEXCOORD0,\n"
1893 "out float2 TexCoord2 : TEXCOORD1\n"
1894 ")\n"
1895 "{\n"
1896 "       gl_FrontColor = gl_Color;\n"
1897 "#ifdef USEDIFFUSE\n"
1898 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
1899 "#endif\n"
1900 "#ifdef USESPECULAR\n"
1901 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
1902 "#endif\n"
1903 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1904 "}\n"
1905 "#endif\n"
1906 "\n"
1907 "#ifdef FRAGMENT_SHADER\n"
1908 "\n"
1909 "void main\n"
1910 "(\n"
1911 "float4 gl_FrontColor : COLOR,\n"
1912 "float2 TexCoord1 : TEXCOORD0,\n"
1913 "float2 TexCoord2 : TEXCOORD1,\n"
1914 "#ifdef USEDIFFUSE\n"
1915 "uniform sampler2D Texture_First,\n"
1916 "#endif\n"
1917 "#ifdef USESPECULAR\n"
1918 "uniform sampler2D Texture_Second,\n"
1919 "#endif\n"
1920 "out float4 gl_FragColor : COLOR\n"
1921 ")\n"
1922 "{\n"
1923 "       gl_FragColor = gl_FrontColor;\n"
1924 "#ifdef USEDIFFUSE\n"
1925 "       gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
1926 "#endif\n"
1927 "\n"
1928 "#ifdef USESPECULAR\n"
1929 "       float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
1930 "# ifdef USECOLORMAPPING\n"
1931 "       gl_FragColor *= tex2;\n"
1932 "# endif\n"
1933 "# ifdef USEGLOW\n"
1934 "       gl_FragColor += tex2;\n"
1935 "# endif\n"
1936 "# ifdef USEVERTEXTEXTUREBLEND\n"
1937 "       gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
1938 "# endif\n"
1939 "#endif\n"
1940 "}\n"
1941 "#endif\n"
1942 "#else // !MODE_GENERIC\n"
1943 "\n"
1944 "\n"
1945 "\n"
1946 "\n"
1947 "#ifdef MODE_BLOOMBLUR\n"
1948 "#ifdef VERTEX_SHADER\n"
1949 "void main\n"
1950 "(\n"
1951 "float4 gl_Vertex : POSITION,\n"
1952 "uniform float4x4 ModelViewProjectionMatrix,\n"
1953 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1954 "out float4 gl_Position : POSITION,\n"
1955 "out float2 TexCoord : TEXCOORD0\n"
1956 ")\n"
1957 "{\n"
1958 "       TexCoord = gl_MultiTexCoord0.xy;\n"
1959 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1960 "}\n"
1961 "#endif\n"
1962 "\n"
1963 "#ifdef FRAGMENT_SHADER\n"
1964 "\n"
1965 "void main\n"
1966 "(\n"
1967 "float2 TexCoord : TEXCOORD0,\n"
1968 "uniform sampler2D Texture_First,\n"
1969 "uniform float4 BloomBlur_Parameters,\n"
1970 "out float4 gl_FragColor : COLOR\n"
1971 ")\n"
1972 "{\n"
1973 "       int i;\n"
1974 "       float2 tc = TexCoord;\n"
1975 "       float3 color = tex2D(Texture_First, tc).rgb;\n"
1976 "       tc += BloomBlur_Parameters.xy;\n"
1977 "       for (i = 1;i < SAMPLES;i++)\n"
1978 "       {\n"
1979 "               color += tex2D(Texture_First, tc).rgb;\n"
1980 "               tc += BloomBlur_Parameters.xy;\n"
1981 "       }\n"
1982 "       gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
1983 "}\n"
1984 "#endif\n"
1985 "#else // !MODE_BLOOMBLUR\n"
1986 "#ifdef MODE_REFRACTION\n"
1987 "#ifdef VERTEX_SHADER\n"
1988 "void main\n"
1989 "(\n"
1990 "float4 gl_Vertex : POSITION,\n"
1991 "uniform float4x4 ModelViewProjectionMatrix,\n"
1992 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1993 "uniform float4x4 TexMatrix,\n"
1994 "uniform float3 EyePosition,\n"
1995 "out float4 gl_Position : POSITION,\n"
1996 "out float2 TexCoord : TEXCOORD0,\n"
1997 "out float3 EyeVector : TEXCOORD1,\n"
1998 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
1999 ")\n"
2000 "{\n"
2001 "       TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2002 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2003 "       ModelViewProjectionPosition = gl_Position;\n"
2004 "}\n"
2005 "#endif\n"
2006 "\n"
2007 "#ifdef FRAGMENT_SHADER\n"
2008 "void main\n"
2009 "(\n"
2010 "float2 TexCoord : TEXCOORD0,\n"
2011 "float3 EyeVector : TEXCOORD1,\n"
2012 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2013 "uniform sampler2D Texture_Normal,\n"
2014 "uniform sampler2D Texture_Refraction,\n"
2015 "uniform sampler2D Texture_Reflection,\n"
2016 "uniform float4 DistortScaleRefractReflect,\n"
2017 "uniform float4 ScreenScaleRefractReflect,\n"
2018 "uniform float4 ScreenCenterRefractReflect,\n"
2019 "uniform float4 RefractColor,\n"
2020 "out float4 gl_FragColor : COLOR\n"
2021 ")\n"
2022 "{\n"
2023 "       float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2024 "       //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2025 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2026 "       float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
2027 "       // FIXME temporary hack to detect the case that the reflection\n"
2028 "       // gets blackened at edges due to leaving the area that contains actual\n"
2029 "       // content.\n"
2030 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2031 "       // 'appening.\n"
2032 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2033 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2034 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2035 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2036 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2037 "       gl_FragColor = tex2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
2038 "}\n"
2039 "#endif\n"
2040 "#else // !MODE_REFRACTION\n"
2041 "\n"
2042 "\n"
2043 "\n"
2044 "\n"
2045 "#ifdef MODE_WATER\n"
2046 "#ifdef VERTEX_SHADER\n"
2047 "\n"
2048 "void main\n"
2049 "(\n"
2050 "float4 gl_Vertex : POSITION,\n"
2051 "uniform float4x4 ModelViewProjectionMatrix,\n"
2052 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2053 "uniform float4x4 TexMatrix,\n"
2054 "uniform float3 EyePosition,\n"
2055 "out float4 gl_Position : POSITION,\n"
2056 "out float2 TexCoord : TEXCOORD0,\n"
2057 "out float3 EyeVector : TEXCOORD1,\n"
2058 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2059 ")\n"
2060 "{\n"
2061 "       TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2062 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2063 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2064 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2065 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2066 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2067 "       ModelViewProjectionPosition = gl_Position;\n"
2068 "}\n"
2069 "#endif\n"
2070 "\n"
2071 "#ifdef FRAGMENT_SHADER\n"
2072 "void main\n"
2073 "(\n"
2074 "float2 TexCoord : TEXCOORD0,\n"
2075 "float3 EyeVector : TEXCOORD1,\n"
2076 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2077 "uniform sampler2D Texture_Normal,\n"
2078 "uniform sampler2D Texture_Refraction,\n"
2079 "uniform sampler2D Texture_Reflection,\n"
2080 "uniform float4 DistortScaleRefractReflect,\n"
2081 "uniform float4 ScreenScaleRefractReflect,\n"
2082 "uniform float4 ScreenCenterRefractReflect,\n"
2083 "uniform float4 RefractColor,\n"
2084 "uniform float4 ReflectColor,\n"
2085 "uniform float ReflectFactor,\n"
2086 "uniform float ReflectOffset,\n"
2087 "out float4 gl_FragColor : COLOR\n"
2088 ")\n"
2089 "{\n"
2090 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2091 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2092 "       float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2093 "       float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xyxy * DistortScaleRefractReflect;\n"
2094 "       // FIXME temporary hack to detect the case that the reflection\n"
2095 "       // gets blackened at edges due to leaving the area that contains actual\n"
2096 "       // content.\n"
2097 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2098 "       // 'appening.\n"
2099 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2100 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2101 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2102 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2103 "       ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2104 "       f       = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2105 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2106 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2107 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2108 "       ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2109 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2110 "       gl_FragColor = lerp(tex2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, tex2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
2111 "}\n"
2112 "#endif\n"
2113 "#else // !MODE_WATER\n"
2114 "\n"
2115 "\n"
2116 "\n"
2117 "\n"
2118 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
2119 "\n"
2120 "// fragment shader specific:\n"
2121 "#ifdef FRAGMENT_SHADER\n"
2122 "\n"
2123 "#ifdef USEFOG\n"
2124 "float FogVertex(float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler2D Texture_FogMask)\n"
2125 "{\n"
2126 "       float fogfrac;\n"
2127 "#ifdef USEFOGOUTSIDE\n"
2128 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2129 "#else\n"
2130 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2131 "#endif\n"
2132 "       return float(tex2D(Texture_FogMask, half2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)));\n"
2133 "}\n"
2134 "#endif\n"
2135 "\n"
2136 "#ifdef USEOFFSETMAPPING\n"
2137 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler2D Texture_Normal)\n"
2138 "{\n"
2139 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2140 "       // 14 sample relief mapping: linear search and then binary search\n"
2141 "       // this basically steps forward a small amount repeatedly until it finds\n"
2142 "       // itself inside solid, then jitters forward and back using decreasing\n"
2143 "       // amounts to find the impact\n"
2144 "       //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2145 "       //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2146 "       float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2147 "       float3 RT = float3(TexCoord, 1);\n"
2148 "       OffsetVector *= 0.1;\n"
2149 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2150 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2151 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2152 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2153 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2154 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2155 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2156 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2157 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2158 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
2159 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
2160 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
2161 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
2162 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2163 "       return RT.xy;\n"
2164 "#else\n"
2165 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2166 "       // this basically moves forward the full distance, and then backs up based\n"
2167 "       // on height of samples\n"
2168 "       //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2169 "       //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2170 "       float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2171 "       TexCoord += OffsetVector;\n"
2172 "       OffsetVector *= 0.333;\n"
2173 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2174 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2175 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2176 "       return TexCoord;\n"
2177 "#endif\n"
2178 "}\n"
2179 "#endif // USEOFFSETMAPPING\n"
2180 "\n"
2181 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
2182 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2183 "# ifndef USESHADOWMAPVSDCT\n"
2184 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2185 "{\n"
2186 "       float3 adir = abs(dir);\n"
2187 "       float2 tc;\n"
2188 "       float2 offset;\n"
2189 "       float ma;\n"
2190 "       if (adir.x > adir.y)\n"
2191 "       {\n"
2192 "               if (adir.x > adir.z) // X\n"
2193 "               {\n"
2194 "                       ma = adir.x;\n"
2195 "                       tc = dir.zy;\n"
2196 "                       offset = float2(lerp(0.5, 1.5, dir.x < 0.0), 0.5);\n"
2197 "               }\n"
2198 "               else // Z\n"
2199 "               {\n"
2200 "                       ma = adir.z;\n"
2201 "                       tc = dir.xy;\n"
2202 "                       offset = float2(lerp(0.5, 1.5, dir.z < 0.0), 2.5);\n"
2203 "               }\n"
2204 "       }\n"
2205 "       else\n"
2206 "       {\n"
2207 "               if (adir.y > adir.z) // Y\n"
2208 "               {\n"
2209 "                       ma = adir.y;\n"
2210 "                       tc = dir.xz;\n"
2211 "                       offset = float2(lerp(0.5, 1.5, dir.y < 0.0), 1.5);\n"
2212 "               }\n"
2213 "               else // Z\n"
2214 "               {\n"
2215 "                       ma = adir.z;\n"
2216 "                       tc = dir.xy;\n"
2217 "                       offset = float2(lerp(0.5, 1.5, dir.z < 0.0), 2.5);\n"
2218 "               }\n"
2219 "       }\n"
2220 "\n"
2221 "       float3 stc = float3(tc * ShadowMap_Parameters.x, ShadowMap_Parameters.w) / ma;\n"
2222 "       stc.xy += offset * ShadowMap_Parameters.y;\n"
2223 "       stc.z += ShadowMap_Parameters.z;\n"
2224 "       return stc;\n"
2225 "}\n"
2226 "# else\n"
2227 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2228 "{\n"
2229 "       float3 adir = abs(dir);\n"
2230 "       float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2231 "       float ma = max(max(adir.x, adir.y), adir.z);\n"
2232 "       float3 stc = float3(lerp(dir.xy, dir.zz, proj.xy) * ShadowMap_Parameters.x, ShadowMap_Parameters.w) / ma;\n"
2233 "       stc.xy += proj.zw * ShadowMap_Parameters.y;\n"
2234 "       stc.z += ShadowMap_Parameters.z;\n"
2235 "       return stc;\n"
2236 "}\n"
2237 "# endif\n"
2238 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2239 "\n"
2240 "#ifdef USESHADOWMAPCUBE\n"
2241 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2242 "{\n"
2243 "    float3 adir = abs(dir);\n"
2244 "    return float4(dir, ShadowMap_Parameters.z + ShadowMap_Parameters.w / max(max(adir.x, adir.y), adir.z));\n"
2245 "}\n"
2246 "#endif\n"
2247 "\n"
2248 "# ifdef USESHADOWMAPRECT\n"
2249 "#ifdef USESHADOWMAPVSDCT\n"
2250 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2251 "#else\n"
2252 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2253 "#endif\n"
2254 "{\n"
2255 "#ifdef USESHADOWMAPVSDCT\n"
2256 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2257 "#else\n"
2258 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2259 "#endif\n"
2260 "       float f;\n"
2261 "#  ifdef USESHADOWSAMPLER\n"
2262 "\n"
2263 "#    ifdef USESHADOWMAPPCF\n"
2264 "#      define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2265 "    f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2266 "#    else\n"
2267 "    f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2268 "#    endif\n"
2269 "\n"
2270 "#  else\n"
2271 "\n"
2272 "#    ifdef USESHADOWMAPPCF\n"
2273 "#      if USESHADOWMAPPCF > 1\n"
2274 "#        define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2275 "    float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2276 "    float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2277 "    float4 row2 = step(shadowmaptc.z, float4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
2278 "    float4 row3 = step(shadowmaptc.z, float4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
2279 "    float4 row4 = step(shadowmaptc.z, float4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
2280 "    float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2281 "    f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2282 "#      else\n"
2283 "#        define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2284 "    float2 offset = frac(shadowmaptc.xy);\n"
2285 "    float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2286 "    float3 row2 = step(shadowmaptc.z, float3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
2287 "    float3 row3 = step(shadowmaptc.z, float3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
2288 "    float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2289 "    f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2290 "#      endif\n"
2291 "#    else\n"
2292 "    f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2293 "#    endif\n"
2294 "\n"
2295 "#  endif\n"
2296 "       return f;\n"
2297 "}\n"
2298 "# endif\n"
2299 "\n"
2300 "# ifdef USESHADOWMAP2D\n"
2301 "#ifdef USESHADOWMAPVSDCT\n"
2302 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2303 "#else\n"
2304 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2305 "#endif\n"
2306 "{\n"
2307 "#ifdef USESHADOWMAPVSDCT\n"
2308 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2309 "#else\n"
2310 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2311 "#endif\n"
2312 "    float f;\n"
2313 "\n"
2314 "#  ifdef USESHADOWSAMPLER\n"
2315 "#    ifdef USESHADOWMAPPCF\n"
2316 "#      define texval(x, y) shadow2D(Texture_ShadowMap2D, float3(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r  \n"
2317 "    float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2318 "    f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2319 "#    else\n"
2320 "    f = shadow2D(Texture_ShadowMap2D, float3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
2321 "#    endif\n"
2322 "#  else\n"
2323 "#    ifdef USESHADOWMAPPCF\n"
2324 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2325 "#      ifdef GL_ARB_texture_gather\n"
2326 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
2327 "#      else\n"
2328 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x,y)*ShadowMap_TextureScale)\n"
2329 "#      endif\n"
2330 "    float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2331 "    center *= ShadowMap_TextureScale;\n"
2332 "    float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2333 "    float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2334 "    float4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
2335 "    float4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
2336 "    float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2337 "                lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2338 "    f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2339 "#     else\n"
2340 "#        define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale)  \n"
2341 "#      if USESHADOWMAPPCF > 1\n"
2342 "    float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2343 "    center *= ShadowMap_TextureScale;\n"
2344 "    float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2345 "    float4 row2 = step(shadowmaptc.z, float4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
2346 "    float4 row3 = step(shadowmaptc.z, float4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
2347 "    float4 row4 = step(shadowmaptc.z, float4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
2348 "    float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2349 "    f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2350 "#      else\n"
2351 "    float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2352 "    float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2353 "    float3 row2 = step(shadowmaptc.z, float3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
2354 "    float3 row3 = step(shadowmaptc.z, float3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
2355 "    float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2356 "    f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2357 "#      endif\n"
2358 "#     endif\n"
2359 "#    else\n"
2360 "    f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2361 "#    endif\n"
2362 "#  endif\n"
2363 "    return f;\n"
2364 "}\n"
2365 "# endif\n"
2366 "\n"
2367 "# ifdef USESHADOWMAPCUBE\n"
2368 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2369 "{\n"
2370 "    // apply depth texture cubemap as light filter\n"
2371 "    float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2372 "    float f;\n"
2373 "#  ifdef USESHADOWSAMPLER\n"
2374 "    f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2375 "#  else\n"
2376 "    f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2377 "#  endif\n"
2378 "    return f;\n"
2379 "}\n"
2380 "# endif\n"
2381 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2382 "#endif // FRAGMENT_SHADER\n"
2383 "\n"
2384 "\n"
2385 "\n"
2386 "\n"
2387 "#ifdef MODE_DEFERREDGEOMETRY\n"
2388 "#ifdef VERTEX_SHADER\n"
2389 "void main\n"
2390 "(\n"
2391 "float4 gl_Vertex : POSITION,\n"
2392 "uniform float4x4 ModelViewProjectionMatrix,\n"
2393 "#ifdef USEVERTEXTEXTUREBLEND\n"
2394 "float4 gl_Color : COLOR0,\n"
2395 "#endif\n"
2396 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2397 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2398 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2399 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2400 "uniform float4x4 TexMatrix,\n"
2401 "#ifdef USEVERTEXTEXTUREBLEND\n"
2402 "uniform float4x4 BackgroundTexMatrix,\n"
2403 "#endif\n"
2404 "uniform float4x4 ModelViewMatrix,\n"
2405 "#ifdef USEOFFSETMAPPING\n"
2406 "uniform float3 EyePosition,\n"
2407 "#endif\n"
2408 "out float4 gl_Position : POSITION,\n"
2409 "out float4 gl_FrontColor : COLOR,\n"
2410 "out float4 TexCoordBoth : TEXCOORD0,\n"
2411 "#ifdef USEOFFSETMAPPING\n"
2412 "out float3 EyeVector : TEXCOORD2,\n"
2413 "#endif\n"
2414 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2415 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2416 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2417 ")\n"
2418 "{\n"
2419 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2420 "#ifdef USEVERTEXTEXTUREBLEND\n"
2421 "       gl_FrontColor = gl_Color;\n"
2422 "       TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2423 "#endif\n"
2424 "\n"
2425 "       // transform unnormalized eye direction into tangent space\n"
2426 "#ifdef USEOFFSETMAPPING\n"
2427 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2428 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2429 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2430 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2431 "#endif\n"
2432 "\n"
2433 "       VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2434 "       VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2435 "       VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2436 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2437 "}\n"
2438 "#endif // VERTEX_SHADER\n"
2439 "\n"
2440 "#ifdef FRAGMENT_SHADER\n"
2441 "void main\n"
2442 "(\n"
2443 "float4 TexCoordBoth : TEXCOORD0,\n"
2444 "float3 EyeVector : TEXCOORD2,\n"
2445 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2446 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2447 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2448 "uniform sampler2D Texture_Normal,\n"
2449 "#ifdef USEALPHAKILL\n"
2450 "uniform sampler2D Texture_Color,\n"
2451 "#endif\n"
2452 "uniform sampler2D Texture_Gloss,\n"
2453 "#ifdef USEVERTEXTEXTUREBLEND\n"
2454 "uniform sampler2D Texture_SecondaryNormal,\n"
2455 "uniform sampler2D Texture_SecondaryGloss,\n"
2456 "#endif\n"
2457 "#ifdef USEOFFSETMAPPING\n"
2458 "uniform float OffsetMapping_Scale,\n"
2459 "#endif\n"
2460 "uniform half SpecularPower,\n"
2461 "out float4 gl_FragColor : COLOR\n"
2462 ")\n"
2463 "{\n"
2464 "       float2 TexCoord = TexCoordBoth.xy;\n"
2465 "#ifdef USEOFFSETMAPPING\n"
2466 "       // apply offsetmapping\n"
2467 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2468 "#define TexCoord TexCoordOffset\n"
2469 "#endif\n"
2470 "\n"
2471 "#ifdef USEALPHAKILL\n"
2472 "       if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2473 "               discard;\n"
2474 "#endif\n"
2475 "\n"
2476 "#ifdef USEVERTEXTEXTUREBLEND\n"
2477 "       float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2478 "       float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2479 "       //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2480 "       //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2481 "#endif\n"
2482 "\n"
2483 "#ifdef USEVERTEXTEXTUREBLEND\n"
2484 "       float3 surfacenormal = lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend) - float3(0.5, 0.5, 0.5);\n"
2485 "       float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2486 "#else\n"
2487 "       float3 surfacenormal = float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5, 0.5, 0.5);\n"
2488 "       float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2489 "#endif\n"
2490 "\n"
2491 "       gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), 1);\n"
2492 "}\n"
2493 "#endif // FRAGMENT_SHADER\n"
2494 "#else // !MODE_DEFERREDGEOMETRY\n"
2495 "\n"
2496 "\n"
2497 "\n"
2498 "\n"
2499 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2500 "#ifdef VERTEX_SHADER\n"
2501 "void main\n"
2502 "(\n"
2503 "float4 gl_Vertex : POSITION,\n"
2504 "uniform float4x4 ModelViewProjectionMatrix,\n"
2505 "uniform float4x4 ModelViewMatrix,\n"
2506 "out float4 gl_Position : POSITION,\n"
2507 "out float4 ModelViewPosition : TEXCOORD0\n"
2508 ")\n"
2509 "{\n"
2510 "       ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2511 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2512 "}\n"
2513 "#endif // VERTEX_SHADER\n"
2514 "\n"
2515 "#ifdef FRAGMENT_SHADER\n"
2516 "void main\n"
2517 "(\n"
2518 "float2 Pixel : WPOS,\n"
2519 "float4 ModelViewPosition : TEXCOORD0,\n"
2520 "uniform float4x4 ViewToLight,\n"
2521 "uniform float2 ScreenToDepth, // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2522 "uniform float3 LightPosition,\n"
2523 "uniform half2 PixelToScreenTexCoord,\n"
2524 "uniform half3 DeferredColor_Ambient,\n"
2525 "uniform half3 DeferredColor_Diffuse,\n"
2526 "#ifdef USESPECULAR\n"
2527 "uniform half3 DeferredColor_Specular,\n"
2528 "uniform half SpecularPower,\n"
2529 "#endif\n"
2530 "uniform sampler2D Texture_Attenuation,\n"
2531 "uniform sampler2D Texture_ScreenDepth,\n"
2532 "uniform sampler2D Texture_ScreenNormalMap,\n"
2533 "\n"
2534 "#ifdef USESHADOWMAPRECT\n"
2535 "# ifdef USESHADOWSAMPLER\n"
2536 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2537 "# else\n"
2538 "uniform samplerRECT Texture_ShadowMapRect,\n"
2539 "# endif\n"
2540 "#endif\n"
2541 "\n"
2542 "#ifdef USESHADOWMAP2D\n"
2543 "# ifdef USESHADOWSAMPLER\n"
2544 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2545 "# else\n"
2546 "uniform sampler2D Texture_ShadowMap2D,\n"
2547 "# endif\n"
2548 "#endif\n"
2549 "\n"
2550 "#ifdef USESHADOWMAPVSDCT\n"
2551 "uniform samplerCUBE Texture_CubeProjection,\n"
2552 "#endif\n"
2553 "\n"
2554 "#ifdef USESHADOWMAPCUBE\n"
2555 "# ifdef USESHADOWSAMPLER\n"
2556 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2557 "# else\n"
2558 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2559 "# endif\n"
2560 "#endif\n"
2561 "\n"
2562 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2563 "uniform float2 ShadowMap_TextureScale,\n"
2564 "uniform float4 ShadowMap_Parameters,\n"
2565 "#endif\n"
2566 "\n"
2567 "out float4 gl_FragData0 : COLOR0,\n"
2568 "out float4 gl_FragData1 : COLOR1\n"
2569 ")\n"
2570 "{\n"
2571 "       // calculate viewspace pixel position\n"
2572 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2573 "       ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2574 "       float3 position;\n"
2575 "       position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2576 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2577 "       // decode viewspace pixel normal\n"
2578 "       half4 normalmap = tex2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
2579 "       half3 surfacenormal = normalize(normalmap.rgb - half3(0.5,0.5,0.5));\n"
2580 "       // surfacenormal = pixel normal in viewspace\n"
2581 "       // LightVector = pixel to light in viewspace\n"
2582 "       // CubeVector = position in lightspace\n"
2583 "       // eyevector = pixel to view in viewspace\n"
2584 "       float3 CubeVector = float3(mul(ViewToLight, float4(position,1)));\n"
2585 "       half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
2586 "#ifdef USEDIFFUSE\n"
2587 "       // calculate diffuse shading\n"
2588 "       half3 lightnormal = half3(normalize(LightPosition - position));\n"
2589 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2590 "#endif\n"
2591 "#ifdef USESPECULAR\n"
2592 "       // calculate directional shading\n"
2593 "       float3 eyevector = position * -1.0;\n"
2594 "#  ifdef USEEXACTSPECULARMATH\n"
2595 "       half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2596 "#  else\n"
2597 "       half3 specularnormal = normalize(lightnormal + half3(normalize(eyevector)));\n"
2598 "       half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2599 "#  endif\n"
2600 "#endif\n"
2601 "\n"
2602 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2603 "       fade *= ShadowMapCompare(CubeVector,\n"
2604 "# if defined(USESHADOWMAP2D)\n"
2605 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2606 "# endif\n"
2607 "# if defined(USESHADOWMAPRECT)\n"
2608 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2609 "# endif\n"
2610 "# if defined(USESHADOWMAPCUBE)\n"
2611 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2612 "# endif\n"
2613 "\n"
2614 "#ifdef USESHADOWMAPVSDCT\n"
2615 ", Texture_CubeProjection\n"
2616 "#endif\n"
2617 "       );\n"
2618 "#endif\n"
2619 "\n"
2620 "#ifdef USEDIFFUSE\n"
2621 "       gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2622 "#else\n"
2623 "       gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2624 "#endif\n"
2625 "#ifdef USESPECULAR\n"
2626 "       gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2627 "#else\n"
2628 "       gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2629 "#endif\n"
2630 "\n"
2631 "# ifdef USECUBEFILTER\n"
2632 "       float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2633 "       gl_FragData0.rgb *= cubecolor;\n"
2634 "       gl_FragData1.rgb *= cubecolor;\n"
2635 "# endif\n"
2636 "}\n"
2637 "#endif // FRAGMENT_SHADER\n"
2638 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2639 "\n"
2640 "\n"
2641 "\n"
2642 "\n"
2643 "#ifdef VERTEX_SHADER\n"
2644 "void main\n"
2645 "(\n"
2646 "float4 gl_Vertex : POSITION,\n"
2647 "uniform float4x4 ModelViewProjectionMatrix,\n"
2648 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2649 "float4 gl_Color : COLOR0,\n"
2650 "#endif\n"
2651 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2652 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2653 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2654 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2655 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2656 "\n"
2657 "uniform float3 EyePosition,\n"
2658 "uniform float4x4 TexMatrix,\n"
2659 "#ifdef USEVERTEXTEXTUREBLEND\n"
2660 "uniform float4x4 BackgroundTexMatrix,\n"
2661 "#endif\n"
2662 "#ifdef MODE_LIGHTSOURCE\n"
2663 "uniform float4x4 ModelToLight,\n"
2664 "#endif\n"
2665 "#ifdef MODE_LIGHTSOURCE\n"
2666 "uniform float3 LightPosition,\n"
2667 "#endif\n"
2668 "#ifdef MODE_LIGHTDIRECTION\n"
2669 "uniform float3 LightDir,\n"
2670 "#endif\n"
2671 "uniform float4 FogPlane,\n"
2672 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2673 "uniform float3 LightPosition,\n"
2674 "#endif\n"
2675 "\n"
2676 "out float4 gl_FrontColor : COLOR,\n"
2677 "out float4 TexCoordBoth : TEXCOORD0,\n"
2678 "#ifdef USELIGHTMAP\n"
2679 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2680 "#endif\n"
2681 "#ifdef USEEYEVECTOR\n"
2682 "out float3 EyeVector : TEXCOORD2,\n"
2683 "#endif\n"
2684 "#ifdef USEREFLECTION\n"
2685 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2686 "#endif\n"
2687 "#ifdef USEFOG\n"
2688 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2689 "#endif\n"
2690 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2691 "out float3 LightVector : TEXCOORD5,\n"
2692 "#endif\n"
2693 "#ifdef MODE_LIGHTSOURCE\n"
2694 "out float3 CubeVector : TEXCOORD3,\n"
2695 "#endif\n"
2696 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2697 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2698 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2699 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2700 "#endif\n"
2701 "out float4 gl_Position : POSITION\n"
2702 ")\n"
2703 "{\n"
2704 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2705 "       gl_FrontColor = gl_Color;\n"
2706 "#endif\n"
2707 "       // copy the surface texcoord\n"
2708 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2709 "#ifdef USEVERTEXTEXTUREBLEND\n"
2710 "       TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2711 "#endif\n"
2712 "#ifdef USELIGHTMAP\n"
2713 "       TexCoordLightmap = float2(gl_MultiTexCoord4);\n"
2714 "#endif\n"
2715 "\n"
2716 "#ifdef MODE_LIGHTSOURCE\n"
2717 "       // transform vertex position into light attenuation/cubemap space\n"
2718 "       // (-1 to +1 across the light box)\n"
2719 "       CubeVector = float3(mul(ModelToLight, gl_Vertex));\n"
2720 "\n"
2721 "# ifdef USEDIFFUSE\n"
2722 "       // transform unnormalized light direction into tangent space\n"
2723 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
2724 "       //  normalize it per pixel)\n"
2725 "       float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2726 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2727 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2728 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2729 "# endif\n"
2730 "#endif\n"
2731 "\n"
2732 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2733 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2734 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2735 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2736 "#endif\n"
2737 "\n"
2738 "       // transform unnormalized eye direction into tangent space\n"
2739 "#ifdef USEEYEVECTOR\n"
2740 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2741 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2742 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2743 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2744 "#endif\n"
2745 "\n"
2746 "#ifdef USEFOG\n"
2747 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2748 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2749 "#endif\n"
2750 "\n"
2751 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2752 "       VectorS = gl_MultiTexCoord1.xyz;\n"
2753 "       VectorT = gl_MultiTexCoord2.xyz;\n"
2754 "       VectorR = gl_MultiTexCoord3.xyz;\n"
2755 "#endif\n"
2756 "\n"
2757 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2758 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2759 "\n"
2760 "#ifdef USEREFLECTION\n"
2761 "       ModelViewProjectionPosition = gl_Position;\n"
2762 "#endif\n"
2763 "}\n"
2764 "#endif // VERTEX_SHADER\n"
2765 "\n"
2766 "\n"
2767 "\n"
2768 "\n"
2769 "#ifdef FRAGMENT_SHADER\n"
2770 "void main\n"
2771 "(\n"
2772 "#ifdef USEDEFERREDLIGHTMAP\n"
2773 "float2 Pixel : WPOS,\n"
2774 "#endif\n"
2775 "float4 gl_FrontColor : COLOR,\n"
2776 "float4 TexCoordBoth : TEXCOORD0,\n"
2777 "#ifdef USELIGHTMAP\n"
2778 "float2 TexCoordLightmap : TEXCOORD1,\n"
2779 "#endif\n"
2780 "#ifdef USEEYEVECTOR\n"
2781 "float3 EyeVector : TEXCOORD2,\n"
2782 "#endif\n"
2783 "#ifdef USEREFLECTION\n"
2784 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2785 "#endif\n"
2786 "#ifdef USEFOG\n"
2787 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2788 "#endif\n"
2789 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2790 "float3 LightVector : TEXCOORD5,\n"
2791 "#endif\n"
2792 "#ifdef MODE_LIGHTSOURCE\n"
2793 "float3 CubeVector : TEXCOORD3,\n"
2794 "#endif\n"
2795 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2796 "float4 ModelViewPosition : TEXCOORD0,\n"
2797 "#endif\n"
2798 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2799 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2800 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2801 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2802 "#endif\n"
2803 "\n"
2804 "uniform sampler2D Texture_Normal,\n"
2805 "uniform sampler2D Texture_Color,\n"
2806 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2807 "uniform sampler2D Texture_Gloss,\n"
2808 "#endif\n"
2809 "#ifdef USEGLOW\n"
2810 "uniform sampler2D Texture_Glow,\n"
2811 "#endif\n"
2812 "#ifdef USEVERTEXTEXTUREBLEND\n"
2813 "uniform sampler2D Texture_SecondaryNormal,\n"
2814 "uniform sampler2D Texture_SecondaryColor,\n"
2815 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2816 "uniform sampler2D Texture_SecondaryGloss,\n"
2817 "#endif\n"
2818 "#ifdef USEGLOW\n"
2819 "uniform sampler2D Texture_SecondaryGlow,\n"
2820 "#endif\n"
2821 "#endif\n"
2822 "#ifdef USECOLORMAPPING\n"
2823 "uniform sampler2D Texture_Pants,\n"
2824 "uniform sampler2D Texture_Shirt,\n"
2825 "#endif\n"
2826 "#ifdef USEFOG\n"
2827 "uniform sampler2D Texture_FogMask,\n"
2828 "#endif\n"
2829 "#ifdef USELIGHTMAP\n"
2830 "uniform sampler2D Texture_Lightmap,\n"
2831 "#endif\n"
2832 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2833 "uniform sampler2D Texture_Deluxemap,\n"
2834 "#endif\n"
2835 "#ifdef USEREFLECTION\n"
2836 "uniform sampler2D Texture_Reflection,\n"
2837 "#endif\n"
2838 "\n"
2839 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2840 "uniform sampler2D Texture_ScreenDepth,\n"
2841 "uniform sampler2D Texture_ScreenNormalMap,\n"
2842 "#endif\n"
2843 "#ifdef USEDEFERREDLIGHTMAP\n"
2844 "uniform sampler2D Texture_ScreenDiffuse,\n"
2845 "uniform sampler2D Texture_ScreenSpecular,\n"
2846 "#endif\n"
2847 "\n"
2848 "#ifdef USECOLORMAPPING\n"
2849 "uniform half3 Color_Pants,\n"
2850 "uniform half3 Color_Shirt,\n"
2851 "#endif\n"
2852 "#ifdef USEFOG\n"
2853 "uniform float3 FogColor,\n"
2854 "uniform float FogRangeRecip,\n"
2855 "uniform float FogPlaneViewDist,\n"
2856 "uniform float FogHeightFade,\n"
2857 "#endif\n"
2858 "\n"
2859 "#ifdef USEOFFSETMAPPING\n"
2860 "uniform float OffsetMapping_Scale,\n"
2861 "#endif\n"
2862 "\n"
2863 "#ifdef USEDEFERREDLIGHTMAP\n"
2864 "uniform half2 PixelToScreenTexCoord,\n"
2865 "uniform half3 DeferredMod_Diffuse,\n"
2866 "uniform half3 DeferredMod_Specular,\n"
2867 "#endif\n"
2868 "uniform half3 Color_Ambient,\n"
2869 "uniform half3 Color_Diffuse,\n"
2870 "uniform half3 Color_Specular,\n"
2871 "uniform half SpecularPower,\n"
2872 "#ifdef USEGLOW\n"
2873 "uniform half3 Color_Glow,\n"
2874 "#endif\n"
2875 "uniform half Alpha,\n"
2876 "#ifdef USEREFLECTION\n"
2877 "uniform float4 DistortScaleRefractReflect,\n"
2878 "uniform float4 ScreenScaleRefractReflect,\n"
2879 "uniform float4 ScreenCenterRefractReflect,\n"
2880 "uniform half4 ReflectColor,\n"
2881 "#endif\n"
2882 "#ifdef USEREFLECTCUBE\n"
2883 "uniform float4x4 ModelToReflectCube,\n"
2884 "uniform sampler2D Texture_ReflectMask,\n"
2885 "uniform samplerCUBE Texture_ReflectCube,\n"
2886 "#endif\n"
2887 "#ifdef MODE_LIGHTDIRECTION\n"
2888 "uniform half3 LightColor,\n"
2889 "#endif\n"
2890 "#ifdef MODE_LIGHTSOURCE\n"
2891 "uniform half3 LightColor,\n"
2892 "#endif\n"
2893 "\n"
2894 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
2895 "uniform sampler2D Texture_Attenuation,\n"
2896 "uniform samplerCUBE Texture_Cube,\n"
2897 "\n"
2898 "#ifdef USESHADOWMAPRECT\n"
2899 "# ifdef USESHADOWSAMPLER\n"
2900 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2901 "# else\n"
2902 "uniform samplerRECT Texture_ShadowMapRect,\n"
2903 "# endif\n"
2904 "#endif\n"
2905 "\n"
2906 "#ifdef USESHADOWMAP2D\n"
2907 "# ifdef USESHADOWSAMPLER\n"
2908 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2909 "# else\n"
2910 "uniform sampler2D Texture_ShadowMap2D,\n"
2911 "# endif\n"
2912 "#endif\n"
2913 "\n"
2914 "#ifdef USESHADOWMAPVSDCT\n"
2915 "uniform samplerCUBE Texture_CubeProjection,\n"
2916 "#endif\n"
2917 "\n"
2918 "#ifdef USESHADOWMAPCUBE\n"
2919 "# ifdef USESHADOWSAMPLER\n"
2920 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2921 "# else\n"
2922 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2923 "# endif\n"
2924 "#endif\n"
2925 "\n"
2926 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2927 "uniform float2 ShadowMap_TextureScale,\n"
2928 "uniform float4 ShadowMap_Parameters,\n"
2929 "#endif\n"
2930 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2931 "\n"
2932 "out float4 gl_FragColor : COLOR\n"
2933 ")\n"
2934 "{\n"
2935 "       float2 TexCoord = TexCoordBoth.xy;\n"
2936 "#ifdef USEVERTEXTEXTUREBLEND\n"
2937 "       float2 TexCoord2 = TexCoordBoth.zw;\n"
2938 "#endif\n"
2939 "#ifdef USEOFFSETMAPPING\n"
2940 "       // apply offsetmapping\n"
2941 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2942 "#define TexCoord TexCoordOffset\n"
2943 "#endif\n"
2944 "\n"
2945 "       // combine the diffuse textures (base, pants, shirt)\n"
2946 "       half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
2947 "#ifdef USEALPHAKILL\n"
2948 "       if (color.a < 0.5)\n"
2949 "               discard;\n"
2950 "#endif\n"
2951 "       color.a *= Alpha;\n"
2952 "#ifdef USECOLORMAPPING\n"
2953 "       color.rgb += half3(tex2D(Texture_Pants, TexCoord)) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
2954 "#endif\n"
2955 "#ifdef USEVERTEXTEXTUREBLEND\n"
2956 "       float terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
2957 "       //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
2958 "       //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
2959 "       color.rgb = half3(lerp(float3(tex2D(Texture_SecondaryColor, TexCoord2)), float3(color.rgb), terrainblend));\n"
2960 "       color.a = 1.0;\n"
2961 "       //color = lerp(half4(1, 0, 0, 1), color, terrainblend);\n"
2962 "#endif\n"
2963 "\n"
2964 "       // get the surface normal\n"
2965 "#ifdef USEVERTEXTEXTUREBLEND\n"
2966 "       half3 surfacenormal = normalize(half3(lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend)) - half3(0.5, 0.5, 0.5));\n"
2967 "#else\n"
2968 "       half3 surfacenormal = normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5, 0.5, 0.5));\n"
2969 "#endif\n"
2970 "\n"
2971 "       // get the material colors\n"
2972 "       half3 diffusetex = color.rgb;\n"
2973 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2974 "# ifdef USEVERTEXTEXTUREBLEND\n"
2975 "       half4 glosstex = half4(lerp(float4(tex2D(Texture_SecondaryGloss, TexCoord2)), float4(tex2D(Texture_Gloss, TexCoord)), terrainblend));\n"
2976 "# else\n"
2977 "       half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
2978 "# endif\n"
2979 "#endif\n"
2980 "\n"
2981 "#ifdef USEREFLECTCUBE\n"
2982 "       vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
2983 "       vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
2984 "       vec3 ReflectCubeTexCoord = float3(mul(ModelToReflectCube, float4(ModelReflectVector, 0)));\n"
2985 "       diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord)) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord));\n"
2986 "#endif\n"
2987 "\n"
2988 "\n"
2989 "\n"
2990 "\n"
2991 "#ifdef MODE_LIGHTSOURCE\n"
2992 "       // light source\n"
2993 "#ifdef USEDIFFUSE\n"
2994 "       half3 lightnormal = half3(normalize(LightVector));\n"
2995 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2996 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
2997 "#ifdef USESPECULAR\n"
2998 "#ifdef USEEXACTSPECULARMATH\n"
2999 "       half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3000 "#else\n"
3001 "       half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3002 "       half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3003 "#endif\n"
3004 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3005 "#endif\n"
3006 "#else\n"
3007 "       color.rgb = diffusetex * Color_Ambient;\n"
3008 "#endif\n"
3009 "       color.rgb *= LightColor;\n"
3010 "       color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
3011 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3012 "       color.rgb *= ShadowMapCompare(CubeVector,\n"
3013 "# if defined(USESHADOWMAP2D)\n"
3014 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3015 "# endif\n"
3016 "# if defined(USESHADOWMAPRECT)\n"
3017 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3018 "# endif\n"
3019 "# if defined(USESHADOWMAPCUBE)\n"
3020 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3021 "# endif\n"
3022 "\n"
3023 "#ifdef USESHADOWMAPVSDCT\n"
3024 ", Texture_CubeProjection\n"
3025 "#endif\n"
3026 "       );\n"
3027 "\n"
3028 "#endif\n"
3029 "# ifdef USECUBEFILTER\n"
3030 "       color.rgb *= half3(texCUBE(Texture_Cube, CubeVector));\n"
3031 "# endif\n"
3032 "#endif // MODE_LIGHTSOURCE\n"
3033 "\n"
3034 "\n"
3035 "\n"
3036 "\n"
3037 "#ifdef MODE_LIGHTDIRECTION\n"
3038 "#define SHADING\n"
3039 "#ifdef USEDIFFUSE\n"
3040 "       half3 lightnormal = half3(normalize(LightVector));\n"
3041 "#endif\n"
3042 "#define lightcolor LightColor\n"
3043 "#endif // MODE_LIGHTDIRECTION\n"
3044 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3045 "#define SHADING\n"
3046 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3047 "       half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3048 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3049 "       // convert modelspace light vector to tangentspace\n"
3050 "       half3 lightnormal;\n"
3051 "       lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3052 "       lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3053 "       lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3054 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3055 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3056 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3057 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3058 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3059 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3060 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3061 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3062 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3063 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3064 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3065 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3066 "#define SHADING\n"
3067 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3068 "       half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3069 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3070 "#endif\n"
3071 "\n"
3072 "\n"
3073 "\n"
3074 "\n"
3075 "#ifdef MODE_LIGHTMAP\n"
3076 "       color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
3077 "#endif // MODE_LIGHTMAP\n"
3078 "#ifdef MODE_VERTEXCOLOR\n"
3079 "       color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3080 "#endif // MODE_VERTEXCOLOR\n"
3081 "#ifdef MODE_FLATCOLOR\n"
3082 "       color.rgb = diffusetex * Color_Ambient;\n"
3083 "#endif // MODE_FLATCOLOR\n"
3084 "\n"
3085 "\n"
3086 "\n"
3087 "\n"
3088 "#ifdef SHADING\n"
3089 "# ifdef USEDIFFUSE\n"
3090 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3091 "#  ifdef USESPECULAR\n"
3092 "#   ifdef USEEXACTSPECULARMATH\n"
3093 "       half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3094 "#   else\n"
3095 "       half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3096 "       half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3097 "#   endif\n"
3098 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3099 "#  else\n"
3100 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3101 "#  endif\n"
3102 "# else\n"
3103 "       color.rgb = diffusetex * Color_Ambient;\n"
3104 "# endif\n"
3105 "#endif\n"
3106 "\n"
3107 "#ifdef USEDEFERREDLIGHTMAP\n"
3108 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3109 "       color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
3110 "       color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
3111 "#endif\n"
3112 "\n"
3113 "#ifdef USEGLOW\n"
3114 "#ifdef USEVERTEXTEXTUREBLEND\n"
3115 "       color.rgb += lerp(half3(tex2D(Texture_SecondaryGlow, TexCoord2)), half3(tex2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
3116 "#else\n"
3117 "       color.rgb += half3(tex2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
3118 "#endif\n"
3119 "#endif\n"
3120 "\n"
3121 "#ifdef USEFOG\n"
3122 "#ifdef MODE_LIGHTSOURCE\n"
3123 "       color.rgb *= half(FogVertex(EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask));\n"
3124 "#else\n"
3125 "       color.rgb = lerp(FogColor, float3(color.rgb), FogVertex(EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask));\n"
3126 "#endif\n"
3127 "#endif\n"
3128 "\n"
3129 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
3130 "#ifdef USEREFLECTION\n"
3131 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3132 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3133 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3134 "       float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
3135 "       // FIXME temporary hack to detect the case that the reflection\n"
3136 "       // gets blackened at edges due to leaving the area that contains actual\n"
3137 "       // content.\n"
3138 "       // Remove this 'ack once we have a better way to stop this thing from\n"
3139 "       // 'appening.\n"
3140 "       float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3141 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3142 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3143 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3144 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3145 "       color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
3146 "#endif\n"
3147 "\n"
3148 "       gl_FragColor = float4(color);\n"
3149 "}\n"
3150 "#endif // FRAGMENT_SHADER\n"
3151 "\n"
3152 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3153 "#endif // !MODE_DEFERREDGEOMETRY\n"
3154 "#endif // !MODE_WATER\n"
3155 "#endif // !MODE_REFRACTION\n"
3156 "#endif // !MODE_BLOOMBLUR\n"
3157 "#endif // !MODE_GENERIC\n"
3158 "#endif // !MODE_POSTPROCESS\n"
3159 "#endif // !MODE_SHOWDEPTH\n"
3160 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3161 ;
3162
3163 char *glslshaderstring = NULL;
3164 char *cgshaderstring = NULL;
3165
3166 //=======================================================================================================================================================
3167
3168 typedef struct shaderpermutationinfo_s
3169 {
3170         const char *pretext;
3171         const char *name;
3172 }
3173 shaderpermutationinfo_t;
3174
3175 typedef struct shadermodeinfo_s
3176 {
3177         const char *vertexfilename;
3178         const char *geometryfilename;
3179         const char *fragmentfilename;
3180         const char *pretext;
3181         const char *name;
3182 }
3183 shadermodeinfo_t;
3184
3185 typedef enum shaderpermutation_e
3186 {
3187         SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3188         SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3189         SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3190         SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3191         SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3192         SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3193         SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3194         SHADERPERMUTATION_GAMMARAMPS = 1<<7, ///< gamma (postprocessing only)
3195         SHADERPERMUTATION_CUBEFILTER = 1<<8, ///< (lightsource) use cubemap light filter
3196         SHADERPERMUTATION_GLOW = 1<<9, ///< (lightmap) blend in an additive glow texture
3197         SHADERPERMUTATION_BLOOM = 1<<10, ///< bloom (postprocessing only)
3198         SHADERPERMUTATION_SPECULAR = 1<<11, ///< (lightsource or deluxemapping) render specular effects
3199         SHADERPERMUTATION_POSTPROCESSING = 1<<12, ///< user defined postprocessing (postprocessing only)
3200         SHADERPERMUTATION_EXACTSPECULARMATH = 1<<13, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3201         SHADERPERMUTATION_REFLECTION = 1<<14, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3202         SHADERPERMUTATION_OFFSETMAPPING = 1<<15, ///< adjust texcoords to roughly simulate a displacement mapped surface
3203         SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<16, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3204         SHADERPERMUTATION_SHADOWMAPRECT = 1<<17, ///< (lightsource) use shadowmap rectangle texture as light filter
3205         SHADERPERMUTATION_SHADOWMAPCUBE = 1<<18, ///< (lightsource) use shadowmap cubemap texture as light filter
3206         SHADERPERMUTATION_SHADOWMAP2D = 1<<19, ///< (lightsource) use shadowmap rectangle texture as light filter
3207         SHADERPERMUTATION_SHADOWMAPPCF = 1<<20, ///< (lightsource) use percentage closer filtering on shadowmap test results
3208         SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<21, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3209         SHADERPERMUTATION_SHADOWSAMPLER = 1<<22, ///< (lightsource) use hardware shadowmap test
3210         SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<23, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3211         SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<24, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3212         SHADERPERMUTATION_ALPHAKILL = 1<<25, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3213         SHADERPERMUTATION_REFLECTCUBE = 1<<26, ///< fake reflections using global cubemap (not HDRI light probe)
3214         SHADERPERMUTATION_LIMIT = 1<<27, ///< size of permutations array
3215         SHADERPERMUTATION_COUNT = 27 ///< size of shaderpermutationinfo array
3216 }
3217 shaderpermutation_t;
3218
3219 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3220 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3221 {
3222         {"#define USEDIFFUSE\n", " diffuse"},
3223         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3224         {"#define USEVIEWTINT\n", " viewtint"},
3225         {"#define USECOLORMAPPING\n", " colormapping"},
3226         {"#define USESATURATION\n", " saturation"},
3227         {"#define USEFOGINSIDE\n", " foginside"},
3228         {"#define USEFOGOUTSIDE\n", " fogoutside"},
3229         {"#define USEGAMMARAMPS\n", " gammaramps"},
3230         {"#define USECUBEFILTER\n", " cubefilter"},
3231         {"#define USEGLOW\n", " glow"},
3232         {"#define USEBLOOM\n", " bloom"},
3233         {"#define USESPECULAR\n", " specular"},
3234         {"#define USEPOSTPROCESSING\n", " postprocessing"},
3235         {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3236         {"#define USEREFLECTION\n", " reflection"},
3237         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3238         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3239         {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3240         {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3241         {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3242         {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3243         {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3244         {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3245         {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3246         {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3247         {"#define USEALPHAKILL\n", " alphakill"},
3248         {"#define USEREFLECTCUBE\n", " reflectcube"},
3249 };
3250
3251 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3252 typedef enum shadermode_e
3253 {
3254         SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3255         SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3256         SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3257         SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3258         SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3259         SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3260         SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3261         SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3262         SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3263         SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3264         SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3265         SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3266         SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3267         SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3268         SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3269         SHADERMODE_COUNT
3270 }
3271 shadermode_t;
3272
3273 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3274 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3275 {
3276         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3277         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3278         {"glsl/default.glsl", NULL, NULL               , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3279         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3280         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3281         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3282         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3283         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3284         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3285         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3286         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3287         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3288         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3289         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3290         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3291 };
3292
3293 #ifdef SUPPORTCG
3294 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3295 {
3296         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3297         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3298         {"cg/default.cg", NULL, NULL           , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3299         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3300         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3301         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3302         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3303         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3304         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3305         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3306         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3307         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3308         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3309         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3310         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3311 };
3312 #endif
3313
3314 struct r_glsl_permutation_s;
3315 typedef struct r_glsl_permutation_s
3316 {
3317         /// hash lookup data
3318         struct r_glsl_permutation_s *hashnext;
3319         unsigned int mode;
3320         unsigned int permutation;
3321
3322         /// indicates if we have tried compiling this permutation already
3323         qboolean compiled;
3324         /// 0 if compilation failed
3325         int program;
3326         /// locations of detected uniforms in program object, or -1 if not found
3327         int loc_Texture_First;
3328         int loc_Texture_Second;
3329         int loc_Texture_GammaRamps;
3330         int loc_Texture_Normal;
3331         int loc_Texture_Color;
3332         int loc_Texture_Gloss;
3333         int loc_Texture_Glow;
3334         int loc_Texture_SecondaryNormal;
3335         int loc_Texture_SecondaryColor;
3336         int loc_Texture_SecondaryGloss;
3337         int loc_Texture_SecondaryGlow;
3338         int loc_Texture_Pants;
3339         int loc_Texture_Shirt;
3340         int loc_Texture_FogMask;
3341         int loc_Texture_Lightmap;
3342         int loc_Texture_Deluxemap;
3343         int loc_Texture_Attenuation;
3344         int loc_Texture_Cube;
3345         int loc_Texture_Refraction;
3346         int loc_Texture_Reflection;
3347         int loc_Texture_ShadowMapRect;
3348         int loc_Texture_ShadowMapCube;
3349         int loc_Texture_ShadowMap2D;
3350         int loc_Texture_CubeProjection;
3351         int loc_Texture_ScreenDepth;
3352         int loc_Texture_ScreenNormalMap;
3353         int loc_Texture_ScreenDiffuse;
3354         int loc_Texture_ScreenSpecular;
3355         int loc_Texture_ReflectMask;
3356         int loc_Texture_ReflectCube;
3357         int loc_Alpha;
3358         int loc_BloomBlur_Parameters;
3359         int loc_ClientTime;
3360         int loc_Color_Ambient;
3361         int loc_Color_Diffuse;
3362         int loc_Color_Specular;
3363         int loc_Color_Glow;
3364         int loc_Color_Pants;
3365         int loc_Color_Shirt;
3366         int loc_DeferredColor_Ambient;
3367         int loc_DeferredColor_Diffuse;
3368         int loc_DeferredColor_Specular;
3369         int loc_DeferredMod_Diffuse;
3370         int loc_DeferredMod_Specular;
3371         int loc_DistortScaleRefractReflect;
3372         int loc_EyePosition;
3373         int loc_FogColor;
3374         int loc_FogHeightFade;
3375         int loc_FogPlane;
3376         int loc_FogPlaneViewDist;
3377         int loc_FogRangeRecip;
3378         int loc_LightColor;
3379         int loc_LightDir;
3380         int loc_LightPosition;
3381         int loc_OffsetMapping_Scale;
3382         int loc_PixelSize;
3383         int loc_ReflectColor;
3384         int loc_ReflectFactor;
3385         int loc_ReflectOffset;
3386         int loc_RefractColor;
3387         int loc_Saturation;
3388         int loc_ScreenCenterRefractReflect;
3389         int loc_ScreenScaleRefractReflect;
3390         int loc_ScreenToDepth;
3391         int loc_ShadowMap_Parameters;
3392         int loc_ShadowMap_TextureScale;
3393         int loc_SpecularPower;
3394         int loc_UserVec1;
3395         int loc_UserVec2;
3396         int loc_UserVec3;
3397         int loc_UserVec4;
3398         int loc_ViewTintColor;
3399         int loc_ViewToLight;
3400         int loc_ModelToLight;
3401         int loc_TexMatrix;
3402         int loc_BackgroundTexMatrix;
3403         int loc_ModelViewProjectionMatrix;
3404         int loc_ModelViewMatrix;
3405         int loc_PixelToScreenTexCoord;
3406         int loc_ModelToReflectCube;
3407 }
3408 r_glsl_permutation_t;
3409
3410 #define SHADERPERMUTATION_HASHSIZE 256
3411
3412 /// information about each possible shader permutation
3413 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3414 /// currently selected permutation
3415 r_glsl_permutation_t *r_glsl_permutation;
3416 /// storage for permutations linked in the hash table
3417 memexpandablearray_t r_glsl_permutationarray;
3418
3419 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3420 {
3421         //unsigned int hashdepth = 0;
3422         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3423         r_glsl_permutation_t *p;
3424         for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3425         {
3426                 if (p->mode == mode && p->permutation == permutation)
3427                 {
3428                         //if (hashdepth > 10)
3429                         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3430                         return p;
3431                 }
3432                 //hashdepth++;
3433         }
3434         p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3435         p->mode = mode;
3436         p->permutation = permutation;
3437         p->hashnext = r_glsl_permutationhash[mode][hashindex];
3438         r_glsl_permutationhash[mode][hashindex] = p;
3439         //if (hashdepth > 10)
3440         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3441         return p;
3442 }
3443
3444 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3445 {
3446         char *shaderstring;
3447         if (!filename || !filename[0])
3448                 return NULL;
3449         if (!strcmp(filename, "glsl/default.glsl"))
3450         {
3451                 if (!glslshaderstring)
3452                 {
3453                         glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3454                         if (glslshaderstring)
3455                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
3456                         else
3457                                 glslshaderstring = (char *)builtinshaderstring;
3458                 }
3459                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3460                 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3461                 return shaderstring;
3462         }
3463         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3464         if (shaderstring)
3465         {
3466                 if (printfromdisknotice)
3467                         Con_DPrintf("from disk %s... ", filename);
3468                 return shaderstring;
3469         }
3470         return shaderstring;
3471 }
3472
3473 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3474 {
3475         int i;
3476         shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3477         int vertstrings_count = 0;
3478         int geomstrings_count = 0;
3479         int fragstrings_count = 0;
3480         char *vertexstring, *geometrystring, *fragmentstring;
3481         const char *vertstrings_list[32+3];
3482         const char *geomstrings_list[32+3];
3483         const char *fragstrings_list[32+3];
3484         char permutationname[256];
3485
3486         if (p->compiled)
3487                 return;
3488         p->compiled = true;
3489         p->program = 0;
3490
3491         permutationname[0] = 0;
3492         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
3493         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3494         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3495
3496         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3497
3498         // the first pretext is which type of shader to compile as
3499         // (later these will all be bound together as a program object)
3500         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3501         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3502         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3503
3504         // the second pretext is the mode (for example a light source)
3505         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3506         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3507         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3508         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3509
3510         // now add all the permutation pretexts
3511         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3512         {
3513                 if (permutation & (1<<i))
3514                 {
3515                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3516                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3517                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3518                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3519                 }
3520                 else
3521                 {
3522                         // keep line numbers correct
3523                         vertstrings_list[vertstrings_count++] = "\n";
3524                         geomstrings_list[geomstrings_count++] = "\n";
3525                         fragstrings_list[fragstrings_count++] = "\n";
3526                 }
3527         }
3528
3529         // now append the shader text itself
3530         vertstrings_list[vertstrings_count++] = vertexstring;
3531         geomstrings_list[geomstrings_count++] = geometrystring;
3532         fragstrings_list[fragstrings_count++] = fragmentstring;
3533
3534         // if any sources were NULL, clear the respective list
3535         if (!vertexstring)
3536                 vertstrings_count = 0;
3537         if (!geometrystring)
3538                 geomstrings_count = 0;
3539         if (!fragmentstring)
3540                 fragstrings_count = 0;
3541
3542         // compile the shader program
3543         if (vertstrings_count + geomstrings_count + fragstrings_count)
3544                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3545         if (p->program)
3546         {
3547                 CHECKGLERROR
3548                 qglUseProgramObjectARB(p->program);CHECKGLERROR
3549                 // look up all the uniform variable names we care about, so we don't
3550                 // have to look them up every time we set them
3551
3552                 p->loc_Texture_First              = qglGetUniformLocationARB(p->program, "Texture_First");
3553                 p->loc_Texture_Second             = qglGetUniformLocationARB(p->program, "Texture_Second");
3554                 p->loc_Texture_GammaRamps         = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3555                 p->loc_Texture_Normal             = qglGetUniformLocationARB(p->program, "Texture_Normal");
3556                 p->loc_Texture_Color              = qglGetUniformLocationARB(p->program, "Texture_Color");
3557                 p->loc_Texture_Gloss              = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3558                 p->loc_Texture_Glow               = qglGetUniformLocationARB(p->program, "Texture_Glow");
3559                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3560                 p->loc_Texture_SecondaryColor     = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3561                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3562                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3563                 p->loc_Texture_Pants              = qglGetUniformLocationARB(p->program, "Texture_Pants");
3564                 p->loc_Texture_Shirt              = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3565                 p->loc_Texture_FogMask            = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3566                 p->loc_Texture_Lightmap           = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3567                 p->loc_Texture_Deluxemap          = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3568                 p->loc_Texture_Attenuation        = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3569                 p->loc_Texture_Cube               = qglGetUniformLocationARB(p->program, "Texture_Cube");
3570                 p->loc_Texture_Refraction         = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3571                 p->loc_Texture_Reflection         = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3572                 p->loc_Texture_ShadowMapRect      = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3573                 p->loc_Texture_ShadowMapCube      = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3574                 p->loc_Texture_ShadowMap2D        = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3575                 p->loc_Texture_CubeProjection     = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3576                 p->loc_Texture_ScreenDepth        = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3577                 p->loc_Texture_ScreenNormalMap    = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3578                 p->loc_Texture_ScreenDiffuse      = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3579                 p->loc_Texture_ScreenSpecular     = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3580                 p->loc_Texture_ReflectMask        = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3581                 p->loc_Texture_ReflectCube        = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3582                 p->loc_Alpha                      = qglGetUniformLocationARB(p->program, "Alpha");
3583                 p->loc_BloomBlur_Parameters       = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3584                 p->loc_ClientTime                 = qglGetUniformLocationARB(p->program, "ClientTime");
3585                 p->loc_Color_Ambient              = qglGetUniformLocationARB(p->program, "Color_Ambient");
3586                 p->loc_Color_Diffuse              = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3587                 p->loc_Color_Specular             = qglGetUniformLocationARB(p->program, "Color_Specular");
3588                 p->loc_Color_Glow                 = qglGetUniformLocationARB(p->program, "Color_Glow");
3589                 p->loc_Color_Pants                = qglGetUniformLocationARB(p->program, "Color_Pants");
3590                 p->loc_Color_Shirt                = qglGetUniformLocationARB(p->program, "Color_Shirt");
3591                 p->loc_DeferredColor_Ambient      = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3592                 p->loc_DeferredColor_Diffuse      = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3593                 p->loc_DeferredColor_Specular     = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3594                 p->loc_DeferredMod_Diffuse        = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3595                 p->loc_DeferredMod_Specular       = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3596                 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3597                 p->loc_EyePosition                = qglGetUniformLocationARB(p->program, "EyePosition");
3598                 p->loc_FogColor                   = qglGetUniformLocationARB(p->program, "FogColor");
3599                 p->loc_FogHeightFade              = qglGetUniformLocationARB(p->program, "FogHeightFade");
3600                 p->loc_FogPlane                   = qglGetUniformLocationARB(p->program, "FogPlane");
3601                 p->loc_FogPlaneViewDist           = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3602                 p->loc_FogRangeRecip              = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3603                 p->loc_LightColor                 = qglGetUniformLocationARB(p->program, "LightColor");
3604                 p->loc_LightDir                   = qglGetUniformLocationARB(p->program, "LightDir");
3605                 p->loc_LightPosition              = qglGetUniformLocationARB(p->program, "LightPosition");
3606                 p->loc_OffsetMapping_Scale        = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3607                 p->loc_PixelSize                  = qglGetUniformLocationARB(p->program, "PixelSize");
3608                 p->loc_ReflectColor               = qglGetUniformLocationARB(p->program, "ReflectColor");
3609                 p->loc_ReflectFactor              = qglGetUniformLocationARB(p->program, "ReflectFactor");
3610                 p->loc_ReflectOffset              = qglGetUniformLocationARB(p->program, "ReflectOffset");
3611                 p->loc_RefractColor               = qglGetUniformLocationARB(p->program, "RefractColor");
3612                 p->loc_Saturation                 = qglGetUniformLocationARB(p->program, "Saturation");
3613                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3614                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3615                 p->loc_ScreenToDepth              = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3616                 p->loc_ShadowMap_Parameters       = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3617                 p->loc_ShadowMap_TextureScale     = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3618                 p->loc_SpecularPower              = qglGetUniformLocationARB(p->program, "SpecularPower");
3619                 p->loc_UserVec1                   = qglGetUniformLocationARB(p->program, "UserVec1");
3620                 p->loc_UserVec2                   = qglGetUniformLocationARB(p->program, "UserVec2");
3621                 p->loc_UserVec3                   = qglGetUniformLocationARB(p->program, "UserVec3");
3622                 p->loc_UserVec4                   = qglGetUniformLocationARB(p->program, "UserVec4");
3623                 p->loc_ViewTintColor              = qglGetUniformLocationARB(p->program, "ViewTintColor");
3624                 p->loc_ViewToLight                = qglGetUniformLocationARB(p->program, "ViewToLight");
3625                 p->loc_ModelToLight               = qglGetUniformLocationARB(p->program, "ModelToLight");
3626                 p->loc_TexMatrix                  = qglGetUniformLocationARB(p->program, "TexMatrix");
3627                 p->loc_BackgroundTexMatrix        = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3628                 p->loc_ModelViewMatrix            = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3629                 p->loc_ModelViewProjectionMatrix  = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3630                 p->loc_PixelToScreenTexCoord      = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3631                 p->loc_ModelToReflectCube         = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3632                 // initialize the samplers to refer to the texture units we use
3633                 if (p->loc_Texture_First           >= 0) qglUniform1iARB(p->loc_Texture_First          , GL20TU_FIRST);
3634                 if (p->loc_Texture_Second          >= 0) qglUniform1iARB(p->loc_Texture_Second         , GL20TU_SECOND);
3635                 if (p->loc_Texture_GammaRamps      >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps     , GL20TU_GAMMARAMPS);
3636                 if (p->loc_Texture_Normal          >= 0) qglUniform1iARB(p->loc_Texture_Normal         , GL20TU_NORMAL);
3637                 if (p->loc_Texture_Color           >= 0) qglUniform1iARB(p->loc_Texture_Color          , GL20TU_COLOR);
3638                 if (p->loc_Texture_Gloss           >= 0) qglUniform1iARB(p->loc_Texture_Gloss          , GL20TU_GLOSS);
3639                 if (p->loc_Texture_Glow            >= 0) qglUniform1iARB(p->loc_Texture_Glow           , GL20TU_GLOW);
3640                 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3641                 if (p->loc_Texture_SecondaryColor  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3642                 if (p->loc_Texture_SecondaryGloss  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3643                 if (p->loc_Texture_SecondaryGlow   >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow  , GL20TU_SECONDARY_GLOW);
3644                 if (p->loc_Texture_Pants           >= 0) qglUniform1iARB(p->loc_Texture_Pants          , GL20TU_PANTS);
3645                 if (p->loc_Texture_Shirt           >= 0) qglUniform1iARB(p->loc_Texture_Shirt          , GL20TU_SHIRT);
3646                 if (p->loc_Texture_FogMask         >= 0) qglUniform1iARB(p->loc_Texture_FogMask        , GL20TU_FOGMASK);
3647                 if (p->loc_Texture_Lightmap        >= 0) qglUniform1iARB(p->loc_Texture_Lightmap       , GL20TU_LIGHTMAP);
3648                 if (p->loc_Texture_Deluxemap       >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap      , GL20TU_DELUXEMAP);
3649                 if (p->loc_Texture_Attenuation     >= 0) qglUniform1iARB(p->loc_Texture_Attenuation    , GL20TU_ATTENUATION);
3650                 if (p->loc_Texture_Cube            >= 0) qglUniform1iARB(p->loc_Texture_Cube           , GL20TU_CUBE);
3651                 if (p->loc_Texture_Refraction      >= 0) qglUniform1iARB(p->loc_Texture_Refraction     , GL20TU_REFRACTION);
3652                 if (p->loc_Texture_Reflection      >= 0) qglUniform1iARB(p->loc_Texture_Reflection     , GL20TU_REFLECTION);
3653                 if (p->loc_Texture_ShadowMapRect   >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect  , GL20TU_SHADOWMAPRECT);
3654                 if (p->loc_Texture_ShadowMapCube   >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube  , GL20TU_SHADOWMAPCUBE);
3655                 if (p->loc_Texture_ShadowMap2D     >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D    , GL20TU_SHADOWMAP2D);
3656                 if (p->loc_Texture_CubeProjection  >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3657                 if (p->loc_Texture_ScreenDepth     >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth    , GL20TU_SCREENDEPTH);
3658                 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3659                 if (p->loc_Texture_ScreenDiffuse   >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse  , GL20TU_SCREENDIFFUSE);
3660                 if (p->loc_Texture_ScreenSpecular  >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3661                 if (p->loc_Texture_ReflectMask     >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask    , GL20TU_REFLECTMASK);
3662                 if (p->loc_Texture_ReflectCube     >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube    , GL20TU_REFLECTCUBE);
3663                 CHECKGLERROR
3664                 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3665         }
3666         else
3667                 Con_Printf("^1GLSL shader %s failed!  some features may not work properly.\n", permutationname);
3668
3669         // free the strings
3670         if (vertexstring)
3671                 Mem_Free(vertexstring);
3672         if (geometrystring)
3673                 Mem_Free(geometrystring);
3674         if (fragmentstring)
3675                 Mem_Free(fragmentstring);
3676 }
3677
3678 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3679 {
3680         r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3681         if (r_glsl_permutation != perm)
3682         {
3683                 r_glsl_permutation = perm;
3684                 if (!r_glsl_permutation->program)
3685                 {
3686                         if (!r_glsl_permutation->compiled)
3687                                 R_GLSL_CompilePermutation(perm, mode, permutation);
3688                         if (!r_glsl_permutation->program)
3689                         {
3690                                 // remove features until we find a valid permutation
3691                                 int i;
3692                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3693                                 {
3694                                         // reduce i more quickly whenever it would not remove any bits
3695                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3696                                         if (!(permutation & j))
3697                                                 continue;
3698                                         permutation -= j;
3699                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3700                                         if (!r_glsl_permutation->compiled)
3701                                                 R_GLSL_CompilePermutation(perm, mode, permutation);
3702                                         if (r_glsl_permutation->program)
3703                                                 break;
3704                                 }
3705                                 if (i >= SHADERPERMUTATION_COUNT)
3706                                 {
3707                                         //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3708                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3709                                         qglUseProgramObjectARB(0);CHECKGLERROR
3710                                         return; // no bit left to clear, entire mode is broken
3711                                 }
3712                         }
3713                 }
3714                 CHECKGLERROR
3715                 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3716         }
3717         if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3718         if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3719 }
3720
3721 #ifdef SUPPORTCG
3722 #include <Cg/cgGL.h>
3723 struct r_cg_permutation_s;
3724 typedef struct r_cg_permutation_s
3725 {
3726         /// hash lookup data
3727         struct r_cg_permutation_s *hashnext;
3728         unsigned int mode;
3729         unsigned int permutation;
3730
3731         /// indicates if we have tried compiling this permutation already
3732         qboolean compiled;
3733         /// 0 if compilation failed
3734         CGprogram vprogram;
3735         CGprogram fprogram;
3736         /// locations of detected parameters in programs, or NULL if not found
3737         CGparameter vp_EyePosition;
3738         CGparameter vp_FogPlane;
3739         CGparameter vp_LightDir;
3740         CGparameter vp_LightPosition;
3741         CGparameter vp_ModelToLight;
3742         CGparameter vp_TexMatrix;
3743         CGparameter vp_BackgroundTexMatrix;
3744         CGparameter vp_ModelViewProjectionMatrix;
3745         CGparameter vp_ModelViewMatrix;
3746
3747         CGparameter fp_Texture_First;
3748         CGparameter fp_Texture_Second;
3749         CGparameter fp_Texture_GammaRamps;
3750         CGparameter fp_Texture_Normal;
3751         CGparameter fp_Texture_Color;
3752         CGparameter fp_Texture_Gloss;
3753         CGparameter fp_Texture_Glow;
3754         CGparameter fp_Texture_SecondaryNormal;
3755         CGparameter fp_Texture_SecondaryColor;
3756         CGparameter fp_Texture_SecondaryGloss;
3757         CGparameter fp_Texture_SecondaryGlow;
3758         CGparameter fp_Texture_Pants;
3759         CGparameter fp_Texture_Shirt;
3760         CGparameter fp_Texture_FogMask;
3761         CGparameter fp_Texture_Lightmap;
3762         CGparameter fp_Texture_Deluxemap;
3763         CGparameter fp_Texture_Attenuation;
3764         CGparameter fp_Texture_Cube;
3765         CGparameter fp_Texture_Refraction;
3766         CGparameter fp_Texture_Reflection;
3767         CGparameter fp_Texture_ShadowMapRect;
3768         CGparameter fp_Texture_ShadowMapCube;
3769         CGparameter fp_Texture_ShadowMap2D;
3770         CGparameter fp_Texture_CubeProjection;
3771         CGparameter fp_Texture_ScreenDepth;
3772         CGparameter fp_Texture_ScreenNormalMap;
3773         CGparameter fp_Texture_ScreenDiffuse;
3774         CGparameter fp_Texture_ScreenSpecular;
3775         CGparameter fp_Texture_ReflectMask;
3776         CGparameter fp_Texture_ReflectCube;
3777         CGparameter fp_Alpha;
3778         CGparameter fp_BloomBlur_Parameters;
3779         CGparameter fp_ClientTime;
3780         CGparameter fp_Color_Ambient;
3781         CGparameter fp_Color_Diffuse;
3782         CGparameter fp_Color_Specular;
3783         CGparameter fp_Color_Glow;
3784         CGparameter fp_Color_Pants;
3785         CGparameter fp_Color_Shirt;
3786         CGparameter fp_DeferredColor_Ambient;
3787         CGparameter fp_DeferredColor_Diffuse;
3788         CGparameter fp_DeferredColor_Specular;
3789         CGparameter fp_DeferredMod_Diffuse;
3790         CGparameter fp_DeferredMod_Specular;
3791         CGparameter fp_DistortScaleRefractReflect;
3792         CGparameter fp_EyePosition;
3793         CGparameter fp_FogColor;
3794         CGparameter fp_FogHeightFade;
3795         CGparameter fp_FogPlane;
3796         CGparameter fp_FogPlaneViewDist;
3797         CGparameter fp_FogRangeRecip;
3798         CGparameter fp_LightColor;
3799         CGparameter fp_LightDir;
3800         CGparameter fp_LightPosition;
3801         CGparameter fp_OffsetMapping_Scale;
3802         CGparameter fp_PixelSize;
3803         CGparameter fp_ReflectColor;
3804         CGparameter fp_ReflectFactor;
3805         CGparameter fp_ReflectOffset;
3806         CGparameter fp_RefractColor;
3807         CGparameter fp_Saturation;
3808         CGparameter fp_ScreenCenterRefractReflect;
3809         CGparameter fp_ScreenScaleRefractReflect;
3810         CGparameter fp_ScreenToDepth;
3811         CGparameter fp_ShadowMap_Parameters;
3812         CGparameter fp_ShadowMap_TextureScale;
3813         CGparameter fp_SpecularPower;
3814         CGparameter fp_UserVec1;
3815         CGparameter fp_UserVec2;
3816         CGparameter fp_UserVec3;
3817         CGparameter fp_UserVec4;
3818         CGparameter fp_ViewTintColor;
3819         CGparameter fp_ViewToLight;
3820         CGparameter fp_PixelToScreenTexCoord;
3821         CGparameter fp_ModelToReflectCube;
3822 }
3823 r_cg_permutation_t;
3824
3825 /// information about each possible shader permutation
3826 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3827 /// currently selected permutation
3828 r_cg_permutation_t *r_cg_permutation;
3829 /// storage for permutations linked in the hash table
3830 memexpandablearray_t r_cg_permutationarray;
3831
3832 #define CHECKCGERROR {CGerror err = cgGetError(), err2 = err;if (err){Con_Printf("%s:%i CG error %i: %s : %s\n", __FILE__, __LINE__, err, cgGetErrorString(err), cgGetLastErrorString(&err2));if (err == 1) Con_Printf("last listing:\n%s\n", cgGetLastListing(vid.cgcontext));}}
3833
3834 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
3835 {
3836         //unsigned int hashdepth = 0;
3837         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3838         r_cg_permutation_t *p;
3839         for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
3840         {
3841                 if (p->mode == mode && p->permutation == permutation)
3842                 {
3843                         //if (hashdepth > 10)
3844                         //      Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3845                         return p;
3846                 }
3847                 //hashdepth++;
3848         }
3849         p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
3850         p->mode = mode;
3851         p->permutation = permutation;
3852         p->hashnext = r_cg_permutationhash[mode][hashindex];
3853         r_cg_permutationhash[mode][hashindex] = p;
3854         //if (hashdepth > 10)
3855         //      Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3856         return p;
3857 }
3858
3859 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
3860 {
3861         char *shaderstring;
3862         if (!filename || !filename[0])
3863                 return NULL;
3864         if (!strcmp(filename, "cg/default.cg"))
3865         {
3866                 if (!cgshaderstring)
3867                 {
3868                         cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3869                         if (cgshaderstring)
3870                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
3871                         else
3872                                 cgshaderstring = (char *)builtincgshaderstring;
3873                 }
3874                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
3875                 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
3876                 return shaderstring;
3877         }
3878         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3879         if (shaderstring)
3880         {
3881                 if (printfromdisknotice)
3882                         Con_DPrintf("from disk %s... ", filename);
3883                 return shaderstring;
3884         }
3885         return shaderstring;
3886 }
3887
3888 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
3889 {
3890         // TODO: load or create .fp and .vp shader files
3891 }
3892
3893 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
3894 {
3895         int i;
3896         shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
3897         int vertstrings_count = 0, vertstring_length = 0;
3898         int geomstrings_count = 0, geomstring_length = 0;
3899         int fragstrings_count = 0, fragstring_length = 0;
3900         char *t;
3901         char *vertexstring, *geometrystring, *fragmentstring;
3902         char *vertstring, *geomstring, *fragstring;
3903         const char *vertstrings_list[32+3];
3904         const char *geomstrings_list[32+3];
3905         const char *fragstrings_list[32+3];
3906         char permutationname[256];
3907         char cachename[256];
3908         CGprofile vertexProfile;
3909         CGprofile fragmentProfile;
3910
3911         if (p->compiled)
3912                 return;
3913         p->compiled = true;
3914         p->vprogram = NULL;
3915         p->fprogram = NULL;
3916
3917         permutationname[0] = 0;
3918         cachename[0] = 0;
3919         vertexstring   = R_CG_GetText(modeinfo->vertexfilename, true);
3920         geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
3921         fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
3922
3923         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3924         strlcat(cachename, "cg/", sizeof(cachename));
3925
3926         // the first pretext is which type of shader to compile as
3927         // (later these will all be bound together as a program object)
3928         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3929         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3930         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3931
3932         // the second pretext is the mode (for example a light source)
3933         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3934         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3935         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3936         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3937         strlcat(cachename, modeinfo->name, sizeof(cachename));
3938
3939         // now add all the permutation pretexts
3940         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3941         {
3942                 if (permutation & (1<<i))
3943                 {
3944                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3945                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3946                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3947                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3948                         strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
3949                 }
3950                 else
3951                 {
3952                         // keep line numbers correct
3953                         vertstrings_list[vertstrings_count++] = "\n";
3954                         geomstrings_list[geomstrings_count++] = "\n";
3955                         fragstrings_list[fragstrings_count++] = "\n";
3956                 }
3957         }
3958
3959         // replace spaces in the cachename with _ characters
3960         for (i = 0;cachename[i];i++)
3961                 if (cachename[i] == ' ')
3962                         cachename[i] = '_';
3963
3964         // now append the shader text itself
3965         vertstrings_list[vertstrings_count++] = vertexstring;
3966         geomstrings_list[geomstrings_count++] = geometrystring;
3967         fragstrings_list[fragstrings_count++] = fragmentstring;
3968
3969         // if any sources were NULL, clear the respective list
3970         if (!vertexstring)
3971                 vertstrings_count = 0;
3972         if (!geometrystring)
3973                 geomstrings_count = 0;
3974         if (!fragmentstring)
3975                 fragstrings_count = 0;
3976
3977         vertstring_length = 0;
3978         for (i = 0;i < vertstrings_count;i++)
3979                 vertstring_length += strlen(vertstrings_list[i]);
3980         vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
3981         for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
3982                 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
3983
3984         geomstring_length = 0;
3985         for (i = 0